<template>
  <div>
    <n-spin :show="show" description="请稍候...">
      <n-form :label-width="100" :model="formValue" :rules="rules" ref="formRef">
        <n-form-item label="服务器" path="serverId">
          <n-select multiple v-model:value="formValue.server_ids" :options="serverOptions" />
          <template #feedback> 选择多个服务器时，会随机其中一个作为默认引流服务器</template>
        </n-form-item>
        <br />

        <div>
          <n-space>
            <n-button type="primary" @click="formSubmit">保存</n-button>
          </n-space>
        </div>
      </n-form>
    </n-spin>
  </div>
</template>

<script lang="ts" setup>
  import { onMounted, ref } from 'vue';
  import { useMessage } from 'naive-ui';
  import { useUserStoreWidthOut } from '@/store/modules/user';
  import { EditDrainageServer, GetDrainageServer } from '@/api/account/list';

  const useUserStore = useUserStoreWidthOut();
  const show = ref(false);
  const formRef: any = ref(null);
  const message = useMessage();

  const rules = {
    server_ids: {
      required: true,
      message: '请选择服务器',
      trigger: 'blur',
    },
  };

  const formValue = ref({
    server_ids: '',
  });

  function formSubmit() {
    formRef.value.validate((errors) => {
      if (!errors) {
        EditDrainageServer(formValue.value).then((_res) => {
          message.success('更新成功');
          load();
        });
      } else {
        message.error('验证失败，请填写完整信息');
      }
    });
  }

  onMounted(() => {
    load();
  });

  const serverOptions = useUserStore.config.server_simple_option;

  function load() {
    show.value = true;
    new Promise((_resolve, _reject) => {
      GetDrainageServer()
        .then((res) => {
          console.log('res:' + JSON.stringify(res));
          formValue.value.server_ids = res;
        })
        .finally(() => {
          show.value = false;
        });
    });
  }
</script>
