<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="18" 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">
        <a-input-search
          style="flex: 1; min-width: 120px"
          placeholder="输入姓名"
          v-model:value="queryParam.realname"
          @search="onSearch"
        />
        <a-button @click="searchReset(1)">重置</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, onSelect: onSelect, type: 'radio', preserveSelectedRowKeys: true }"
          :loading="loading"
          @change="handleTableChange"
        />
      </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 { filterDepartTree, recurTree } from './types';
import type { UserItem, DepartTreeNode } from './types';

const props = withDefaults(
  defineProps<{
    secLevel?: any;
    departId?: string;
    role?: string | number;
    isSpecial?: number;
    checkedUser?: UserItem | null;
  }>(),
  {
    secLevel: 0,
    departId: '',
    role: 1,
    isSpecial: 0,
    checkedUser: undefined,
  }
);

const emit = defineEmits(['select']);

const searchDepartValue = ref('');
const queryParam = reactive<Record<string, any>>({ realname: '' });
const dataSource = ref<UserItem[]>([]);
const selectedDepIds = ref<string[]>([]);
const selectedUser = ref<UserItem | null>(null);
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: 'sortno',
  order: 'asc' as const,
});

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

const selectedRowKeys = computed(() => (selectedUser.value ? [selectedUser.value.id] : []));

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

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

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

watch(
  () => props.checkedUser,
  (user) => {
    selectedUser.value = user || null;
  },
  { immediate: true }
);

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

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) => !user.username.toLowerCase().includes('admin'));
      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();
}

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

function onSelect(record: UserItem, selected: boolean) {
  if (selected) {
    selectedUser.value = record;
    emit('select', record);
  } else {
    selectedUser.value = null;
    emit('select', null);
  }
}

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);
  }
}

onMounted(async () => {
  await queryDepartTree();
});

defineExpose({
  getSelectedUser: () => selectedUser.value,
});
</script>

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