<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="部门名称" min-width="260" />
        <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="bindAddressStr" 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="800px" append-to-body>
      <el-form ref="customerDeptFormRef" :model="form" :rules="rules" label-width="120px">
        <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: 240px"
          />
        </el-form-item>
        <el-form-item label="部门名称" prop="deptName">
          <el-input v-model="form.deptName" placeholder="请输入部门名称" style="width: 240px" />
        </el-form-item>
        <el-form-item label="部门主管" prop="deptManage">
          <el-select v-model="form.deptManage" placeholder="请选择" clearable style="width: 240px">
            <el-option v-for="manage in customerContactList" :key="manage.id" :label="manage.contactName" :value="manage.id" />
          </el-select>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <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-col>
          <el-col :span="12">
            <el-form-item label="是否额度控制">
              <el-radio-group v-model="form.isLimit">
                <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-col>
        </el-row>
        <el-form-item label="选择年度" prop="selectYear">
          <el-date-picker
            v-model="form.selectYear"
            type="year"
            placeholder="请选择年度"
            value-format="YYYY"
            style="width: 240px"
            :disabled="form.isLimit == '1'"
          />
        </el-form-item>
        <div style="color: #999; font-size: 12px; margin-left: 120px; margin-bottom: 18px">
          只能对当期年度进行额度设置，往期年度，显示最后一日数据，无法充值额度。
        </div>
        <el-form-item v-if="form.isLimit === '0'" label="分项费用类型" prop="expenseTypeId">
          <el-select v-model="form.expenseTypeId" placeholder="请选择" style="width: 240px" @change="expenseTypeChange">
            <el-option v-for="item in expenseTypeList" :key="item.id" :label="item.expenseName" :value="item.id" />
          </el-select>
          <!-- <el-button type="primary" link style="margin-left: 12px">查询其他分项费用情况</el-button> -->
        </el-form-item>
        <el-form-item label="现有额度(年)" prop="yearlyBudget">
          <el-input v-model="form.yearlyBudget" style="width: 240px" disabled />
        </el-form-item>
        <el-form-item label="已用额度(年)" prop="usedBudget">
          <el-input v-model="form.usedBudget" style="width: 240px" disabled />
        </el-form-item>
        <el-form-item label="剩余额度" prop="residueYearlyBudget">
          <el-input v-model="form.residueYearlyBudget" style="width: 240px" disabled />
        </el-form-item>
        <el-form-item v-if="form.isLimit === '0'" label="充值额度" prop="recharge">
          <el-input v-model="form.recharge" style="width: 240px" />
        </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="请选择" clearable style="width: 100%">
            <el-option
              v-for="addr in shippingAddressList"
              :key="addr.id"
              :label="(addr.provincialCityCountry || '') + (addr.provincialCityCountry && addr.address ? ' - ' : '') + (addr.address || '')"
              :value="addr.id"
            />
          </el-select>
        </el-form-item>
        <div style="margin-left: 120px; margin-top: 10px">
          <div style="font-weight: bold; margin-bottom: 8px">充值说明：</div>
          <div style="color: #666; font-size: 13px; line-height: 1.8">
            1. 需要给当前部门进行额度充值时，请在充值额度中填写"正数"即可。<br />
            2. 需要给当前部门进行额度扣减时请在充值额度中填写"负数"即可，扣减额度不能高于剩余额度。<br />
            3. 当现有额度为0时，则该部门的此项费用不能进行采购。
          </div>
        </div>
      </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 { listShippingAddress, getShippingAddress } from '@/api/customer/customerFile/shippingAddress';
import { listExpenseType } from '@/api/customer/expenseType';
import { ExpenseTypeVO } from '@/api/customer/expenseType/types';
import { ShippingAddressVO, ShippingAddressQuery, ShippingAddressForm } from '@/api/customer/customerFile/shippingAddress/types';
import { delDept } from '@/api/system/dept';
import { listCustomerContact } from '@/api/customer/customerFile/customerContact';
import { CustomerContactVO } from '@/api/customer/customerFile/customerContact/types';
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 shippingAddressList = ref<ShippingAddressVO[]>([]);
const expenseTypeList = ref<ExpenseTypeVO[]>([]);
const buttonLoading = ref(false);
const customerContactList = ref<CustomerContactVO[]>([]);
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,
  expenseTypeId: 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,
    expenseTypeId: undefined,
    residueYearlyBudget: undefined,
    recharge: undefined,
    status: undefined,
    platformCode: undefined,
    params: {}
  },
  rules: {
    parentId: [{ required: true, message: '上级部门不能为空', trigger: 'change' }],
    deptName: [{ required: true, message: '部门名称不能为空', trigger: 'blur' }],
    deptManage: [{ required: true, message: '部门主管不能为空', trigger: 'blur' }],
    customerId: [{ required: true, message: '客户编号不能为空', trigger: 'blur' }]
  }
});

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 expenseTypeChange = async () => {
  form.value.yearlyBudget = 0.0;
  form.value.usedBudget = 0.0;
  form.value.residueYearlyBudget = 0.0;
};
/** 查询客户联系人信息列表 */
const getContactList = async () => {
  loading.value = true;
  // 使用props传递的customerId进行查询
  if (props.customerId) {
    queryParams.value.customerId = props.customerId;
  }
  const res = await listCustomerContact(queryParams.value as any);
  customerContactList.value = res.rows;
};

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

/** 获取费用类型列表 */
const getExpenseTypeList = async () => {
  if (!props.customerId) {
    expenseTypeList.value = [];
    return;
  }
  try {
    const res = await listExpenseType({ customerId: props.customerId, pageNum: 1, pageSize: 100 });
    expenseTypeList.value = res.rows || res.data || [];
  } catch (error) {
    console.error('获取费用类型列表失败:', error);
    expenseTypeList.value = [];
  }
};

/** 获取客户收货地址列表 */
const getShippingAddressList = async () => {
  if (!props.customerId) {
    shippingAddressList.value = [];
    return;
  }
  try {
    const query: ShippingAddressQuery = {
      pageNum: 1,
      pageSize: 100,
      customerId: props.customerId
    };
    const res = await listShippingAddress(query);
    shippingAddressList.value = res.rows || [];
  } catch (error) {
    console.error('获取收货地址列表失败:', error);
    shippingAddressList.value = [];
  }
};

// 取消按钮
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) => {
  if (row != null && row.deptId) {
    form.value.parentId = row.deptId;
  }
  // 设置客户ID
  form.value.customerId = props.customerId;
  form.value.bindStatus = '1';
  form.value.isLimit = '1';
  form.value.selectYear = new Date().getFullYear().toString();
  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) => {
  const res = await getCustomerDept(row.deptId);
  // 修正数据：如果 parentId 等于自己的 id，说明是顶级部门，将 parentId 设为 0

  if (res.data.parentId === 100) {
    res.data.parentId = undefined;
  }
  Object.assign(form.value, res.data);

  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();
        reset();
      } 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();
  getTreeselect();
  getContactList();
  getExpenseTypeList();
  getShippingAddressList();
});
</script>
