<template>
  <section class="settings">
    <el-form label-position="top" class="w100">
      <el-form-item label="语言模型">
        <el-row class="flexWrap">
          <ai-model v-for="m in models" :model="m" small :class="{active:settings.model.id==m.id}"
                    @click="settings.model=m"/>
        </el-row>
      </el-form-item>
      <el-form-item label="流式输出">
        <el-switch v-model="settings.stream" :active-value="true" :inactive-value="false"/>
      </el-form-item>
      <el-form-item label="API KEY">
        <el-input v-model="settings.model.apiKey" clearable @change="v=>settings.model.setApiKey(v),getModelAccount()"/>
      </el-form-item>
      <el-row v-loading="loadingAccount" element-loading-background="#272A37">
        <el-form-item label="账号用户" class="fill">{{ account.username }}</el-form-item>
        <el-form-item label="账户余额" class="fill">{{ [account.usage, account.total].join(" / ") }}</el-form-item>
        <el-button type="text" @click="getModelAccount">刷新</el-button>
      </el-row>
    </el-form>
  </section>
</template>

<script>
import AiModel from "../ui/AiModel";
import AiSelect from "../ui/AiSelect";
import * as models from "../utils/models";


export default {
  name: "settings",
  components: {AiModel, AiSelect},
  props: {
    modelValue: {default: () => ({})}
  },
  emits: ["update:modelValue"],
  data() {
    return {
      settings: {},
      loadingAccount: false
    }
  },
  watch: {
    modelValue: {
      immediate: true,
      handler(v) {
        this.settings = v
      }
    }
  },
  computed: {
    models: () => Object.values(models).map((model => new model())),
    account: v => v.settings.account || {usage: 0, total: 0}
  },
  methods: {
    getModelAccount() {
      const ai = this.settings.model
      if (ai.getAccount) {
        this.loadingAccount = true
        ai.getAccount().then(v => this.settings.account = v).finally(() => this.loadingAccount = false)
      }
    }
  },
  created() {
  }
}
</script>

<style lang="scss" scoped>
.settings {
  min-width: 400px;

  :deep(.el-form) {
    .el-form-item__label {
      color: #bbb;
    }

    .el-form-item__content {
      color: white;
    }

    .el-input__wrapper {
      background-color: transparent;

      & > input {
        color: white;
      }
    }

    .AiModel {
      padding: 8px;
      border: 1px solid transparent;
      cursor: pointer;
      user-select: none;

      &.active {
        border-color: #409EFF;
        border-radius: 4px;
      }
    }
  }
}
</style>
