<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 />
        <n-form-item label="开放服务器最大ID" path="maxOpendServerId">
          <n-input-number placeholder="" v-model:value="formValue.maxOpendServerId" />
        </n-form-item>
        <br />
        <n-form-item label="新部署服务器最大ID" path="maxDeployServerId">
          <n-input-number placeholder="" v-model:value="formValue.maxDeployServerId" />
        </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 { EditDisplayServer, GetDisplayServer } 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: '',
    maxOpendServerId: 0,
    maxDeployServerId: 0,
  });

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

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

  const serverOptions = useUserStore.config.server_json_option;

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