<template>
  <div>
    <n-spin :show="show" description="请稍候...">
      <n-form :label-width="100" :model="formValue" :rules="rules" ref="formRef">
        <n-form-item label="登录白名单" path="player_ids">
          <n-select multiple v-model:value="formValue.server_ids" :options="serverOptions" />
        </n-form-item>
        <n-form-item label="登录白名单" path="player_ids">
          <n-input type="textarea" v-model:value="formValue.player_ids" placeholder="" clearable />
          <template #feedback>
            填写账号ID，多个玩家请用,（英文逗号）隔开，清空时则是开放所有玩家登录</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 { EditWhiteListServer, GetWhiteListServer } from '@/api/account/list';
  import { useUserStoreWidthOut } from '@/store/modules/user';

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

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

  };

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

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

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

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