<template>
  <div>
    <n-card :bordered="false" class="proCard" title="无尽排行">
      <BasicForm @register="register" @submit="handleSubmit" @reset="handleReset">
        <template #statusSlot="{ model, field }">
          <n-input v-model:value="model[field]" />
        </template>
      </BasicForm>

      <n-spin :show="show" description="正在从服务器拉取信息...">
        <BasicTable
          :loading="loading"
          :columns="columns"
          :data-source="dataSource"
          :row-key="(row) => row.id"
          ref="actionRef"
          :actionColumn="actionColumn"
          @update:checked-row-keys="onCheckedRow"
          :scroll-x="1090"
          :resizeHeightOffset="-10000"
          :pagination="false"
        >
          <template #tableTitle>
            <n-button type="primary" @click="addTable"> 调整玩家排行榜 </n-button>
          </template>
        </BasicTable>
      </n-spin>

      <n-modal
        v-model:show="showModal"
        :show-icon="false"
        preset="dialog"
        :title="title"
        style="width: 620px"
      >
        <n-form
          :model="formParams"
          ref="formRef"
          label-placement="left"
          :label-width="80"
          class="py-4"
        >
          <n-form-item label="玩家ID" path="playId">
            <n-input-number placeholder="请输入玩家ID" v-model:value="formParams.playId" />
          </n-form-item>
          <n-form-item label="通过房间数" path="roomCount">
            <n-input-number
              placeholder="通过房间数"
              v-model:value="formParams.roomCount"
              :min="0"
            />
          </n-form-item>

          <n-form-item label="最大房间数" path="maxRoomCount">
            <n-input-number
              placeholder="请输入最大房间数"
              v-model:value="formParams.maxRoomCount"
              :min="0"
            />
          </n-form-item>
        </n-form>

        <template #action>
          <n-space>
            <n-button @click="() => (showModal = false)">取消</n-button>
            <n-button type="info" :loading="formBtnLoading" @click="confirmForm">确定</n-button>
          </n-space>
        </template>
      </n-modal>
    </n-card>
    <UserModal ref="userModalRef" :userId="userId" />
  </div>
</template>

<script lang="ts" setup>
  import { h, inject, onMounted, reactive, ref } from 'vue';
  import { useMessage } from 'naive-ui';
  import { BasicTable, TableAction } from '@/components/Table';
  import { BasicForm, FormSchema, useForm } from '@/components/Form/index';
  import { updateElRank } from '@/api/echarts/rechargeList';
  import { columns } from './columns';
  import { useRouter } from 'vue-router';
  import { addOnMessage, getSocket } from '@/utils/websocket';
  import { SocketEnum } from '@/enums/socketEnum';
  import UserModal from '@/views/account/accountList/modal.vue';
  import { useUserStoreWidthOut } from '@/store/modules/user';

  const queryTableParames = ref({ limit: 20 });
  const params = ref({
    pageSize: 10,
    limit: 20,
    server_id: 1,
  });

  const useUserStore = useUserStoreWidthOut();
  const schemas: FormSchema[] = [
    {
      field: 'server_id',
      component: 'NSelect',
      label: '服务器',
      componentProps: {
        placeholder: '请选择服务器',
        defaultValue: params.value.server_id,
        options: useUserStore.config.server_simple_option,
        onUpdateValue: (e: any) => {
          console.log(e);
          params.value.server_id = e;
        },
      },
    },
    {
      field: 'limit',
      component: 'NInputNumber',
      label: '查询排名',
      componentProps: {
        placeholder: '请输入查询排行前几名',
        onUpdateValue: (e: any) => {
          console.log(e);
          queryTableParames.value.limit = e;
        },
        defaultValue: queryTableParames.value.limit,
        min: 1,
        max: 200,
      },
    },
  ];

  const dataSource = ref([]);
  const router = useRouter();
  const formRef: any = ref(null);
  const message = useMessage();
  const actionRef = ref();
  const show = ref(true);

  const loading = ref(false);

  const [register, {}] = useForm({
    gridProps: { cols: '1 s:1 m:2 l:3 xl:4 2xl:4' },
    labelWidth: 80,
    schemas,
  });

  function onCheckedRow(rowKeys) {
    console.log(rowKeys);
  }

  function handleSubmit(values: Recordable) {
    console.log(values);
    queryElrank();
  }

  function handleReset(values: Recordable) {
    console.log(values);
  }

  const showModal = ref(false);
  const formBtnLoading = ref(false);
  let formParams = reactive<any>({
    playId: '',
    roomCount: 0,
    maxRoomCount: 0,
  });

  function addTable() {
    formParams.playId = null;
    formParams.roomCount = null;
    formParams.maxRoomCount = null;
    showModal.value = true;
  }

  function confirmForm(e) {
    e.preventDefault();

    formRef.value.validate((errors) => {
      if (!errors) {
        console.log('formParams:' + JSON.stringify(formParams));

        if (formParams.playId === null || formParams.playId < 0) {
          message.error('请输入玩家ID');
          return;
        }
        if (formParams.roomCount === null || formParams.roomCount < 0) {
          message.error('请输入通关房间数量');
          return;
        }

        updateElRank({
          playId: formParams.playId,
          roomCount: formParams.roomCount,
          maxRoomCount: formParams.maxRoomCount,
          server_id: params.value.server_id,
        })
          .then((_res) => {
            console.log('_res:' + JSON.stringify(_res));
            message.success('已提交后台处理,添加成功后会推送系统消息，刷新玩家信息查看结果');
          })
          .catch((e: Error) => {
            message.error(e.message ?? '操作失败');
          });

        setTimeout(() => {
          showModal.value = false;
          queryElrank();
        });
      } else {
        message.error('请填写完整信息');
      }
      formBtnLoading.value = false;
    });
  }

  function queryElrank() {
    loading.value = true;

    if (getSocket() === undefined) {
      message.error('socket连接异常，请重试！');
      router.push({ name: 'account-list' });
      return;
    }
    console.log('queryTableParames.value:' + JSON.stringify(queryTableParames.value));

    try {
      getSocket().send(
        JSON.stringify({
          type: SocketEnum.TypeQueryEndlessRank,
          data: JSON.stringify({
            limit: queryTableParames.value.limit,
            server_id: params.value.server_id,
          }),
        })
      );
    } catch (_err) {
      console.log('错误信息：' + _err.message);

      setTimeout(function () {
        message.error('socket连接被断开，正在尝试恢复....');
        getSocket().send(
          JSON.stringify({
            type: SocketEnum.TypeQueryEndlessRank,
            data: JSON.stringify({
              limit: queryTableParames.value.limit,
              server_id: params.value.server_id,
            }),
          })
        );
        message.success('socket已恢复');
      }, 1000);
    }
  }

  onMounted(async () => {
    setTimeout(() => {
      show.value = false;
    }, 2000);
    queryElrank();
  });

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

    dataSource.value = [];

    if (data.code == SocketEnum.CodeErr) {
      loading.value = false;
      message.error('查询出错，请稍后重试！ cid:' + data.cid);
      return;
    }

    if (data.msg !== undefined && data.msg !== null) {
      try {
        dataSource.value = JSON.parse(data.msg);
        console.log('dataSource.value:' + JSON.stringify(dataSource.value));
      } catch (e) {
        message.error('查询服务出错，' + data.msg);
      }
    }

    loadData();

    loading.value = false;
  };

  addOnMessage(onMessageList, queryElrankData);

  function loadData() {}

  const actionColumn = reactive({
    width: 220,
    title: '操作',
    key: 'action',
    // fixed: 'right',
    render(record) {
      return h(TableAction as any, {
        style: 'button',
        actions: [
          {
            type: 'default',
            label: '查询玩家信息',
            onClick: handleEdit.bind(null, record),
            ifShow: () => {
              return true;
            },
          },
        ],
        select: (key) => {
          message.info(`您点击了，${key} 按钮`);
        },
      });
    },
  });

  function handleEdit(record: Recordable) {
    // router.push({
    //   name: 'account-info',
    //   params: { id: record.playerid },
    // });

    openUserModal(record.playerId);
  }

  const userModalRef = ref();
  const userId = ref(0);
  function openUserModal(id) {
    userId.value = id;
    const { openDrawer } = userModalRef.value;
    openDrawer();
  }
</script>

<style lang="less" scoped></style>
