<template>
  <div>
    <div class="n-layout-page-header">
      <n-card :bordered="false" title="聊天内容举报记录">
        游戏服务器中对玩家的聊天记录举报会在这里记录
      </n-card>
    </div>
    <n-card :bordered="false" class="proCard">
      <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 #tableTitle>
          <n-button type="primary" @click="loadModal" :loading="loadingRef" class="mx-1">
            导出数据
          </n-button>
          <n-modal
            v-model:show="modalShow"
            preset="dialog"
            positive-text="确认"
            negative-text="取消"
            :content="modalData"
            @positive-click="exportChatLogs"
            @negative-click="modalShow = false"
          />
        </template>
      </BasicTable>
    </n-card>
    <div>
      <n-modal v-model:show="showChat" :mask-closable="true" :block-scroll="false" title="聊天记录">
        <ChatPreview
          :title="previewTitle"
          :messages="messages"
          @loadMoreMessages="loadMoreMessages"
        />
      </n-modal>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { h, reactive, ref } from 'vue';
  import { BasicTable, TableAction } from '@/components/Table';
  import { BasicForm, FormSchema, useForm } from '@/components/Form';
  import { exportChatLog, getChatLog, getChatLogList, getChatReportList } from '@/api/account/list';
  import { clanChatChannel, columns } from './columns';
  import { useRouter } from 'vue-router';
  import { arrayAddIndex, arrayDelIndex, delNullProperty } from '@/utils/array';
  import { defRangeShortcuts } from '@/utils/dateUtil';
  import { useUserStoreWidthOut } from '@/store/modules/user';
  import { useMessage } from 'naive-ui';

  const message = useMessage();
  const firstChatID = ref('');
  const lastChatID = ref('');
  const chatLogReq = ref(null);
  const messages = ref([]);
  const previewTitle = ref('');
  // 加载更多历史消息的函数
  async function loadMoreMessages(flag: String) {
    console.log('flag:', flag);
    const moreMessages = [];
    if (flag === 'up') {
      const req = {
        ...chatLogReq.value,
        before_id: firstChatID.value,
      };
      await getChatLogList(delNullProperty({ ...req })).then((res) => {
        if (!res) {
          message.info('没有更早的数据了');
          return;
        }
        res.forEach((column: any) => {
          let sender = 'other';
          if (column.player_id === chatLogReq.value.player_id) {
            sender = 'me';
          }
          moreMessages.push({
            id: column.chat_id,
            sender: sender,
            username: column.nick_name,
            text: column.content,
            avatar: column.head_img,
            time: new Date(column.create_time).toLocaleString(),
          });
        });
        if (res.length > 0) {
          firstChatID.value = res[0].chat_id;
        }
        messages.value = [...moreMessages, ...messages.value];
      });
    } else {
      const req = {
        ...chatLogReq.value,
        later_id: lastChatID.value,
      };
      await getChatLogList(delNullProperty({ ...req })).then((res) => {
        if (!res) {
          message.info('没有更晚的数据了');
          return;
        }
        res.forEach((column: any) => {
          let sender = 'other';
          if (column.player_id === chatLogReq.value.player_id) {
            sender = 'me';
          }
          moreMessages.push({
            id: column.chat_id,
            sender: sender,
            username: column.nick_name,
            text: column.content,
            avatar: column.head_img,
            time: new Date(column.create_time).toLocaleString(),
          });
        });
        if (res.length > 0) {
          lastChatID.value = res[res.length - 1].chat_id;
        }
        messages.value = [...messages.value, ...moreMessages];
      });
    }
  }

  let params = ref({
    sorter: [],
    pageSize: 100,
  });

  const useUserStore = useUserStoreWidthOut();
  const serverOption = [
    {
      value: 0,
      label: '全部',
      name: '全部',
    },
    ...useUserStore.config.server_simple_option,
  ];

  const schemas: FormSchema[] = [
    {
      field: 'server_id',
      component: 'NSelect',
      label: '举报者服务器',
      componentProps: {
        placeholder: '请选择服务器',
        defaultValue: 0,
        options: serverOption,
      },
    },
    {
      field: 'player_id',
      component: 'NInput',
      label: '举报者ID',
      componentProps: {
        placeholder: '请输入玩家ID',
        onInput: (e: any) => {
          console.log(e);
        },
      },
      rules: [{ message: '请输入玩家ID', trigger: ['blur'] }],
    },
    {
      field: 'clan_server_id',
      component: 'NSelect',
      label: '被举报者服务器',
      componentProps: {
        placeholder: '请选择服务器',
        defaultValue: 0,
        options: serverOption,
      },
    },
    {
      field: 'clan_player_id',
      component: 'NInput',
      label: '被举报者ID',
      componentProps: {
        placeholder: '请输入账号ID',
        onInput: (e: any) => {
          console.log(e);
        },
      },
      rules: [{ message: '请输入账号ID', trigger: ['blur'] }],
    },
    {
      field: 'clan_chat_channel',
      component: 'NSelect',
      label: '频道',
      componentProps: {
        placeholder: '请选择频道',
        defaultValue: 0,
        options: clanChatChannel,
      },
    },
    {
      field: 'clan_time',
      component: 'NDatePicker',
      label: '消息发送时间',
      componentProps: {
        type: 'datetimerange',
        clearable: true,
        shortcuts: defRangeShortcuts(),
        onUpdateValue: (e: any) => {
          console.log(e);
        },
      },
    },
    {
      field: 'create_time',
      component: 'NDatePicker',
      label: '举报时间',
      componentProps: {
        type: 'datetimerange',
        clearable: true,
        shortcuts: defRangeShortcuts(),
        onUpdateValue: (e: any) => {
          console.log(e);
        },
      },
    },
  ];

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

  const columnsRef = ref(columns);
  const formRef = ref({});

  const actionColumn = reactive({
    width: 300,
    title: '操作',
    key: 'action',
    fixed: 'right',
    render(record) {
      return h(TableAction as any, {
        style: 'button',
        actions: [
          {
            label: '举报者信息',
            type: 'default',
            onClick: handleEdit.bind(null, '', record),
            ifShow: () => {
              return true;
            },
          },
          {
            label: '被举报者信息',
            type: 'default',
            onClick: handleEdit.bind(null, 'clan_player', record),
            ifShow: () => {
              return true;
            },
          },
          {
            label: '聊天历史',
            type: 'default',
            onClick: viewChat.bind(null, record),
            ifShow: () => {
              return true;
            },
          },
        ],
        dropDownActionLabel: '下载',
        dropDownActions: dropDownActions(record),
        select: (key, item) => {
          handleDownload(item.label);
        },
      });
    },
  });

  const showChat = ref(false);
  async function viewChat(record: Recordable) {
    console.log(record.clan_time);
    previewTitle.value = record.clan_channel_name;
    const now = new Date();
    // 设置时间为整点
    now.setHours(now.getHours(), 0, 0, 0);
    console.log(
      !(record.clan_time < now.getTime() && new Date().getTime() > now.getTime() + 1000 * 5 * 60)
    );
    // 消息发送时间<当前整点且当前时间在当前整点5分钟后才有数据
    if (
      !(record.clan_time < now.getTime() && new Date().getTime() > now.getTime() + 1000 * 5 * 60)
    ) {
      message.warning('聊天记录还未同步，请稍后查看');
      return;
    }
    chatLogReq.value = {
      server_id: record.server_id,
      chat_channel: record.clan_chat_channel,
      player_id: record.clan_player_id,
    };
    const req = {
      ...chatLogReq.value,
      current_id: record.clan_chat_id,
    };
    messages.value = [];
    await getChatLogList(delNullProperty({ ...req })).then((res) => {
      console.log('=====:', res);
      if (!res) {
        message.warning('未查到聊天记录');
      }
      if (res.length > 0) {
        firstChatID.value = res[0].chat_id;
        lastChatID.value = res[res.length - 1].chat_id;
      }
      res.forEach((column: any) => {
        // console.log(column);
        let sender = 'other';
        if (column.player_id === chatLogReq.value.player_id) {
          sender = 'me';
        }
        messages.value.push({
          id: column.chat_id,
          sender: sender,
          username: column.nick_name,
          text: column.content,
          avatar: column.head_img,
          time: new Date(column.create_time).toLocaleString(),
        });
      });
    });
    showChat.value = true;
  }

  const [register, {}] = useForm({
    gridProps: { cols: '7' },
    labelWidth: 90,
    schemas,
  });
  const modalShow = ref(false);
  const modalData = ref(null);
  const loadingRef = ref(false);
  // 发起 API 请求并在成功后显示对话框
  const loadModal = async () => {
    loadingRef.value = true;
    await getChatReportList(delNullProperty({ ...params.value, ...formRef.value.formModel }))
      .then((response) => {
        if (response.count > 500) {
          modalData.value =
            '要导出的数据为' +
            response.count +
            '条。数据量较大，请点击取消后重新筛选数据后再导出，点击确认将继续导出';
          modalShow.value = true; // 显示模态框
          loadingRef.value = false;
        } else {
          exportChatLogs();
        }
      })
      .catch((err) => {
        console.log(err);
      });
    loadingRef.value = false;
  };

  function exportChatLogs() {
    console.log('开始下载逻辑');
    loadingRef.value = true;
    exportChatLog(
      delNullProperty({
        is_export: 1,
        ...formRef.value.formModel,
      })
    )
      .then((response) => {
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');
        const now = new Date();
        const year = now.getFullYear();
        const month = (now.getMonth() + 1).toString().padStart(2, '0');
        const day = now.getDate().toString().padStart(2, '0');
        const hours = now.getHours().toString().padStart(2, '0');
        const minutes = now.getMinutes().toString().padStart(2, '0');
        const seconds = now.getSeconds().toString().padStart(2, '0');
        const filename =
          '聊天举报记录导出' + year + month + day + hours + minutes + seconds + '.xlsx';
        link.href = url;
        link.setAttribute('download', filename); // 设置下载文件的名称
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        loadingRef.value = false;
      })
      .catch((err) => {
        console.error('export err!', err);
      });
    /*window.location.href =
      '/api/chat/reportList?' +
      encodeParams(
        delNullProperty({
          is_export: 1,
          ...formRef.value.formModel,
          authorization: useUserStore.token,
        })
      );*/
  }

  function dropDownActions(record: Recordable) {
    const arr = [];
    record.chat_logs.forEach((column: string) => {
      arr.push({
        label: column,
        key: 'enabled',
        type: 'info',
        // 根据业务控制是否显示: 非enable状态的不显示启用按钮
        ifShow: () => {
          return true;
        },
      });
    });
    return arr;
  }

  function handleDownload(path) {
    getChatLog({ path: path })
      .then((response) => {
        const url = window.URL.createObjectURL(new Blob([response.data]));
        const link = document.createElement('a');
        const split = path.split('/');
        const filename = split[split.length - 1];
        link.href = url;
        link.setAttribute('download', filename); // 设置下载文件的名称
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      })
      .catch((err) => {
        console.error('There was an error downloading the file!', err);
      });
  }

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

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

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

  function handleEdit(flag: String, record: Recordable) {
    let req = { id: record.player_id, record: JSON.stringify(record) };
    if (flag === 'clan_player') {
      req = { id: record.clan_player_id, record: JSON.stringify(record) };
    }
    router.push({
      name: 'account-info',
      params: req,
    });
  }

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

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

  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();
  }
</script>

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