<template>
  <div>
    <n-card :bordered="false" class="proCard" title="玩家列表">
      <BasicForm
        @register="register"
        @submit="handleSubmit"
        @reset="handleReset"
        @keyup.enter="handleSubmit"
        ref="formRef"
      >
        <template #statusSlot="{ model, field }">
          <n-input v-model:value="model[field]" />
        </template>
      </BasicForm>

      <BasicTable
        :columns="columns"
        :request="loadDataTable"
        :row-key="(row) => row.id"
        ref="actionRef"
        :actionColumn="actionColumn"
        @update:checked-row-keys="onCheckedRow"
        @update:sorter="handleSorterChange"
        :scroll-x="1090"
        :flex-height="false"
      >
        <!--        <template #toolbar>-->
        <!--          <n-button type="primary" @click="reloadTable">刷新数据</n-button>-->
        <!--        </template>-->
        <template #tableTitle>
          <n-button type="primary" @click="exportData"> 导出数据 </n-button>
        </template>
      </BasicTable>
    </n-card>

    <n-modal v-model:show="showModal" preset="dialog" title="确认删除用户" style="width: 950px">
      <template #default>
        <n-card>
          <DelVerifyUserInfo :userId="playerId" :userInfo="playerInfo" />
        </n-card>
      </template>
      <template #action>
        <n-button @click="onNegativeClick">取消</n-button>
        <n-button type="info" :loading="formBtnLoading" @click="onPositiveClick">确认</n-button>
      </template>
    </n-modal>

    <n-modal
      v-model:show="delAccountModal"
      preset="dialog"
      title="确认删除用户账号，删除账号会删除该账号下的所有游戏数据"
      style="color: red; width: 950px"
    >
      <template #default>
        <n-card>
          <DelVerifyUserInfos :userId="accounId" />
        </n-card>
      </template>

      <template #action>
        <n-button @click="onNegativeClick">取消</n-button>
        <n-tooltip trigger="hover">
          <template #trigger>
            <n-button type="info" :loading="formBtnLoading" @click="onDelAccountClick">
              确认
            </n-button>
          </template>
          删除账号会删除该账号下的所有角色
        </n-tooltip>
      </template>
    </n-modal>
  </div>
</template>

<script lang="ts" setup>
  import { h, reactive, ref, inject } from 'vue';

  import { useMessage } from 'naive-ui';
  import { BasicTable, TableAction } from '@/components/Table';
  import { BasicForm, FormSchema, useForm } from '@/components/Form/index';
  import { deletePlayer, getTableList, deleteAccount } from '@/api/account/list';
  import { columns } from './columns';
  import { useRouter } from 'vue-router';
  import { arrayAddIndex, arrayDelIndex, delNullProperty } from '@/utils/array';
  import { useUserStoreWidthOut } from '@/store/modules/user';
  import { defRangeShortcuts } from '@/utils/dateUtil';
  import { getSocket, addOnMessage } from '@/utils/websocket';
  import { SocketEnum } from '@/enums/socketEnum';
  import { userInfoObj } from '@/views/account/accountList/userInfo';
  import DelVerifyUserInfo from './components/DelVerifyUserInfo.vue';
  import DelVerifyUserInfos from './components/DelVerifyUserInfos.vue';

  const playerId = ref(0);
  const accounId = ref(0);

  const playerInfo = ref(userInfoObj);

  const onMessageList = inject('onMessageList');
  const queryUserMessage = (res) => {
    const data = JSON.parse(res.data);
    if (data.type !== SocketEnum.TypeQueryUser) {
      return;
    }
    if (data.code == SocketEnum.CodeErr) {
      message.success('没有查询到该用户的档案');
      router.push({ name: 'account-list' });
      return;
    }
    playerInfo.value = JSON.parse(data.msg);
  };

  addOnMessage(onMessageList, queryUserMessage);

  const formBtnLoading = ref(false);
  const useUserStore = useUserStoreWidthOut();
  const showModal = ref(false);
  const delAccountModal = ref(false);
  const params = ref({
    server_id: 1,
    sorter: [],
    channel_id: '',
  });

  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: 'channel_id',
      labelMessage: '选择推广渠道后不支持其他条件的混合搜索',
      component: 'NTreeSelect',
      label: '推广渠道',
      componentProps: {
        placeholder: '请选择推广渠道',
        clearFilterAfterSelect: true,
        clearable: true,
        filterable: true,
        defaultExpandAll: true,
        options: useUserStore.config.channel_tree_option,
        onUpdateValue: (e: any) => {
          console.log(e);
          params.value.channel_id = e;
        },
      },
    },
    {
      field: 'id',
      component: 'NInput',
      label: '玩家ID',
      componentProps: {
        placeholder: '请输入玩家ID',
        onInput: (e: any) => {
          console.log(e);
        },
      },
      rules: [{ message: '请输入玩家ID', trigger: ['blur'] }],
    },
    {
      field: 'openId',
      component: 'NInput',
      label: 'openId',
      componentProps: {
        placeholder: '请输入openId',
        onInput: (e: any) => {
          console.log(e);
        },
      },
      rules: [{ message: '请输入openId', trigger: ['blur'] }],
    },
    {
      field: 'nickname',
      labelMessage: '支持模糊查询',
      component: 'NInput',
      label: '昵称',
      componentProps: {
        placeholder: '请输入昵称',
        onInput: (e: any) => {
          console.log(e);
        },
      },
      rules: [{ message: '请输入昵称', trigger: ['blur'] }],
    },
    // {
    //   field: 'ban',
    //   component: 'NSelect',
    //   label: '账号状态',
    //   componentProps: {
    //     placeholder: '请选择',
    //     options: [
    //       {
    //         label: '全部',
    //         value: 0,
    //       },
    //       {
    //         label: '禁用',
    //         value: 1,
    //       },
    //       {
    //         label: '正常',
    //         value: 2,
    //       },
    //     ],
    //     onUpdateValue: (e: any) => {
    //       console.log(e);
    //     },
    //   },
    // },
    {
      field: 'createtime',
      component: 'NDatePicker',
      label: '注册时间',
      componentProps: {
        type: 'datetimerange',
        clearable: true,
        shortcuts: defRangeShortcuts(),
        onUpdateValue: (e: any) => {
          console.log(e);
        },
      },
    },
    {
      field: 'level',
      component: 'NInput',
      label: '玩家等级',
      componentProps: {
        pair: true,
        separator: '~',
        clearable: true,
        placeholder: ['从', '到'],
        onInput: (e: any) => {
          console.log(e);
        },
      },
    },
    {
      field: 'diamond',
      labelMessage: '支持带单位搜索',
      component: 'NInput',
      label: '钻石',
      componentProps: {
        pair: true,
        separator: '~',
        clearable: true,
        placeholder: ['从', '到'],
        onInput: (e: any) => {
          console.log(e);
        },
      },
    },
    {
      field: 'coin',
      labelMessage: '支持带单位搜索',
      component: 'NInput',
      label: '金币',
      componentProps: {
        pair: true,
        separator: '~',
        clearable: true,
        placeholder: ['从', '到'],
        onInput: (e: any) => {
          console.log(e);
        },
      },
    },
    {
      field: 'stamina',
      labelMessage: '注意：玩家的体力会随时间变化',
      component: 'NInput',
      label: '体力值',
      componentProps: {
        pair: true,
        separator: '~',
        clearable: true,
        placeholder: ['从', '到'],
        onInput: (e: any) => {
          console.log(e);
        },
      },
    },
  ];

  const router = useRouter();
  const message = useMessage();
  const actionRef = ref();

  const columnsRef = ref(columns);
  const formRef = ref<any>({});
  const actionColumn = reactive({
    width: 280,
    title: '操作',
    key: 'action',
    fixed: 'right',
    render(record) {
      return h(TableAction as any, {
        style: 'button',
        actions: [
          {
            label: '查询信息',
            onClick: handleEdit.bind(null, record),
            ifShow: () => {
              return true;
            },
          },
          {
            type: 'error',
            label: '删除玩家数据',
            onClick: handleDeletePlayer.bind(null, record),
            ifShow: () => {
              return true;
            },
          },
          {
            type: 'error',
            label: '删除玩家账户',
            onClick: handleDeleteAccount.bind(null, record),
            ifShow: () => {
              return true;
            },
          },
        ],
        select: (key) => {
          message.info(`您点击了，${key} 按钮`);
        },
      });
    },
  });

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

  function handleSorterChange(sorter) {
    columnsRef.value.forEach((column: any) => {
      if (column.sortOrder === undefined) return;
      if (!sorter) {
        column.sortOrder = false;
        return;
      }
      if (column.key === sorter.columnKey) {
        column.sortOrder = sorter.order;
        if (sorter.order === false) {
          params.value.sorter = arrayDelIndex(params.value.sorter, 'field', column.key);
        } else {
          let asOrder = 'ASC';
          if (sorter.order === 'descend') {
            asOrder = 'DESC';
          }
          params.value.sorter = arrayAddIndex(params.value.sorter, 'field', column.key, {
            field: column.key,
            by: asOrder,
          });
        }
      }
    });
    reloadTable();
  }

  const loadDataTable = async (res) => {
    return await getTableList(
      delNullProperty({ ...params.value, ...res, ...formRef.value.formModel })
    );
  };

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

  function reloadTable() {
    actionRef.value.reload();
  }

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

  const deletePlayerId = ref(0);
  const deleteAccId = ref(0);

  function onPositiveClick() {
    showModal.value = false;
    deletePlayer({
      ...{ playerid: deletePlayerId.value },
    })
      .then((res) => {
        console.log(res);
        reloadTable();
      })
      .catch((err) => {
        console.log(err);
        message.error(err);
      });
  }

  function onDelAccountClick() {
    delAccountModal.value = false;
    deleteAccount({
      ...{ accId: deleteAccId.value },
    })
      .then((res) => {
        console.log(res);
        reloadTable();
      })
      .catch((err) => {
        console.log(err);
        message.error(err);
      });
  }

  function onNegativeClick() {
    showModal.value = false;
    delAccountModal.value = false;
  }

  function handleDeletePlayer(record: Recordable) {
    showModal.value = true;
    deletePlayerId.value = record.playerid;
    playerId.value = record.playerid;
    getUserInfo(record.playerid);
  }

  function handleDeleteAccount(record: Recordable) {
    delAccountModal.value = true;
    deleteAccId.value = record.accId;
    accounId.value = record.accId;
  }

  function getUserInfo(userId: number) {
    if (getSocket() === undefined) {
      message.error('socket连接异常，请重试！');
      router.push({ name: 'account-list' });
      return;
    }

    try {
      getSocket().send(
        JSON.stringify({
          type: SocketEnum.TypeQueryUser,
          data: userId + '',
        })
      );
    } catch (e) {
      console.log('错误信息：' + e);

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

  function handleSubmit(values: Recordable) {
    console.log('handleSubmit values：' + JSON.stringify(values));
    reloadTable();
  }

  function handleReset(values: Recordable) {
    console.log(values);
    params.value.server_id = 1;
    params.value.sorter = [];
    params.value.channel_id = '';
    reloadTable();
  }

  function exportData() {
    return;
    // window.location.href =
    //   '/api/dash/export/statistics';
  }
</script>

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