<template>
  <div class="page-container staff-manage">
    <PageTitle title="人员管理" />

    <div class="main-content">
      <!-- 左侧部门树 -->
      <div class="dept-tree">
        <el-tree
          :data="deptTreeData"
          :props="{ label: 'deptName', children: 'children' }"
          node-key="deptId"
          default-expand-all
          highlight-current
          @node-click="handleDeptClick"
        >
          <template #default="{ node, data }">
            <span :class="['tree-node', { active: currentDeptId === data.deptId }]">{{ node.label }}</span>
          </template>
        </el-tree>
      </div>

      <!-- 右侧人员列表 -->
      <div class="staff-list">
        <!-- 操作栏 -->
        <div class="action-bar">
          <el-input v-model="queryParams.contactName" placeholder="搜索员工姓名" style="width: 200px" clearable @keyup.enter="handleQuery">
            <template #prefix
              ><el-icon><Search /></el-icon
            ></template>
          </el-input>
          <div class="action-buttons">
            <el-button type="danger" @click="handleAdd">+ 新增</el-button>
            <el-button :disabled="selectedRows.length === 0" @click="handleBatchDelete">批量删除</el-button>
          </div>
        </div>

        <!-- 表格 -->
        <el-table :data="staffList" border @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column prop="contactName" label="姓名" min-width="100" align="center" />
          <el-table-column prop="phone" label="手机号" min-width="140" align="center" />
          <el-table-column prop="roleName" label="角色" min-width="120" align="center" />
          <el-table-column prop="deptName" label="部门名称" min-width="120" align="center" />
          <el-table-column prop="status" label="状态" min-width="80" align="center">
            <template #default="{ row }">
              <span :class="['status-text', row.status === '启用' ? 'active' : '']">{{ row.status == '0' ? '启用' : '禁用' }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100" align="center">
            <template #default="{ row }">
              <el-button type="primary" link size="small" @click="handleEdit(row)">编辑</el-button>
              <el-button type="danger" link size="small" @click="handleDelete(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <TablePagination v-model:page="queryParams.pageNum" v-model:page-size="queryParams.pageSize" :total="total" @change="handleQuery" />
      </div>
    </div>

    <!-- 新增/编辑弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px" destroy-on-close>
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px">
        <el-form-item label="姓名" prop="contactName">
          <el-input v-model="formData.contactName" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="formData.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="所属部门" prop="deptId">
          <el-tree-select
            v-model="formData.deptId"
            :data="deptTreeData"
            :props="{ label: 'deptName', children: 'children' }"
            node-key="deptId"
            placeholder="请选择部门"
            style="width: 100%"
            check-strictly
            :render-after-expand="false"
            @change="handleDeptChange"
          />
        </el-form-item>
        <el-form-item label="角色" prop="roleId">
          <el-select v-model="formData.roleId" placeholder="请选择角色" style="width: 100%" @change="handRoleChange">
            <el-option v-for="role in roleList" :key="role.roleId" :label="role.roleName" :value="role.roleId.toString()" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="formData.status">
            <el-radio label="0">启用</el-radio>
            <el-radio label="1">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="danger" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, getCurrentInstance, ComponentInternalInstance } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search } from '@element-plus/icons-vue';
import { PageTitle, TablePagination } from '@/components';
import { DeptInfo } from '@/api/pc/organization/types';
import { getDeptTree, getRoleList, getContactList, addContact, updateContact, deleteContact } from '@/api/pc/organization';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const currentDeptId = ref<number | null>(null);
const dialogVisible = ref(false);
const formRef = ref();
const editingRow = ref<any>(null);
const selectedRows = ref<any[]>([]);

const queryParams = reactive({ pageNum: 1, pageSize: 10, deptId: null as number | null, contactName: '' });
const total = ref(0);

const deptTreeData = ref<DeptInfo[]>([]);

const formData = reactive({
  id: null,
  contactName: '',
  phone: '',
  deptId: null as number | null,
  deptName: '',
  roleId: '',
  roleName: '',
  status: '0'
});

const formRules = {
  contactName: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
  deptId: [{ required: true, message: '请选择部门', trigger: 'change' }]
};

const dialogTitle = computed(() => (editingRow.value ? '编辑人员' : '新增人员'));

// 人员列表数据
const staffList = ref([]);
const roleList = ref<any[]>([]);

// 加载部门树
const loadDeptTree = async () => {
  try {
    const res = await getDeptTree();
    if (res.code === 200 && res.data) {
      deptTreeData.value = res.data;

      if (Array.isArray(res.data)) {
        const treeData = proxy?.handleTree<DeptInfo>(res.data, 'deptId', 'parentId');
        deptTreeData.value = treeData || res.data;
      } else {
        deptTreeData.value = [];
      }
    }
  } catch (error) {
    console.error('获取部门树失败:', error);
    ElMessage.error('获取部门树失败');
  }
};

// 加载角色列表
const loadRoleList = async () => {
  try {
    roleList.value = [
      { roleId: 1, roleName: '管理角色' },
      { roleId: 2, roleName: '采购角色' },
      { roleId: 3, roleName: '查询角色' },
      { roleId: 4, roleName: '审核角色' }
    ];
    // const res = await getRoleList(queryParams);
    // if (res.code === 200 && res.data) {
    //   roleList.value = res.data;
    // }
  } catch (error) {
    console.error('获取角色列表失败:', error);
  }
};

const handleDeptChange = (value: any) => {
  console.log(value);
  // 定义递归查找函数
  const findNode = (nodes: any[], id: any): any => {
    for (const node of nodes) {
      // 类型转换后比较
      if (String(node.deptId) === String(id)) {
        return node;
      }
      // 如果有子节点，递归查找
      if (node.children && node.children.length > 0) {
        const found = findNode(node.children, id);
        if (found) return found;
      }
    }
    return null;
  };

  const selectedDept = findNode(deptTreeData.value, value);

  if (selectedDept) {
    formData.deptName = selectedDept.deptName;
    formData.deptId = selectedDept.deptId;
  }
};

const handRoleChange = (value: number) => {
  const selectedRole = roleList.value.find((item) => item.roleId === value);
  if (selectedRole) {
    formData.roleName = selectedRole.roleName;
  }
};

// 加载员工列表
const loadContactList = async () => {
  try {
    const params: any = {
      pageNum: queryParams.pageNum,
      pageSize: queryParams.pageSize
    };

    if (queryParams.deptId) params.deptId = queryParams.deptId;
    if (queryParams.contactName) params.contactName = queryParams.contactName;

    const res = await getContactList(params);
    if (res.code === 200) {
      staffList.value = res.rows;
      total.value = res.total || 0;
    }
  } catch (error) {
    console.error('获取员工列表失败:', error);
    ElMessage.error('获取员工列表失败');
  }
};

const handleDeptClick = (data: any) => {
  currentDeptId.value = data.deptId;
  queryParams.deptId = data.deptId;
  queryParams.pageNum = 1;
  loadContactList();
};

const handleQuery = () => {
  queryParams.pageNum = 1;
  loadContactList();
};

const handleSelectionChange = (rows: any[]) => {
  selectedRows.value = rows;
};

const handleAdd = () => {
  editingRow.value = null;
  formData.contactName = '';
  formData.phone = '';
  formData.deptId = currentDeptId.value;
  formData.roleId = '';
  formData.status = '0';
  dialogVisible.value = true;
};

const handleEdit = (row: any) => {
  editingRow.value = row;
  formData.id = row.id;
  formData.contactName = row.contactName;
  formData.phone = row.phone;
  formData.deptId = row.deptId;
  formData.roleId = row.roleId;
  formData.status = row.status;
  dialogVisible.value = true;
};

const handleBatchDelete = () => {
  ElMessageBox.confirm(`确定要删除选中的 ${selectedRows.value.length} 名人员吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteContact(selectedRows.value.map((item) => item.id));
    ElMessage.success('删除成功');
  });
};

const handleDelete = (row: any) => {
  ElMessageBox.confirm(`确定要删除"${row.contactName}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const index = staffList.value.findIndex((item) => item.id === row.id);
    if (index > -1) {
      staffList.value.splice(index, 1);
    }
    ElMessage.success('删除成功');
  });
};

const handleSubmit = async () => {
  const valid = await formRef.value?.validate();
  if (!valid) return;
  if (editingRow.value) {
    await updateContact(formData);
    ElMessage.success('编辑成功');
  } else {
    await addContact(formData);
    ElMessage.success('新增成功');
  }
  loadContactList();
  dialogVisible.value = false;
};

// 页面加载时获取部门树和员工列表
onMounted(() => {
  loadDeptTree();
  loadRoleList();
  loadContactList();
});
</script>

<style scoped lang="scss">
.staff-manage {
  .main-content {
    display: flex;
    gap: 20px;
    min-height: 500px;
  }

  .dept-tree {
    width: 200px;
    flex-shrink: 0;
    border-right: 1px solid #eee;
    padding-right: 15px;

    .tree-node {
      font-size: 14px;
      color: #333;
      &.active {
        color: #e60012;
      }
    }

    :deep(.el-tree-node__content) {
      height: 36px;
    }

    :deep(.el-tree-node.is-current > .el-tree-node__content) {
      background-color: #fff5f5;
      .tree-node {
        color: #e60012;
      }
    }
  }

  .staff-list {
    flex: 1;
    min-width: 0;

    .action-bar {
      margin-bottom: 15px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      gap: 10px;

      .action-buttons {
        display: flex;
        gap: 10px;
      }
    }

    .status-text {
      color: #999;
      &.active {
        color: #67c23a;
      }
    }
  }
}

:deep(.el-table) {
  th.el-table__cell {
    background: #fafafa;
    font-weight: 500;
    color: #333;
  }
}
</style>
