<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="deptList" row-key="deptId" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
        <el-table-column prop="deptName" label="部门名称" width="200" />
        <el-table-column prop="annualBudget" label="年度预算" align="center" />
        <el-table-column prop="monthlyQuota" label="月采限额" align="center" />
        <el-table-column prop="budgetUsed" label="已用预算" align="center" />
        <el-table-column prop="shopAddressId" 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="deptFormRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="上级部门" prop="parentId">
          <el-tree-select
            v-model="form.parentId"
            :data="deptOptions"
            :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="annualBudget">
          <el-input v-model="form.annualBudget" placeholder="请输入年度预算" />
        </el-form-item>
        <el-form-item label="月采限额" prop="monthlyQuota">
          <el-input v-model="form.monthlyQuota" placeholder="请输入月采限额" />
        </el-form-item>
        <el-form-item label="已用预算" prop="budgetUsed">
          <el-input v-model="form.budgetUsed" placeholder="请输入已用预算" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio value="0">启用</el-radio>
            <el-radio value="1">未启用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否绑定">
          <el-switch v-model="form.isBound" :active-value="'0'" :inactive-value="'1'" />
        </el-form-item>
        <el-form-item v-if="form.isBound === '0'" label="绑定地址" prop="shopAddressId">
          <el-select v-model="form.shopAddressId" 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="OrgStructure" lang="ts">
import { listDept, getDept, delDept, addDept, updateDept, listDeptExcludeChild } from '@/api/system/dept';
import { DeptForm, DeptQuery, DeptVO } from '@/api/system/dept/types';

interface DeptOptionsType {
  deptId: number | string;
  deptName: string;
  children: DeptOptionsType[];
}

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

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const deptList = ref<DeptVO[]>([]);
const deptOptions = ref<DeptOptionsType[]>([]);
const loading = ref(false);
const buttonLoading = ref(false);

const deptFormRef = ref<ElFormInstance>();

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

const initFormData: DeptForm = {
  deptId: undefined,
  parentId: undefined,
  deptName: '',
  annualBudget: undefined,
  monthlyQuota: undefined,
  budgetUsed: undefined,
  isBound: '1',
  shopAddressId: undefined,
  status: '0',
  orderNum: -1,
  customerId: undefined
};

const form = ref<DeptForm>({ ...initFormData });

const rules = {
  parentId: [{ required: false, message: '请选择上级部门', trigger: 'change' }],
  deptName: [{ required: true, message: '请输入部门名称', trigger: 'blur' }],
  annualBudget: [{ required: true, message: '请输入年度预算', trigger: 'blur' }],
  monthlyQuota: [{ required: true, message: '请输入月采限额', trigger: 'blur' }],
  budgetUsed: [{ required: true, message: '请输入已用预算', trigger: 'blur' }],
  shopAddressId: [{ required: true, message: '请选择绑定地址', trigger: 'change' }]
};

/** 查询部门列表 */
const getList = async () => {
  loading.value = true;
  const queryParams = {
    customerId: props.customerId
  };
  try {
    const res = await listDept(queryParams);
    deptList.value = proxy?.handleTree(res.data, 'deptId') || [];
  } finally {
    loading.value = false;
  }
};

/** 查询部门下拉树结构 */
const getTreeSelect = async () => {
  const queryParams = {
    customerId: props.customerId
  };
  const res = await listDept(queryParams);
  deptOptions.value = proxy?.handleTree(res.data, 'deptId') || [];
};

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

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

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

/** 修改按钮操作 */
const handleUpdate = async (row: DeptVO) => {
  reset();
  await getTreeSelect();
  const res = await getDept(row.deptId);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改部门';
};

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

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

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