<template>
  <div class="page-container">
    <div class="page-header">
      <PageTitle title="部门管理" />
      <el-button type="danger" @click="handleAdd(null)">+ 新增部门</el-button>
    </div>

    <el-table :data="deptList" row-key="deptId" default-expand-all :tree-props="{ children: 'children' }" :indent="24">
      <el-table-column prop="deptName" label="部门" min-width="250" />
      <el-table-column prop="status" label="状态" width="100" align="center">
        <template #default="{ row }">
          {{ row.status === '0' ? '启用' : '停用' }}
        </template>
      </el-table-column>
      <el-table-column prop="yearlyBudget" label="现有额度(年)" width="130" align="center">
        <template #default="{ row }">
          {{ row.yearlyBudget || '0.00' }}
        </template>
      </el-table-column>
      <el-table-column prop="usedBudget" label="已用额度(年)" width="130" align="center">
        <template #default="{ row }">
          {{ row.usedBudget || '0.00' }}
        </template>
      </el-table-column>
      <el-table-column label="剩余额度(年)" width="130" align="center">
        <template #default="{ row }">
          {{ (row.yearlyBudget || 0) - (row.usedBudget || 0) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" 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="handleAdd(row)">新增</el-button>
          <el-button type="danger" link size="small" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增/编辑部门弹窗 -->
    <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="上级部门">
          <el-tree-select
            v-model="formData.parentId"
            :data="deptList"
            :props="{ value: 'deptId', label: 'deptName', children: 'children' }"
            value-key="deptId"
            placeholder="请选择"
            check-strictly
            :render-after-expand="false"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="部门名称" prop="deptName">
          <el-input v-model="formData.deptName" placeholder="请输入部门名称" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <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-item label="年度额度">
          <el-input-number v-model="formData.yearlyBudget" :min="0" :precision="2" controls-position="right" style="width: 200px" />
        </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 } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { PageTitle } from '@/components';
import { getDeptTree, addDept, updateDept, deleteDept } from '@/api/pc/organization';
import { DeptInfo } from '@/api/pc/organization/types';
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const { sys_platform_yes_no } = toRefs<any>(proxy?.useDict('sys_platform_yes_no'));

const dialogVisible = ref(false);
const formRef = ref();
const editingRow = ref<any>(null);
const parentRow = ref<any>(null);

const formData = reactive({
  deptId: undefined,
  deptName: '',
  parentId: undefined,
  status: '0',
  yearlyBudget: 0,
  parentName: ''
});

const formRules = {
  deptName: [{ required: true, message: '请输入部门名称', trigger: 'blur' }]
};

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

const deptList = ref([]);

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

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

const handleAdd = (parent: any) => {
  editingRow.value = null;
  parentRow.value = parent;
  formData.deptId = undefined;
  formData.deptName = '';
  formData.parentId = parent ? parent.deptId : undefined;
  formData.status = '0';
  formData.yearlyBudget = 0;
  formData.parentName = parent ? parent.parentName : '';
  dialogVisible.value = true;
};

const handleEdit = (row: any) => {
  editingRow.value = row;
  parentRow.value = null;
  formData.deptId = row.deptId;
  formData.deptName = row.deptName;
  formData.parentId = row.parentId == 100 ? undefined : row.parentId;
  formData.status = row.status || '0';
  formData.yearlyBudget = row.yearlyBudget || 0;
  formData.parentName = '';
  dialogVisible.value = true;
};

const handleDelete = (row: any) => {
  ElMessageBox.confirm(`确定要删除部门"${row.deptName}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteDept([row.deptId]);
      ElMessage.success('删除成功');
      await loadDeptTree();
    } catch (error) {
      console.error('删除失败:', error);
      ElMessage.error('删除失败');
    }
  });
};

const handleSubmit = async () => {
  const valid = await formRef.value?.validate();
  if (!valid) return;

  try {
    const data = {
      deptId: formData.deptId,
      deptName: formData.deptName,
      parentId: formData.parentId,
      status: formData.status,
      yearlyBudget: formData.yearlyBudget
    };

    if (editingRow.value) {
      await updateDept(data);
      ElMessage.success('编辑成功');
    } else {
      await addDept(data);
      ElMessage.success('新增成功');
    }

    dialogVisible.value = false;
    await loadDeptTree();
  } catch (error) {
    console.error('保存失败:', error);
    ElMessage.error('保存失败');
  }
};

// 页面加载时获取部门树
onMounted(() => {
  loadDeptTree();
});
</script>

<style scoped lang="scss">
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;

  :deep(.page-title) {
    margin-bottom: 0;
  }
}

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

  .el-table__expand-icon {
    color: #666;
    font-size: 12px;
  }
}
</style>
