<template>
  <a-row :gutter="0" style="height: 556px">
    <!-- 部门树 -->
    <a-col :span="6" style="height: 100%; border-right: 1px solid #e8e8e8; padding: 0 12px; display: flex; flex-direction: column">
      <a-input-search v-model:value="searchDepartValue" style="margin-bottom: 12px; margin-top: 0" placeholder="请输入部门名称" />
      <a-directory-tree
        selectable
        v-model:selectedKeys="selectedDepIds"
        :check-strictly="true"
        :dropdown-style="{ maxHeight: '200px', overflow: 'auto' }"
        :tree-data="filterDepartTreeData"
        :expand-action="false"
        v-model:expandedKeys="expandedKeys"
        @select="onDepSelect"
        style="height: 500px; overflow: auto"
      />
    </a-col>
    <!-- 人员表格 -->
    <a-col :span="10" style="height: 100%; padding: 0 12px; border-right: 1px solid #e8e8e8; display: flex; flex-direction: column">
      <div style="margin-bottom: 12px; margin-top: 0; display: flex; align-items: center; gap: 8px; flex-wrap: wrap">
        <a-input-search
          style="flex: 1; min-width: 120px"
          placeholder="输入姓名"
          v-model:value="queryParam.realname"
          @search="onSearch"
        />
        <a-button @click="searchReset(1)">重置</a-button>
        <a-button type="primary" @click="selectAll">全选</a-button>
        <a-button type="danger" @click="unselectAll">清空</a-button>
      </div>
      <div style="flex: 1; min-height: 0; overflow: auto">
        <a-empty v-if="selectedDepIds.length === 0" description="请先选择部门！" />
        <a-table
          v-else
          :scroll="{ y: 430 }"
          size="middle"
          row-key="id"
          :columns="columns"
          :data-source="dataSource"
          :pagination="ipagination"
          :row-selection="{ selectedRowKeys: selectedRowKeys, onSelectAll: onSelectAll, onSelect: onSelect, type: getType }"
          :loading="loading"
          @change="handleTableChange"
          :custom-row="customRow"
        />
      </div>
    </a-col>
    <!-- 已选列表 -->
    <a-col :span="8" style="height: 100%; padding: 0 12px; display: flex; flex-direction: column">
      <div style="margin-bottom: 12px; margin-top: 0; display: flex; align-items: center; gap: 8px; flex-wrap: wrap">
        <span style="font-weight: 500">已选 ({{ selectedRows.length }})</span>
        <a-button type="danger" @click="clearSelected">清空</a-button>
      </div>
      <div style="flex: 1; overflow: auto; min-height: 0">
        <SzDeptUserSelectedList
          :selectedUsers="selectedRows"
          @update:selectedUsers="(users) => emit('update:checkedUser', users)"
        />
      </div>
    </a-col>
  </a-row>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, watch, onMounted } from 'vue';
import { queryTreeList } from '/@/api/common/api';
import { defHttp } from '/@/utils/http/axios';
import { filterObj } from '/@/utils/common/compUtils';
import { deleteIfExist, pushIfNotExist, filterDepartTree, recurTree } from './types';
import type { UserItem, DepartTreeNode } from './types';
import SzDeptUserSelectedList from './SzDeptUserSelectedList.vue';

const props = withDefaults(
  defineProps<{
    secLevel: any;
    checkedUser?: UserItem[];
    departId: string;
    role: string | number;
    isSpecial?: number;
    multi?: boolean;
  }>(),
  {
    checkedUser: () => [],
    isSpecial: 0,
    multi: true,
  }
);

const emit = defineEmits(['update:checkedUser']);

const searchDepartValue = ref('');
const queryParam = reactive<Record<string, any>>({ realname: '' });
const dataSource = ref<UserItem[]>([]);
const allUserList = ref<UserItem[]>([]);
const selectedDepIds = ref<string[]>([]);
const selectedRows = ref<UserItem[]>([]);
const departTree = ref<DepartTreeNode[]>([]);
const fullDepartTree = ref<DepartTreeNode[]>([]);
const loading = ref(false);
const expandedKeys = ref<string[]>([]);

function findDepartIdByOrgCode(tree: DepartTreeNode[], orgCode: string): string | null {
  for (const node of tree) {
    if (node.orgCode === orgCode) {
      return node.id;
    }
    if (node.children && node.children.length > 0) {
      const found = findDepartIdByOrgCode(node.children, orgCode);
      if (found) return found;
    }
  }
  return null;
}

function resolveDepartId(departIdOrOrgCode: string): string {
  if (!departIdOrOrgCode) return departIdOrOrgCode;
  const uuidPattern = /^[0-9a-f]{32}$/i;
  if (uuidPattern.test(departIdOrOrgCode.replace(/-/g, ''))) return departIdOrOrgCode;
  const realId = findDepartIdByOrgCode(fullDepartTree.value, departIdOrOrgCode);
  if (realId) return realId;
  return departIdOrOrgCode;
}

const columns = [
  { title: '用户姓名', align: 'center' as const, dataIndex: 'realname' },
  { title: '人员密级', align: 'center' as const, dataIndex: 'userSecurityLevel_dictText' },
];

const ipagination = reactive({
  current: 1,
  pageSize: 7,
  showQuickJumper: true,
  total: 0,
});

const isorter = reactive({
  column: 'createTime',
  order: 'desc',
});

const url = {
  pageUserDepart: '/sys/user/queryUserComponentData',
  listUserDepart: '/sys/user/queryUserComponentData',
};

const getType = computed(() => (props.multi ? 'checkbox' : 'radio'));
const selectedRowKeys = computed(() => selectedRows.value.map((item) => item.id));

const filterDepartTreeData = computed(() => {
  if (!searchDepartValue.value) return departTree.value;
  return filterDepartTree(departTree.value, searchDepartValue.value);
});

watch(
  () => props.checkedUser,
  () => {
    selectedRows.value = [...(props.checkedUser || [])];
  }
);

watch(
  () => props.departId,
  () => {
    queryDepartTree();
  },
  { immediate: true }
);

watch(
  () => props.role,
  () => {
    queryDepartTree();
  }
);

watch(
  () => props.secLevel,
  () => {
    if (selectedDepIds.value.length > 0) {
      getAllUsersInDepart();
      loadData();
    }
  }
);

function initData() {
  const depId = props.departId;
  if (depId) {
    const resolvedId = resolveDepartId(depId);
    selectedDepIds.value = [resolvedId];
    getAllUsersInDepart();
    loadData();
  }
  if (props.checkedUser) {
    selectedRows.value = [...props.checkedUser];
  }
}

async function loadData(arg?: number) {
  if (selectedDepIds.value.length > 0) {
    if (arg === 1) {
      ipagination.current = 1;
    }
    const params = getQueryParams();
    loading.value = true;
    try {
      const res: any = await defHttp.get({ url: url.pageUserDepart, params });
      dataSource.value = (res.records || []).filter((user: UserItem) => {
        const userLevel = user.userSecurityLevel;
        const docLevel = props.secLevel;
        return userLevel !== null && userLevel > docLevel;
      });
      ipagination.total = res.total;
    } finally {
      loading.value = false;
    }
  }
}

function getQueryParams() {
  const param = Object.assign({}, queryParam, isorter);
  param.searchSecurityLevel = props.secLevel;
  param.field = getQueryField();
  param.pageNo = ipagination.current;
  param.pageSize = ipagination.pageSize;
  param.departId = selectedDepIds.value.join(',');
  param.isSpecial = props.isSpecial;
  return filterObj(param);
}

function getQueryField() {
  let str = 'id,';
  for (let a = 0; a < columns.length; a++) {
    str += ',' + columns[a].dataIndex;
  }
  return str;
}

function searchReset(num?: number) {
  if (num !== 0) {
    queryParam.realname = '';
    loadData(1);
  }
}

function handleTableChange(pagination: any, _filters: any, sorter: any) {
  if (Object.keys(sorter).length > 0) {
    isorter.column = sorter.field;
    isorter.order = sorter.order === 'ascend' ? 'asc' : 'desc';
  }
  Object.assign(ipagination, pagination);
  loadData();
}

async function getAllUsersInDepart() {
  if (selectedDepIds.value.length === 0 || (selectedDepIds.value.length === 1 && !selectedDepIds.value[0])) {
    allUserList.value = [];
    return;
  }
  const param = Object.assign({}, queryParam);
  param.searchSecurityLevel = props.secLevel;
  param.field = getQueryField();
  param.departId = selectedDepIds.value.join(',');
  param.isSpecial = props.isSpecial;
  param.pageNo = 1;
  param.pageSize = 9999;
  const filteredParam = filterObj(param);
  try {
    const res: any = await defHttp.get({ url: url.listUserDepart, params: filteredParam });
    allUserList.value = (res.records || res).filter((user: UserItem) => {
      const userLevel = user.userSecurityLevel;
      const docLevel = props.secLevel;
      return userLevel !== null && userLevel > docLevel;
    });
  } catch (e) {
    allUserList.value = [];
  }
}

function onDepSelect(keys: string[]) {
  if (keys.length > 0 && keys[0] != null) {
    selectedDepIds.value = [keys[0]];
    loadData(1);
    getAllUsersInDepart();
  }
}

function onSelect(record: UserItem, selected: boolean) {
  if (selected) {
    pushIfNotExist(selectedRows.value, record, 'id');
  } else {
    deleteIfExist(selectedRows.value, record, 'id');
  }
  selectedRows.value.sort((a, b) => (a.sortno || 0) - (b.sortno || 0));
  emit('update:checkedUser', selectedRows.value);
}

function onSelectAll(selected: boolean, selectedRecords: UserItem[], changeRecords: UserItem[]) {
  if (selected) {
    selectedRecords.forEach((item) => {
      pushIfNotExist(selectedRows.value, item, 'id');
    });
  } else {
    const rowsToRemove = changeRecords && changeRecords.length > 0 ? changeRecords : dataSource.value;
    rowsToRemove.forEach((item) => {
      deleteIfExist(selectedRows.value, item, 'id');
    });
  }
  selectedRows.value.sort((a, b) => (a.sortno || 0) - (b.sortno || 0));
  emit('update:checkedUser', selectedRows.value);
}

function onSearch() {
  loadData(1);
}

async function queryDepartTree() {
  expandedKeys.value = [];
  departTree.value = [];
  try {
    const res: any = await queryTreeList();
    const arr = [...res];
    fullDepartTree.value = [...arr];

    if (props.role === 1 || props.role === '1') {
      departTree.value = [...arr];
    } else {
      const resolvedDepartId = resolveDepartId(props.departId);
      const tree = recurTree(arr, (node) => {
        if (node.id === resolvedDepartId) return [node];
        return [];
      });
      departTree.value = [...tree];
    }
    departTree.value.forEach((item) => {
      expandedKeys.value.push(item.key);
    });
    await initData();
  } catch (e) {
    console.error('queryDepartTree error:', e);
  }
}

function selectAll() {
  allUserList.value.forEach((item) => {
    pushIfNotExist(selectedRows.value, item, 'id');
  });
  selectedRows.value.sort((a, b) => (a.sortno || 0) - (b.sortno || 0));
  emit('update:checkedUser', selectedRows.value);
}

function unselectAll() {
  allUserList.value.forEach((item) => {
    deleteIfExist(selectedRows.value, item, 'id');
  });
  emit('update:checkedUser', selectedRows.value);
}

function clearSelected() {
  selectedRows.value = [];
  emit('update:checkedUser', selectedRows.value);
}

function customRow(record: UserItem) {
  return {
    onClick: (_event: Event) => {
      const clickRowKey = record.id;
      if (selectedRowKeys.value.includes(clickRowKey)) {
        deleteIfExist(selectedRows.value, record, 'id');
      } else {
        pushIfNotExist(selectedRows.value, record, 'id');
      }
      selectedRows.value.sort((a, b) => (a.sortno || 0) - (b.sortno || 0));
      emit('update:checkedUser', selectedRows.value);
    },
  };
}

onMounted(async () => {
  await queryDepartTree();
});
</script>

<style scoped>
.ant-table-tbody .ant-table-row td {
  padding-top: 10px;
  padding-bottom: 10px;
}
</style>
