<template>
  <n-spin :show="show" description="正在从服务器查询信息...">
    <n-grid cols="2 s:2 m:2 l:3 xl:3 2xl:3" responsive="screen">
      <n-grid-item>
        <n-form :label-width="80" :model="formValue" ref="formRef">
          <n-form-item label="服务器" path="serverId">
            <n-select v-model:value="formValue.serverId" :options="serverOptions"  @update:value="handleUpdateValue"/>
          </n-form-item>
          <n-form-item label="收益开放等级" path="adOpenLevel">
            <n-input-number v-model:value="formValue.adOpenLevel" placeholder="" />
          </n-form-item>

          <n-form-item label="收益次数" path="doubleAd">
            <n-input-number placeholder="" v-model:value="formValue.doubleAd" />
          </n-form-item>

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

<script lang="ts">
  import { defineComponent, inject, onMounted, reactive, ref, toRefs } from 'vue';
  import { useMessage } from 'naive-ui';
  import { updateSwitchers } from '@/api/account/list';
  import { addOnMessage, getSocket } from '@/utils/websocket';
  import { SocketEnum } from '@/enums/socketEnum';
  import { useRouter } from 'vue-router';
  import {useUserStoreWidthOut} from "@/store/modules/user";

  export default defineComponent({
    setup() {
      const formRef: any = ref(null);
      const message = useMessage();
      const router = useRouter();
      const useUserStore = useUserStoreWidthOut();
      const show = ref(false);

      const data = ref({});

      const state = reactive({
        formValue: {
          serverId: 1,
          adOpenLevel: 0,
          doubleAd: 0,
        },
      });

      function formSubmit() {
        formRef.value.validate((errors) => {
          if (!errors) {
            updateSwitchers(state.formValue)
              .then((res) => {
                console.log('res:' + JSON.stringify(res));
                message.success('保存成功');
              })
              .catch((error) => {
                message.error(error.toString());
              });
          } else {
            message.error('验证失败，请填写完整信息');
          }
        });
      }

      function resetForm() {
        formRef.value.restoreValidation();
      }

      function queryGuide() {
        show.value = true;

        if (getSocket() === undefined) {
          message.error('socket连接异常，请重试！');
          router.push({ name: 'account-list' });
          return;
        }
        getSocket().send(
          JSON.stringify({
            type: SocketEnum.TypeQuerySwitcher,
            data: state.formValue.serverId.toString(),
          })
        );
      }

      onMounted(async () => {
        queryGuide();
      });

      const onMessageList = inject('onMessageList');
      const querySwitcher = (res) => {
        const data = JSON.parse(res.data);
        if (data.type !== SocketEnum.TypeQuerySwitcher) {
          return;
        }

        show.value = false;

        if (data.code == SocketEnum.CodeErr) {
          message.error('查询服务出错，cid:' + data.cid);
          router.push({ name: 'account-list' });
          return;
        }
        if (data.msg !== undefined && data.msg !== null) {
          try {
            data.value = JSON.parse(data.msg);
            state.formValue.adOpenLevel = data.value.adOpenLevel;
            state.formValue.doubleAd = data.value.doubleAd;

          } catch (e) {
            message.error('查询服务出错，' + data.msg);
          }
        }
      };

      addOnMessage(onMessageList, querySwitcher);

      function handleUpdateValue(value: string, _option) {
        queryGuide();
      }

      const serverOptions = useUserStore.config.server_simple_option;
      return {
        formRef,
        ...toRefs(state),
        formSubmit,
        resetForm,
        show,
        data,
        serverOptions,
        handleUpdateValue,
      };
    },
  });
</script>
