<template>
  <div class="ele-body">
    <a-card :bordered="false">
      <!-- 表格 -->
      <ele-pro-table
        ref="tableRef"
        row-key="id"
        :columns="columns"
        :datasource="datasource"
        v-model:selection="selection"
        :scroll="{ x: 1300 }"
        :customRow="customRow"
        cache-key="proChatTable"
      >
        <template #toolbar>
          <search @search="reload" @add="openEdit" />
        </template>
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'userInfo'">
            <div class="user-box">
              <a-avatar
                :size="30"
                :src="`${record.userInfo?.avatar}`"
                style="margin-right: 4px"
              >
                <template #icon>
                  <UserOutlined />
                </template>
              </a-avatar>
              <div class="user-info">
                <span>ID: {{ record.userInfo?.userId }}</span>
                <span>{{ record.userInfo?.realName }}</span>
                <span class="ele-text-placeholder">{{
                  record.userInfo?.nickname
                }}</span>
              </div>
            </div>
          </template>
          <template v-if="column.key === 'friendInfo'">
            <div class="user-box">
              <a-avatar
                :size="30"
                :src="`${record.friendInfo?.avatar}`"
                style="margin-right: 4px"
              >
                <template #icon>
                  <UserOutlined />
                </template>
              </a-avatar>
              <div class="user-info">
                <span>ID: {{ record.friendInfo?.userId }}</span>
                <span>{{ record.friendInfo?.realName }}</span>
                <span class="ele-text-placeholder">{{
                  record.friendInfo?.nickname
                }}</span>
              </div>
            </div>
          </template>
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-button @click="openEdit(record)">查看</a-button>
            </a-space>
          </template>
        </template>
      </ele-pro-table>
    </a-card>
    <!-- 编辑弹窗 -->
    <chat-message-list
      v-model:visible="showEdit"
      :data="current"
      :organization-list="data"
      @done="reload"
    />
    <!-- 导入弹窗 -->
    <!--    <user-import v-model:visible="showImport" @done="reload" />-->
  </div>
</template>

<script lang="ts" setup>
  import { ref } from 'vue';
  import { message } from 'ant-design-vue/es';
  import { UserOutlined } from '@ant-design/icons-vue';
  import type { EleProTable } from 'ele-admin-pro/es';
  import type {
    ColumnItem,
    DatasourceFunction
  } from 'ele-admin-pro/es/ele-pro-table/types';
  import { timeAgo, toTreeData } from 'ele-admin-pro';
  import ChatMessageList from './components/chat-message-list.vue';
  // import UserImport from './components/user-import.vue';
  import { pageChatConversation } from '@/api/love/chat';
  import type { User } from '@/api/system/user/model';
  import { listRoles } from '@/api/system/role';
  import { listOrganizations } from '@/api/system/organization';
  import { Organization } from '@/api/system/organization/model';
  import Search from './components/search.vue';
  import {
    ChatConversation,
    ChatConversationParam
  } from '@/api/love/chat/model';

  // 加载状态
  const loading = ref(true);
  // 树形数据
  const data = ref<Organization[]>([]);
  // 树展开的key
  const expandedRowKeys = ref<number[]>([]);
  // 树选中的key
  const selectedRowKeys = ref<number[]>([]);
  // 表格选中数据
  const selection = ref<User[]>([]);
  // 当前编辑数据
  const current = ref<ChatConversation | null>(null);
  // 是否显示编辑弹窗
  const showEdit = ref(false);

  // 加载角色
  const roles = ref<any[]>([]);
  const filters = () => {
    listRoles().then((result) => {
      result.map((d) => {
        roles.value.push({
          text: d.roleName,
          value: d.roleId
        });
      });
    });
  };
  filters();
  // 加载机构
  listOrganizations()
    .then((list) => {
      loading.value = false;
      const eks: number[] = [];
      list.forEach((d) => {
        d.key = d.organizationId;
        d.value = d.organizationId;
        d.title = d.organizationName;
        if (typeof d.key === 'number') {
          eks.push(d.key);
        }
      });
      expandedRowKeys.value = eks;
      data.value = toTreeData({
        data: list,
        idField: 'organizationId',
        parentIdField: 'parentId'
      });
      if (list.length) {
        if (typeof list[0].key === 'number') {
          selectedRowKeys.value = [list[0].key];
        }
      } else {
        selectedRowKeys.value = [];
      }
    })
    .catch((e) => {
      loading.value = false;
      message.error(e.message);
    });

  // 表格实例
  const tableRef = ref<InstanceType<typeof EleProTable> | null>(null);
  // 表格列配置
  const columns = ref<ColumnItem[]>([
    {
      key: 'index',
      width: 48,
      align: 'center',
      fixed: 'left',
      hideInSetting: true,
      customRender: ({ index }) => index + (tableRef.value?.tableIndex ?? 0)
    },
    {
      title: 'ID',
      dataIndex: 'id',
      width: 80,
      showSorterTooltip: false
    },
    {
      title: '当前用户',
      dataIndex: 'userInfo',
      key: 'userInfo',
      showSorterTooltip: false
    },
    {
      title: '聊天对象',
      dataIndex: 'friendInfo',
      key: 'friendInfo',
      showSorterTooltip: false
    },
    // {
    //   title: '消息数',
    //   dataIndex: 'messages',
    //   showSorterTooltip: false,
    //   customRender: ({ text }) => text.length
    // },
    {
      title: '最新消息',
      dataIndex: 'content',
      width: 300,
      ellipsis: true,
      showSorterTooltip: false
    },
    {
      title: '未读',
      dataIndex: 'unRead',
      width: 80,
      showSorterTooltip: false
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      showSorterTooltip: false,
      ellipsis: true,
      customRender: ({ text }) => timeAgo(text)
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      showSorterTooltip: false,
      ellipsis: true,
      customRender: ({ text }) => timeAgo(text)
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      fixed: 'right',
      align: 'center'
    }
  ]);

  // 默认搜索条件
  // const { where, resetFields } = useSearch<User>({
  //   merchantId: undefined,
  //   merchantName: '',
  //   merchantCode: '',
  //   gradeId: undefined,
  //   gradeName: ''
  // });
  // // 默认搜索条件
  // const defaultWhere = reactive({
  //   username: '',
  //   nickname: '',
  //   keywords: ''
  // });

  // 表格数据源
  const datasource: DatasourceFunction = ({
    page,
    limit,
    where,
    orders,
    filters
  }) => {
    const params: ChatConversationParam = {
      page,
      limit,
      // onlyFake: !!where.onlyFake,
      onlyFake: true,
      keywords: where.keywords,
      userId: where.userId,
      status: where.status,
      order: orders.order,
      sort: orders.sort
    };
    console.log('params', params);
    return pageChatConversation(params);
  };
  /* 搜索 */
  const reload = (where?: ChatConversationParam) => {
    selection.value = [];
    tableRef?.value?.reload({ where });
  };

  reload();
  /* 打开编辑弹窗 */
  const openEdit = (row?: User) => {
    current.value = row ?? null;
    showEdit.value = true;
  };

  /* 自定义行属性 */
  const customRow = (record: User) => {
    return {
      // 行点击事件
      onClick: () => {
        // console.log(record);
      },
      // 行双击事件
      onDblclick: () => {
        openEdit(record);
      }
    };
  };
</script>

<script lang="ts">
  export default {
    name: 'LoveUser'
  };
</script>

<style lang="less" scoped>
  .user-box {
    display: flex;
    align-items: center;

    .user-info {
      display: flex;
      flex-direction: column;
      align-items: start;
    }
  }
</style>
