<template>
  <div class="p-2">
    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="22">
            <span>企业组织结构信息列表</span>
          </el-col>
          <el-col :span="2" style="text-align: right">
            <el-button type="primary" plain icon="Plus" @click="handleAdd">新增部门</el-button>
          </el-col>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="customerDeptList" row-key="deptId" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
        <el-table-column prop="deptName" label="部门名称" width="200" />
        <el-table-column prop="yearlyBudget" label="年度预算" align="center" />
        <el-table-column prop="monthLimit" label="月采限额" align="center" />
        <el-table-column prop="usedBudget" label="已用预算" align="center" />
        <el-table-column prop="bindAddress" label="绑定地址" align="center" />
        <el-table-column label="状态" align="center">
          <template #default="scope">
            <el-tag v-if="scope.row.status === '0'" type="success">启用</el-tag>
            <el-tag v-else type="info">未启用</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200">
          <template #default="scope">
            <el-button link type="primary" @click="handleUpdate(scope.row)">编辑</el-button>
            <el-button link type="primary" @click="handleAdd(scope.row)">新增</el-button>
            <el-button link type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增/编辑部门对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="700px" append-to-body>
      <el-form ref="customerDeptFormRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="上级部门" prop="parentId">
          <el-tree-select
            v-model="form.parentId"
            :data="customerDeptOptions"
            :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="form.deptName" placeholder="请输入部门名称" />
        </el-form-item>
        <el-form-item label="年度预算" prop="yearlyBudget">
          <el-input v-model="form.yearlyBudget" placeholder="请输入年度预算" />
        </el-form-item>
        <el-form-item label="月采限额" prop="monthLimit">
          <el-input v-model="form.monthLimit" placeholder="请输入月采限额" />
        </el-form-item>
        <el-form-item label="已用预算" prop="usedBudget">
          <el-input v-model="form.usedBudget" placeholder="请输入已用预算" />
        </el-form-item>
        <el-form-item label="是否启用">
          <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="是否绑定">
          <el-switch v-model="form.bindStatus" :active-value="'0'" :inactive-value="'1'" />
        </el-form-item>
        <el-form-item v-if="form.bindStatus === '0'" label="绑定地址" prop="bindAddress">
          <el-select v-model="form.bindAddress" placeholder="请选择" style="width: 100%">
            <el-option label="地址1" value="address1" />
            <el-option label="地址2" value="address2" />
          </el-select>
        </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="CustomerDept" lang="ts">
import { listCustomerDept, getCustomerDept, delCustomerDept, addCustomerDept, updateCustomerDept } from '@/api/customer/customerFile/customerDept';
import { CustomerDeptVO, CustomerDeptQuery, CustomerDeptForm } from '@/api/customer/customerFile/customerDept/types';
import { delDept } from '@/api/system/dept';

type CustomerDeptOption = {
  deptId: number;
  deptName: string;
  children?: CustomerDeptOption[];
};

// 接收父组件传递的props
const props = defineProps<{
  customerId?: string | number;
  customerNo?: string;
  customerName?: string;
}>();

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

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

const customerDeptList = ref<CustomerDeptVO[]>([]);
const customerDeptOptions = ref<CustomerDeptOption[]>([]);
const buttonLoading = ref(false);
const showSearch = ref(true);
const isExpandAll = ref(true);
const loading = ref(false);

const queryFormRef = ref<ElFormInstance>();
const customerDeptFormRef = ref<ElFormInstance>();
const customerDeptTableRef = ref<ElTableInstance>();

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

const initFormData: CustomerDeptForm = {
  deptId: undefined,
  deptNo: undefined,
  deptName: undefined,
  parentId: undefined,
  ancestors: undefined,
  customerId: undefined,
  yearlyBudget: undefined,
  usedBudget: undefined,
  monthLimit: undefined,
  monthUsedBudget: undefined,
  bindStatus: undefined,
  bindAddress: undefined,
  deptManage: undefined,
  isLimit: undefined,
  selectYear: undefined,
  expenseType: undefined,
  residueYearlyBudget: undefined,
  recharge: undefined,
  status: '0',
  remark: undefined
};

const data = reactive<PageData<CustomerDeptForm, CustomerDeptQuery>>({
  form: { ...initFormData },
  queryParams: {
    deptName: undefined,
    parentId: undefined,
    ancestors: undefined,
    customerId: undefined,
    yearlyBudget: undefined,
    usedBudget: undefined,
    monthLimit: undefined,
    monthUsedBudget: undefined,
    bindStatus: undefined,
    bindAddress: undefined,
    deptManage: undefined,
    isLimit: undefined,
    selectYear: undefined,
    expenseType: undefined,
    residueYearlyBudget: undefined,
    recharge: undefined,
    status: undefined,
    platformCode: undefined,
    params: {}
  },
  rules: {
    deptName: [{ required: true, message: '部门名称不能为空', trigger: 'blur' }],
    customerId: [{ required: true, message: '客户编号不能为空', trigger: 'blur' }],
    yearlyBudget: [{ required: true, message: '年度预算不能为空', trigger: 'blur' }],
    usedBudget: [{ required: true, message: '已使用预算不能为空', trigger: 'blur' }],
    monthLimit: [{ required: true, message: '月度限额不能为空', trigger: 'blur' }],
    bindStatus: [{ required: true, message: '绑定状态不能为空', trigger: 'change' }]
  }
});

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

/** 查询客户部门信息列表 */
const getList = async () => {
  loading.value = true;
  try {
    queryParams.value.customerId = props.customerId;
    const res = await listCustomerDept(queryParams.value);
    // 如果返回的数据是数组，直接使用；否则尝试构建树形结构
    if (Array.isArray(res.data)) {
      const treeData = proxy?.handleTree<CustomerDeptVO>(res.data, 'deptId', 'parentId');
      customerDeptList.value = treeData || res.data;
    } else {
      customerDeptList.value = [];
    }
  } finally {
    loading.value = false;
  }
};

/** 查询客户部门信息下拉树结构 */
const getTreeselect = async () => {
  const query: CustomerDeptQuery = {
    customerId: props.customerId
  };
  const res = await listCustomerDept(query);
  customerDeptOptions.value = proxy?.handleTree<CustomerDeptOption>(res.data, 'deptId', 'parentId') || [];
};

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

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

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

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

/** 新增按钮操作 */
const handleAdd = async (row?: CustomerDeptVO) => {
  reset();
  await getTreeselect();
  if (row != null && row.deptId) {
    form.value.parentId = row.deptId;
  }
  // 设置客户ID
  form.value.customerId = props.customerId;
  form.value.bindStatus = '1';
  dialog.visible = true;
  dialog.title = '新增部门';
};

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

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

/** 修改按钮操作 */
const handleUpdate = async (row: CustomerDeptVO) => {
  reset();
  await getTreeselect();
  const res = await getCustomerDept(row.deptId);
  Object.assign(form.value, res.data);
  // 修正数据：如果 parentId 等于自己的 id，说明是顶级部门，将 parentId 设为 0
  if (form.value.parentId === form.value.deptId) {
    form.value.parentId = 0;
  }
  dialog.visible = true;
  dialog.title = '修改部门';
};

/** 提交按钮 */
const submitForm = () => {
  customerDeptFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      try {
        // 确保提交时包含客户ID
        const submitData = {
          ...form.value,
          customerId: props.customerId
        };
        if (form.value.deptId) {
          await updateCustomerDept(submitData);
          proxy?.$modal.msgSuccess('修改成功');
        } else {
          await addCustomerDept(submitData);
          proxy?.$modal.msgSuccess('新增成功');
        }
        dialog.visible = false;
        await getList();
      } finally {
        buttonLoading.value = false;
      }
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row: CustomerDeptVO) => {
  await proxy?.$modal.confirm('是否确认删除名称为"' + row.deptName + '"的数据项?');
  await delDept(row.deptId);
  await getList();
  proxy?.$modal.msgSuccess('删除成功');
};

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