<template>
  <ns-modal
    v-model:visible="show"
    width="1100px"
    style="overflow-y: hidden"
    title="添加联系人"
    @ok="handleOk"
    @cancel="handleCancel">
    <div class="box">
      <div class="box-left">
        <div style="width: 100%; display: flex; position: relative" class="ns-title-extra-box">
          <span style="margin-left: 12px; color: #333333">联系人名单</span>
        </div>
        <img
          style="width: 100%; height: 2px"
          src="https://files.axshare.com/gsc/4T0UQR/7e/5d/a2/7e5da2a277344db8af30521cefeb70cc/images/告警设置/u150.svg?pageId=1f58c1ba-b461-4fe8-a2b3-295f1e7b0aa0" />
        <a-input-search
          v-model:value="searchValue"
          style="margin-bottom: 8px"
          placeholder="请输入关键字" />
        <img
          style="width: 100%; height: 2px"
          src="https://files.axshare.com/gsc/4T0UQR/7e/5d/a2/7e5da2a277344db8af30521cefeb70cc/images/告警设置/u150.svg?pageId=1f58c1ba-b461-4fe8-a2b3-295f1e7b0aa0" />
        <div style="width: 100%; height: 370px; overflow-y: auto">
          <a-tree
            v-model:selectedKeys="selectedKeys"
            v-model:expandedKeys="expandedKeys"
            :tree-data="deptTreeData"
            @select="onSelect"
        /></div>
      </div>
      <div class="box-right">
        <div style="width: 100%; display: flex; position: relative" class="ns-title-extra-box">
          <span style="margin-left: 12px; color: #333333">人员列表 </span>
          <a-input-search
            v-model:value="realName"
            style="margin-bottom: 8px; width: 280px; position: absolute; right: 20px"
            placeholder="请输入"
            allowClear="true"
            @search="onSearch" />
        </div>
        <img
          style="width: 100%; height: 2px"
          src="https://files.axshare.com/gsc/4T0UQR/7e/5d/a2/7e5da2a277344db8af30521cefeb70cc/images/告警设置/u150.svg?pageId=1f58c1ba-b461-4fe8-a2b3-295f1e7b0aa0" />
        <div style="width: 100%; height: 450px; overflow-y: auto; padding: 12px 0">
          <a-table
            :row-selection="{
              selectedRowKeys: selectedRowKey,
              preserveSelectedRowKeys: true,
              onChange: onSelectChange,
            }"
            :columns="columns"
            :loading="loading"
            :data-source="dataSource"
            :rowKey="(record: any) => record.userId"
            :pagination="pagination"
            :bordered="true"
            :size="'middle'">
            <template #bodyCell="{ record, column }">
              <template v-if="column.dataIndex === 'address'">
                {{ record.userRoleInfos?.[0].deptRoleInfoList }}
              </template>
            </template>
          </a-table>
        </div>
      </div>
    </div>
  </ns-modal>
</template>

<script lang="ts">
  import { ref, watch } from 'vue';
  import { defineComponent } from 'vue';
  import type { TreeProps } from 'ant-design-vue';
  import { origanizemanage } from '/@/api/origanizemanage';
  import { department } from '/@/api/origanizemanage';
  import { http } from '/nerv-lib/util';

  //搜索存储 拼凑树的搜索类型
  const dataList: TreeProps['treeData'] = [];
  const generateList = (data: TreeProps['treeData']) => {
    for (let i = 0; i < data.length; i++) {
      const node = data[i];
      const key = node.key;
      dataList.push({ key, title: node.title });
      if (node.children) {
        generateList(node.children);
      }
    }
  };
  const getParentKey = (
    key: string | number,
    tree: TreeProps['treeData'],
  ): string | number | undefined => {
    let parentKey;
    for (let i = 0; i < tree.length; i++) {
      const node = tree[i];
      if (node.children) {
        if (node.children.some((item) => item.key === key)) {
          parentKey = node.key;
        } else if (getParentKey(key, node.children)) {
          parentKey = getParentKey(key, node.children);
        }
      }
    }
    return parentKey;
  };
  export default defineComponent({
    setup(props, { emit }) {
      //组织数
      const orgId = ref('');
      const result = JSON.parse(sessionStorage.getItem('ORGID')!);
      orgId.value = result;
      const dataSource = ref([]);
      const loading = ref(false);
      const selectedRowKey = ref([]);
      const selectedRow = ref([]);
      const realName = ref(null);
      // 树方法
      const expandedKeys = ref<(string | number)[]>([]);
      const selectedKeys = ref([]);
      const searchValue = ref<string>('');
      const deviceName = ref<string>('');
      const autoExpandParent = ref<boolean>(true);
      const deptTreeData = ref([]);
      //选择 组织
      const selectOrgId = ref('');
      //默认当前缓存的组织
      selectOrgId.value = result;
      //选择部门
      const selectDeptId = ref('');
      const show = ref(false);
      //人员搜索
      const onSearch = () => {
        pagination.value.current = 1;
        getList();
      };
      //点击树 搜索人员
      const onSelect = (selectedKeys: any, info: any) => {
        selectedKeys.value = selectedKeys;
        //判断选择的部门 还是 组织
        if (info.node.dataRef.deptInfo) {
          selectDeptId.value = info.node.dataRef.deptInfo.deptId;
          selectOrgId.value = info.node.dataRef.deptInfo.orgId;
        }
        if (info.node.dataRef.orgInfo) {
          selectOrgId.value = info.node.dataRef.orgInfo.orgId;
          selectDeptId.value = '';
        }
        pagination.value.current = 1;
        getList();
      };
      // 递归处理部门树数据
      const processDepartmentTree = (tree: any) => {
        tree.forEach((item: any) => {
          item.deptInfo = item.deptInfo;
          item.key = item.deptInfo.deptId;
          item.title = item.deptInfo.deptName;
          item.children = processDepartmentTree(item.children); // 递归处理子节点
        });
        return tree;
      };

      // 获取部门树
      const getDepartList = (params: any) => {
        return http.post(department.queryDeptTree, params).then((res) => {
          const result = res.data.map((item: any) => ({
            key: item.orgInfo.orgId,
            orgInfo: item.orgInfo,
            title: item.orgInfo.orgName,
            children: processDepartmentTree(item.deptTrees),
          }));

          return result;
        });
      };
      //获取树
      const getTreeData = () => {
        getDepartList({ orgId: orgId.value }).then((res) => {
          deptTreeData.value = res;
          selectedKeys.value = [orgId.value];
          generateList(deptTreeData.value);
        });
      };
      //获取列表
      const getList = () => {
        loading.value = true;
        http
          .post(origanizemanage.userList, {
            pageNum: pagination.value.current,
            pageSize: pagination.value.pageSize,
            orgId: selectOrgId.value,
            deptId: selectDeptId.value,
            realName: realName.value,
            userStatus: 0, // 写死 没有被冻结的用户
          })
          .then((res) => {
            dataSource.value = res.data.records;
            pagination.value.total = res.data.total;
            loading.value = false;
          });
      };
      // 改变页码
      const handleChangePage = (current: number, pageSize: number) => {
        pagination.value.current = current;
        pagination.value.pageSize = pageSize;
        getList();
      };
      const pagination = ref({
        total: 0,
        size: 'small',
        current: 1,
        pageSize: 10,
        showQuickJumper: true,
        showLessItems: true,
        // showSizeChanger: true,
        showTotal: (total: number, range: any) =>
          total && range ? `显示第${range[0]}到${range[1]}条记录,共 ${total} 条记录` : '',
        onChange: handleChangePage,
      });
      const onSelectChange = (selectedRowKeys: any, selectedRows: any) => {
        selectedRowKey.value = selectedRowKeys;
        // 使用 forEach 循环遍历 selectedRows 数组
        let newSelectRows: any = [];
        selectedRows.forEach((item: any) => {
          if (item) {
            newSelectRows.push(item);
          }
        });
        // 添加新选中的行的 userId 到 selectedRow.value
        selectedRow.value = [
          ...selectedRow.value,
          ...newSelectRows.filter(
            (newRow: any) =>
              !selectedRow.value.some((existingRow) => existingRow.userId === newRow.userId),
          ),
        ];
        // 移除取消选中的行的 userId
        selectedRow.value = selectedRow.value.filter((existingRow: any) =>
          selectedRowKeys.includes(existingRow.userId),
        );
      };
      const columns = [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          customRender: (text: any) => {
            return text.index + 1;
          },
        },
        {
          title: '姓名',
          dataIndex: 'realName',
          width: 100,
          ellipsis: true,
        },
        {
          title: '性别',
          dataIndex: 'sex',
        },
        {
          title: '组织关系',
          dataIndex: 'orgName',
        },
        {
          title: '部门  ',
          dataIndex: 'address',
        },
      ];
      const reback = () => {
        show.value = false;
        pagination.value.current = 1;
        realName.value = null;
        searchValue.value = '';
        selectDeptId.value = '';
        selectOrgId.value = orgId.value;
        selectedRow.value = [];
        selectedRowKey.value = [];
      };
      const handleOk = () => {
        // 处理确定按钮的逻辑
        emit('handleOk', { id: selectedRowKey.value, data: selectedRow.value });
        //恢复数据
        reback();
      };
      const getData = (data: any) => {
        selectedRow.value = data.data;
        selectedRowKey.value = data.id;
        show.value = true;
        //获取列表
        getList();
        //获取树
        getTreeData();
      };
      const handleCancel = () => {
        // 处理取消按钮的逻辑
        emit('handleCancel', null);
        reback();
      };
      // 监听树的搜索
      watch(searchValue, (value) => {
        const expanded = dataList
          .map((item: TreeProps['treeData'][number]) => {
            if (item.title.indexOf(value) > -1) {
              return getParentKey(item.key, deptTreeData.value);
            }
            return null;
          })
          .filter((item, i, self) => item && self.indexOf(item) === i);
        expandedKeys.value = expanded;
        searchValue.value = value;
        autoExpandParent.value = true;
      });
      return {
        columns,
        realName,
        orgId,
        processDepartmentTree,
        onSearch,
        getList,
        loading,
        dataSource,
        onSelect,
        deptTreeData,
        selectedRow,
        selectedRowKey,
        autoExpandParent,
        expandedKeys,
        selectedKeys,
        onSelectChange,
        pagination,
        handleOk,
        reback,
        show,
        getData,
        getTreeData,
        getDepartList,
        searchValue,
        deviceName,
        handleCancel,
        selectDeptId,
        selectOrgId,
      };
    },
  });
</script>
<style scoped lang="less">
  .box {
    width: 100%;
    height: 500px;
    display: flex;
    .box-left {
      width: 300px;
      height: 100%;
      overflow-y: auto;
      padding: 0, 12px;
      gap: 5px;
    }
    .box-right {
      width: calc(100% - 200px);
      height: 100%;
      padding: 0 12px;
      overflow-y: auto;
    }
  }
</style>
