<template>
  <n-spin :show="show" description="正在从服务器查询信息...">
    <n-grid cols="2 s:2 m:2 l:2 xl:2 2xl:2" 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="iosPay">
            <n-radio-group v-model:value="formValue.iosPay" name="iosPay">
              <n-space>
                <n-radio :value="1">开启支付</n-radio>
                <n-radio :value="0">关闭支付</n-radio>
              </n-space>
            </n-radio-group>
          </n-form-item>-->

          <n-form-item label="苹果开启等级" path="playerLevel">
            <n-input-number
              placeholder="请输入开启等级"
              :min="1"
              v-model:value="formValue.iosOpenLevel"
            />
            <n-space>
              <template #feedback>
                开启支付后，IOS玩家等级大于等于当前设置的开启等级时才会显示相应支付商品
              </template>
            </n-space>
          </n-form-item>

          <!--          <n-form-item label="安卓支付开关" path="andrPay">
            <n-radio-group v-model:value="formValue.andrPay" name="andrPay">
              <n-space>
                <n-radio :value="1">米大师支付</n-radio>
                <n-radio :value="2">微信支付</n-radio>
                <n-radio :value="3">混合支付</n-radio>
                <n-radio :value="0">关闭支付</n-radio>
              </n-space>
            </n-radio-group>
          </n-form-item>-->

          <!--          <n-form-item label="安卓开启等级" path="andrOpenLevel">
            <n-input-number
              placeholder="请输入开启等级"
              :min="1"
              v-model:value="formValue.andrOpenLevel"
            />
            <template #feedback>
              开启支付后，IOS玩家等级大于等于当前设置的开启等级时才会显示相应支付商品
            </template>
          </n-form-item>-->

          <div>
            <br />
            <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 { GetPayConfig, 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 useUserStore = useUserStoreWidthOut();
      const formRef: any = ref(null);
      const message = useMessage();
      const router = useRouter();
      const show = ref(false);
      const data = ref({});
      const state = reactive({
        formValue: {
          // serverId: 1,
          // iosPay: 0,
          iosOpenLevel: 0,
          // andrPay: 0,
          // andrOpenLevel: 1,
        },
      });

      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;
        }

        try {
          console.log('查询开关信息');
          getSocket().send(
            JSON.stringify({
              type: SocketEnum.TypeQuerySwitcher,
              // data: state.formValue.serverId.toString(),
            })
          );
        } catch (_err) {
          console.log('错误信息：' + _err.message);

          setTimeout(function () {
            message.error('socket连接被断开，正在尝试恢复....');
            getSocket().send(
              JSON.stringify({
                type: SocketEnum.TypeQuerySwitcher,
                // data: state.formValue.serverId.toString(),
              })
            );
            message.success('socket已恢复');
          }, 1000);
        }
      }

      // async function queryGuide() {
      //   const res = await GetPayConfig();
      //   console.log('res:' + JSON.stringify(res));
      //   state.formValue.iosOpenLevel = res.iosOpenLevel;
      // }

      onMounted(async () => {
        // await queryGuide();
        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.playerLevel = data.value.openLevel;
            // state.formValue.iosPay = data.value.iosPay;
            // state.formValue.andrPay = data.value.andrPay;
            // state.formValue.andrOpenLevel = data.value.andrOpenLevel;
            state.formValue.iosOpenLevel = data.value.iosOpenLevel;
          } 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>
