<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="数据来源" prop="dataSource">
              <el-input v-model="queryParams.dataSource" placeholder="请输入数据来源" clearable @keyup.enter="handleQuery" />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="20"><span>部门设定</span> </el-col>
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd()" v-hasPermi="['system:comDept:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="info" plain icon="Sort" @click="handleToggleExpandAll">展开/折叠</el-button>
          </el-col>
        </el-row>
      </template>
      <el-table
        ref="comDeptTableRef"
        v-loading="loading"
        :data="comDeptList"
        row-key="id"
        border
        :default-expand-all="isExpandAll"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <!-- <el-table-column label="部门编码" prop="deptCode" /> -->
        <el-table-column label="部门名称" align="center" prop="deptName" />
        <el-table-column label="生效日期" align="center" prop="validFrom" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.validFrom, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="失效日期" align="center" prop="validTo" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.validTo, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="主管" align="center" prop="leader" />
        <el-table-column label="是否启用" align="center" prop="status">
          <template #default="scope">
            <el-switch v-model="scope.row.status" active-value="0" inactive-value="1" @change="handleStatusChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="数据来源" align="center" prop="dataSource" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button link type="primary" icon="Plus" @click="handleAdd(scope.row)" v-hasPermi="['system:comDept:add']">新增</el-button>

            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:comDept:edit']">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加或修改企业部门对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="comDeptFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="部门名称" prop="deptName">
          <el-input v-model="form.deptName" placeholder="请输入部门名称" />
        </el-form-item>
        <el-form-item label="父部门ID" prop="parentId">
          <el-tree-select
            v-model="form.parentId"
            :data="comDeptOptions"
            :props="{ value: 'id', label: 'deptName', children: 'children' }"
            value-key="id"
            placeholder="请选择父部门ID"
            check-strictly
          />
        </el-form-item>
        <el-form-item label="是否启用" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in sys_platform_yes_no" :key="dict.value" :value="dict.value">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="生效日期" prop="validFrom">
          <el-date-picker clearable v-model="form.validFrom" type="date" value-format="YYYY-MM-DD" placeholder="选择生效日期" />
        </el-form-item>
        <el-form-item label="失效日期" prop="validTo">
          <el-date-picker clearable v-model="form.validTo" type="date" value-format="YYYY-MM-DD" placeholder="选择失效日期" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ComDept" lang="ts">
import { listComDept, getComDept, delComDept, addComDept, updateComDept, changeStatus } from '@/api/company/comDept';
import { ComDeptVO, ComDeptQuery, ComDeptForm } from '@/api/company/comDept/types';

type ComDeptOption = {
  id: number;
  deptName: string;
  children?: ComDeptOption[];
};

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

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

const comDeptList = ref<ComDeptVO[]>([]);
const comDeptOptions = ref<ComDeptOption[]>([]);
const buttonLoading = ref(false);
const showSearch = ref(true);
const isExpandAll = ref(true);
const loading = ref(false);

const queryFormRef = ref<ElFormInstance>();
const comDeptFormRef = ref<ElFormInstance>();
const comDeptTableRef = ref<ElTableInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: ComDeptForm = {
  id: undefined,
  deptCode: undefined,
  companyId: undefined,
  deptName: undefined,
  parentId: undefined,
  ancestors: undefined,
  deptCategory: undefined,
  level: undefined,
  leader: undefined,
  phone: undefined,
  email: undefined,
  validFrom: undefined,
  validTo: undefined,
  status: '0',
  dataSource: undefined,
  orderNum: undefined
};

const data = reactive<PageData<ComDeptForm, ComDeptQuery>>({
  form: { ...initFormData },
  queryParams: {
    deptCode: undefined,
    companyId: undefined,
    deptName: undefined,
    parentId: undefined,
    ancestors: undefined,
    deptCategory: undefined,
    level: undefined,
    leader: undefined,
    phone: undefined,
    email: undefined,
    validFrom: undefined,
    validTo: undefined,
    status: undefined,
    dataSource: undefined,
    orderNum: undefined,
    platformCode: undefined,
    params: {}
  },
  rules: {
    deptName: [{ required: true, message: '部门名称不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询企业部门列表 */
const getList = async () => {
  loading.value = true;
  const res = await listComDept(queryParams.value);
  const data = proxy?.handleTree<ComDeptVO>(res.data, 'id', 'parentId');
  if (data) {
    comDeptList.value = data;
    loading.value = false;
  }
};

const handleStatusChange = async (row: ComDeptVO) => {
  const oldValue = row.status; // 保存旧值（0 或 1）

  try {
    await changeStatus(row.id, row.status); // 传新值
    proxy?.$modal.msgSuccess('操作成功');
  } catch {
    row.status = oldValue; // 失败回滚
    proxy?.$modal.msgError('操作失败，请重试');
  }
};

/** 查询企业部门下拉树结构 */
const getTreeselect = async () => {
  const res = await listComDept();
  comDeptOptions.value = [];
  const data: ComDeptOption = { id: 0, deptName: '顶级节点', children: [] };
  data.children = proxy?.handleTree<ComDeptOption>(res.data, 'id', 'parentId');
  comDeptOptions.value.push(data);
};

// 取消按钮
const cancel = () => {
  reset();
  dialog.visible = false;
};

// 表单重置
const reset = () => {
  form.value = { ...initFormData };
  comDeptFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 新增按钮操作 */
const handleAdd = (row?: ComDeptVO) => {
  reset();
  getTreeselect();
  if (row != null && row.id) {
    form.value.parentId = row.id;
  } else {
    form.value.parentId = 0;
  }
  dialog.visible = true;
  dialog.title = '添加企业部门';
};

/** 展开/折叠操作 */
const handleToggleExpandAll = () => {
  isExpandAll.value = !isExpandAll.value;
  toggleExpandAll(comDeptList.value, isExpandAll.value);
};

/** 展开/折叠操作 */
const toggleExpandAll = (data: ComDeptVO[], status: boolean) => {
  data.forEach((item) => {
    comDeptTableRef.value?.toggleRowExpansion(item, status);
    if (item.children && item.children.length > 0) toggleExpandAll(item.children, status);
  });
};

/** 修改按钮操作 */
const handleUpdate = async (row: ComDeptVO) => {
  reset();
  await getTreeselect();
  if (row != null) {
    form.value.parentId = row.parentId;
  }
  const res = await getComDept(row.id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改企业部门';
};

/** 提交按钮 */
const submitForm = () => {
  comDeptFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateComDept(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addComDept(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row: ComDeptVO) => {
  await proxy?.$modal.confirm('是否确认删除企业部门编号为"' + row.id + '"的数据项？');
  loading.value = true;
  await delComDept(row.id).finally(() => (loading.value = false));
  await getList();
  proxy?.$modal.msgSuccess('删除成功');
};

onMounted(() => {
  getList();
});
</script>
