<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"
      />
    </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 { useMessage } from 'naive-ui';
  import { BasicTable, TableAction } from '@/components/Table';
  import { BasicForm, FormSchema, useForm } from '@/components/Form';
  import { getChatLogList, getChatMsgList } from '@/api/account/list';
  import { columns } from './columns';
  import { arrayAddIndex, arrayDelIndex, delNullProperty } from '@/utils/array';
  import { defRangeShortcuts } from '@/utils/dateUtil';
  import { useUserStoreWidthOut } from '@/store/modules/user';
  import { clanChatChannel } from '@/views/account/chatReportList/columns';

  const useUserStore = useUserStoreWidthOut();
  const chatLogReq = ref(null);
  const messages = ref([]);
  const firstChatID = ref('');
  const lastChatID = 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];
      });
    }
  }

  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: 'chat_channel',
      component: 'NCheckbox',
      label: '频道',
      componentProps: {
        options: clanChatChannel,
      },
    },
    {
      field: 'create_time',
      component: 'NDatePicker',
      label: '发送时间',
      componentProps: {
        type: 'datetimerange',
        clearable: true,
        shortcuts: defRangeShortcuts(),
        onUpdateValue: (e: any) => {
          console.log(e);
        },
      },
    },
    /*{
      field: 'is_team_channel',
      component: 'NSwitch',
      label: '过滤组队频道',
      componentProps: {
        placeholder: '请选择频道',
        defaultValue: 0,
        options: clanChatChannel,
      },
    },*/
  ];

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

  const columnsRef = ref(columns);
  const formRef = ref({});
  const actionColumn = reactive({
    width: 80,
    title: '操作',
    key: 'action',
    fixed: 'right',
    render(record) {
      return h(TableAction as any, {
        style: 'button',
        actions: [
          {
            label: '查看聊天',
            // type: 'default',
            onClick: viewChat.bind(null, record),
            ifShow: () => {
              return true;
            },
          },
        ],
        select: (key) => {
          message.info(`您点击了，${key} 按钮`);
        },
      });
    },
  });

  const showChat = ref(false);
  async function viewChat(record: Recordable) {
    previewTitle.value = record.channel_name;
    chatLogReq.value = {
      server_id: record.sever_id,
      chat_channel: record.chat_channel,
      player_id: record.player_id,
    };
    const req = {
      ...chatLogReq.value,
      current_id: record.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: '5' },
    labelWidth: 100,
    schemas,
  });

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

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

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

  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>
