<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" label-width="80px">
            <el-row :gutter="20">
              <el-col :span="6">
                <el-form-item label="所属公司" prop="belongCompanyId" style="width: 100%; margin-right: 0">
                  <el-select v-model="queryParams.belongCompanyId" placeholder="请选择所属公司" clearable filterable style="width: 100%">
                    <el-option v-for="item in companyList" :key="item.id" :label="`${item.companyCode} - ${item.companyName}`" :value="item.id" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="客户编码" prop="customerNo" style="width: 100%; margin-right: 0">
                  <el-input v-model="queryParams.customerNo" placeholder="请输入客户编码" clearable style="width: 100%" @keyup.enter="handleQuery" />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="客户名称" prop="companyName" style="width: 100%; margin-right: 0">
                  <el-input
                    v-model="queryParams.customerName"
                    placeholder="请输入客户名称"
                    clearable
                    style="width: 100%"
                    @keyup.enter="handleQuery"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="客户等级" prop="customerLevelId" style="width: 100%; margin-right: 0">
                  <el-select v-model="queryParams.customerLevelId" placeholder="请选择客户等级" clearable style="width: 100%">
                    <el-option v-for="level in customerLevelList" :key="level.id" :label="level.levelName" :value="level.id" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="行业" prop="industryCategoryId" style="width: 100%; margin-right: 0">
                  <el-select v-model="queryParams.industryCategoryId" placeholder="请选择行业" clearable filterable style="width: 100%">
                    <el-option
                      v-for="industry in industryCategoryList"
                      :key="industry.id"
                      :label="industry.industryCategoryName"
                      :value="industry.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="业务员" prop="salesPersonId" style="width: 100%; margin-right: 0">
                  <el-select v-model="queryParams.salesPersonId" placeholder="请选择业务员" clearable filterable style="width: 100%">
                    <el-option
                      v-for="item in comStaffList"
                      :key="item.staffId"
                      :label="`${item.staffCode} , ${item.staffName}`"
                      :value="item.staffId"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="客服人员" prop="serviceStaffId" style="width: 100%; margin-right: 0">
                  <el-select v-model="queryParams.serviceStaffId" placeholder="请选择客服人员" clearable filterable style="width: 100%">
                    <el-option
                      v-for="item in comStaffList"
                      :key="item.staffId"
                      :label="`${item.staffCode} , ${item.staffName}`"
                      :value="item.staffId"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="归属部门" prop="belongingDepartmentId" style="width: 100%; margin-right: 0">
                  <el-select v-model="queryParams.belongingDepartmentId" placeholder="请选择归属部门" clearable filterable style="width: 100%">
                    <el-option v-for="item in comDeptList" :key="item.id" :label="item.deptName" :value="item.id" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="客户标签" prop="customerTag" style="width: 100%; margin-right: 0">
                  <el-select v-model="queryParams.customerTag" placeholder="请选择客户标签" clearable filterable style="width: 100%">
                    <el-option v-for="tag in customerTagList" :key="tag.id" :label="tag.tagName" :value="tag.id" />
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="6">
                <el-form-item style="width: 100%; margin-right: 0">
                  <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                  <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="17"><span>客户信息列表</span> </el-col>
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['customer:customerInfo:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" plain :disabled="single" @click="handleTransferSalesPerson" v-hasPermi="['customer:customerInfo:edit']"
              >转移业务员</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" plain :disabled="single" @click="handleTransferServiceStaff" v-hasPermi="['customer:customerInfo:edit']"
              >转移客服人员</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" plain :disabled="single" @click="updateCreditAmountBtn" v-hasPermi="['customer:customerInfo:edit']"
              >修改临时额度</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" plain :disabled="single" @click="setCustomerInfoTagBtn" v-hasPermi="['customer:customerInfo:edit']"
              >设置标签</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['customer:customerInfo:export']">导出</el-button>
          </el-col>
        </el-row>
      </template>

      <el-table v-loading="loading" border :data="customerInfoList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="客户名称" align="left" prop="customerName" min-width="200" />
        <el-table-column label="归属公司" align="left" prop="companyName" min-width="150" />
        <el-table-column label="客户编号" align="center" prop="customerNo" min-width="120" />
        <el-table-column label="行业" align="center" prop="industryCategory" min-width="120"> </el-table-column>
        <el-table-column label="业务员" align="center" min-width="100">
          <template #default="scope">
            <span>{{ scope.row.customerSalesInfoVo?.salesPerson }}</span>
          </template>
        </el-table-column>
        <el-table-column label="客服人员" align="center" min-width="100">
          <template #default="scope">
            <span>{{ scope.row.customerSalesInfoVo?.serviceStaff }}</span>
          </template>
        </el-table-column>
        <el-table-column label="归属部门" align="center" prop="belongingDepartmentId" min-width="120">
          <template #default="scope">
            <span>{{ scope.row.customerSalesInfoVo?.belongingDepartment }}</span>
          </template>
        </el-table-column>
        <el-table-column label="信用额" align="center" prop="creditAmount" min-width="80">
          <template #default="scope">
            <span>{{ scope.row.customerSalesInfoVo?.creditAmount }}</span>
          </template>
        </el-table-column>
        <el-table-column label="临时额度" align="center" prop="temporaryQuota" min-width="80">
          <template #default="scope">
            <span>{{ scope.row.customerSalesInfoVo?.temporaryQuota }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status" min-width="80">
          <template #default="scope">
            <dict-tag :options="sys_check_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="150" fixed="right">
          <template #default="scope">
            <el-button link type="primary" @click="handleUpdate(scope.row)" v-hasPermi="['customer:customerInfo:edit']">编辑</el-button>
            <el-button link type="primary" v-if="scope.row.status == '0'" @click="handleCheck(scope.row)" v-hasPermi="['customer:customerInfo:edit']"
              >审核</el-button
            >
            <!-- <el-button link type="danger" @click="handleDelete(scope.row)" v-hasPermi="['customer:customerInfo:remove']">删除</el-button> -->
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>

    <!-- 审核对话框 -->
    <el-dialog title="审核" v-model="checkDialog.visible" width="500px" append-to-body>
      <el-form ref="checkFormRef" :model="checkForm" :rules="checkRules" label-width="100px">
        <el-form-item label="审核结果" prop="status">
          <el-select v-model="checkForm.status" placeholder="请选择" class="w-full">
            <el-option v-for="dict in filteredCheckStatus" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitCheck">确认</el-button>
          <el-button @click="checkDialog.visible = false">取消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 修改临时额度对话框 -->
    <el-dialog title="修改临时额度" v-model="creditDialog.visible" width="500px" append-to-body>
      <el-form ref="creditFormRef" :model="creditForm" :rules="creditRules" label-width="100px">
        <el-form-item label="临时额度" prop="temporaryAmount">
          <el-input v-model="creditForm.temporaryAmount" placeholder="请输入临时额度" class="w-full" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitCreditAmount">确认</el-button>
          <el-button @click="creditDialog.visible = false">取消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 设置标签对话框 -->
    <el-dialog title="设置标签" v-model="tagDialog.visible" width="500px" append-to-body>
      <el-checkbox-group v-model="selectedTags">
        <el-checkbox v-for="tag in customerTagList" :key="tag.id" :value="tag.id">{{ tag.tagName }}</el-checkbox>
      </el-checkbox-group>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitTags">确认</el-button>
          <el-button @click="tagDialog.visible = false">取消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 转移业务员确认对话框 -->
    <el-dialog title="提示" v-model="transferConfirmDialog.visible" width="500px" append-to-body>
      <div style="display: flex; align-items: flex-start; gap: 10px">
        <el-icon color="#e6a23c" :size="20"><WarningFilled /></el-icon>
        <span>是否将选中的{{ ids.length }}个客户转移给其他负责人？转移成功之后，该操作将无法恢复。</span>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="transferConfirmDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="confirmTransfer" :loading="transferConfirmLoading">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 选择业务员对话框 -->
    <el-dialog title="转移业务员" v-model="transferDialog.visible" width="500px" append-to-body>
      <el-form ref="transferFormRef" :model="transferForm" :rules="transferRules" label-width="100px">
        <el-form-item label="业务员" prop="salesPersonId">
          <el-select
            v-model="transferForm.salesPersonId"
            placeholder="请选择业务员"
            clearable
            filterable
            style="width: 100%"
            @change="handleStaffChange"
          >
            <el-option v-for="item in comStaffList" :key="item.staffId" :label="`${item.staffCode} , ${item.staffName}`" :value="item.staffId" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="transferDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="submitTransfer" :loading="transferLoading">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 转移客服人员确认对话框 -->
    <el-dialog title="提示" v-model="transferServiceConfirmDialog.visible" width="500px" append-to-body>
      <div style="display: flex; align-items: flex-start; gap: 10px">
        <el-icon color="#e6a23c" :size="20"><WarningFilled /></el-icon>
        <span>是否将选中的{{ ids.length }}个客户转移给其他负责人？转移成功之后，该操作将无法恢复。</span>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="transferServiceConfirmDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="confirmServiceTransfer" :loading="transferServiceConfirmLoading">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 选择客服人员对话框 -->
    <el-dialog title="转移客服人员" v-model="transferServiceDialog.visible" width="500px" append-to-body>
      <el-form ref="transferServiceFormRef" :model="transferServiceForm" :rules="transferServiceRules" label-width="100px">
        <el-form-item label="客服人员" prop="serviceStaffId">
          <el-select v-model="transferServiceForm.serviceStaffId" placeholder="请选择客服人员" clearable filterable style="width: 100%">
            <el-option v-for="item in comStaffList" :key="item.staffId" :label="`${item.staffCode} , ${item.staffName}`" :value="item.staffId" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="transferServiceDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="submitServiceTransfer" :loading="transferServiceLoading">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="CustomerInfo" lang="ts">
import {
  listCustomerInfo,
  getCustomerInfo,
  delCustomerInfo,
  addCustomerInfo,
  updateCustomerInfo,
  changeStatus,
  updateCreditAmount,
  setCustomerInfoTag,
  transferSalesPerson,
  transferServiceStaff
} from '@/api/customer/customerFile/customerInfo';
import { CustomerInfoVO, CustomerInfoQuery, CustomerInfoForm } from '@/api/customer/customerFile/customerInfo/types';
import { listCustomerTag } from '@/api/customer/customerCategory/customerTag';
import { CustomerTagVO } from '@/api/customer/customerCategory/customerTag/types';
import { listIndustryCategory } from '@/api/customer/customerCategory/industryCategory';
import { IndustryCategoryVO } from '@/api/customer/customerCategory/industryCategory/types';
import { listCompany } from '@/api/company/company';
import { listCustomerLevel } from '@/api/customer/customerLevel';
import { CustomerLevelVO, CustomerLevelQuery } from '@/api/customer/customerLevel/types';
import { CompanyVO } from '@/api/company/company/types';
import { listComStaff, getComStaff } from '@/api/company/comStaff';
import { ComStaffVO, ComStaffQuery, ComStaffForm } from '@/api/company/comStaff/types';
import { listComDept, getComDept } from '@/api/company/comDept';
import { ComDeptVO } from '@/api/company/comDept/types';
import { WarningFilled } from '@element-plus/icons-vue';
const router = useRouter();
const customerInfoList = ref<CustomerInfoVO[]>([]);
const customerTagList = ref<CustomerTagVO[]>([]);
const customerLevelList = ref<CustomerLevelVO[]>([]);
const industryCategoryList = ref<IndustryCategoryVO[]>([]);
const companyList = ref<CompanyVO[]>([]);
const comStaffList = ref<ComStaffVO[]>([]);
const comDeptList = ref<ComDeptVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const transferConfirmLoading = ref(false);
const transferLoading = ref(false);
const transferServiceConfirmLoading = ref(false);
const transferServiceLoading = ref(false);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_check_status, customer_type, customer_level } = toRefs<any>(proxy?.useDict('sys_check_status', 'customer_type', 'customer_level'));

const queryFormRef = ref<ElFormInstance>();
const customerInfoFormRef = ref<ElFormInstance>();

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

// 审核对话框
const checkDialog = reactive<DialogOption>({
  visible: false,
  title: '审核'
});

// 审核表单
const checkForm = reactive({
  customerId: undefined,
  status: undefined
});

const checkFormRef = ref<ElFormInstance>();

// 审核表单验证规则
const checkRules = {
  status: [{ required: true, message: '请选择审核结果', trigger: 'change' }]
};

// 过滤后的审核状态（去掉待审核）
const filteredCheckStatus = computed(() => {
  return sys_check_status.value?.filter((item: any) => item.value !== '0') || [];
});

// 修改临时额度对话框
const creditDialog = reactive<DialogOption>({
  visible: false,
  title: '修改临时额度'
});

// 临时额度表单
const creditForm = reactive({
  customerIds: undefined,
  temporaryAmount: undefined
});

const creditFormRef = ref<ElFormInstance>();

// 临时额度表单验证规则
const creditRules = {
  temporaryAmount: [
    { required: true, message: '请输入临时额度', trigger: 'blur' },
    { pattern: /^\d+(\.\d{1,2})?$/, message: '请输入有效的金额', trigger: 'blur' }
  ]
};

// 设置标签对话框
const tagDialog = reactive<DialogOption>({
  visible: false,
  title: '设置标签'
});

// 选中的标签
const selectedTags = ref<Array<string | number>>([]);

// 转移业务员确认对话框
const transferConfirmDialog = reactive<DialogOption>({
  visible: false,
  title: '提示'
});

// 转移业务员对话框
const transferDialog = reactive<DialogOption>({
  visible: false,
  title: '转移业务员'
});

// 转移业务员表单
const transferForm = reactive({
  salesPersonId: undefined,
  deptId: undefined
});

const transferFormRef = ref<ElFormInstance>();

// 转移业务员表单验证规则
const transferRules = {
  salesPersonId: [{ required: true, message: '请选择业务员', trigger: 'change' }]
};

// 转移客服人员确认对话框
const transferServiceConfirmDialog = reactive<DialogOption>({
  visible: false,
  title: '提示'
});

// 转移客服人员对话框
const transferServiceDialog = reactive<DialogOption>({
  visible: false,
  title: '转移客服人员'
});

// 转移客服人员表单
const transferServiceForm = reactive({
  serviceStaffId: undefined
});

const transferServiceFormRef = ref<ElFormInstance>();

// 转移客服人员表单验证规则
const transferServiceRules = {
  serviceStaffId: [{ required: true, message: '请选择客服人员', trigger: 'change' }]
};

const initFormData: CustomerInfoForm = {
  id: undefined,
  customerNo: undefined,
  belongCompanyId: undefined,
  companyName: undefined,
  customerName: undefined,
  businessCustomerName: undefined,
  shortName: undefined,
  invoiceTypeId: undefined,
  enterpriseScaleId: undefined,
  customerTypeId: undefined,
  industryCategoryId: undefined,
  customerLevelId: undefined,
  landline: undefined,
  fax: undefined,
  url: undefined,
  postCode: undefined,
  validityFromDate: undefined,
  validityToDate: undefined,
  invoiceTop: undefined,
  address: undefined,
  regProvincialNo: undefined,
  regCityNo: undefined,
  regCountyNo: undefined,
  provincialCityCounty: undefined,
  status: undefined,
  remark: undefined
};
const data = reactive<PageData<CustomerInfoForm, CustomerInfoQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    belongCompanyId: undefined,
    customerNo: undefined,
    companyName: undefined,
    customerName: undefined,
    customerLevelId: undefined,
    industryCategoryId: undefined,
    salesPersonId: undefined,
    serviceStaffId: undefined,
    belongingDepartmentId: undefined,
    customerTag: undefined,
    platformCode: undefined,
    params: {}
  },
  rules: {
    customerNo: [{ required: true, message: '客户编号不能为空', trigger: 'blur' }],
    belongCompanyId: [{ required: true, message: '所属公司不能为空', trigger: 'change' }],
    companyName: [{ required: true, message: '客户名称不能为空', trigger: 'blur' }],
    businessCustomerName: [{ required: true, message: '工商名称不能为空', trigger: 'blur' }],
    shortName: [{ required: true, message: '企业简称不能为空', trigger: 'blur' }],
    invoiceTypeId: [{ required: true, message: '开票类型不能为空', trigger: 'change' }],
    enterpriseScaleId: [{ required: true, message: '企业规模不能为空', trigger: 'change' }],
    customerTypeId: [{ required: true, message: '客户类别不能为空', trigger: 'change' }],
    industryCategoryId: [{ required: true, message: '行业类别不能为空', trigger: 'change' }],
    customerLevelId: [{ required: true, message: '客户等级不能为空', trigger: 'change' }]
  }
});

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

/** 查询客户信息列表 */
const getList = async () => {
  loading.value = true;
  const res = await listCustomerInfo(queryParams.value);
  customerInfoList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

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

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

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

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

/** 多选框选中数据 */
const handleSelectionChange = (selection: CustomerInfoVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length < 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  router.push({
    path: '/customer/customer-add'
  });
};

/** 修改按钮操作 */
const handleUpdate = async (row?: CustomerInfoVO) => {
  const _id = row?.id || ids.value[0];
  router.push({
    path: '/customer/customer-overview',
    query: { id: _id, status: 'edit' }
  });
};

/** 审核按钮操作 */
const handleCheck = (row: CustomerInfoVO) => {
  checkForm.customerId = row.id;
  checkForm.status = undefined;
  checkFormRef.value?.resetFields();
  checkDialog.visible = true;
};

/** 提交审核 */
const submitCheck = () => {
  checkFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      try {
        await changeStatus(checkForm.customerId, checkForm.status);
        proxy?.$modal.msgSuccess('审核成功');
        checkDialog.visible = false;
        await getList();
      } catch (error) {
        proxy?.$modal.msgError('审核失败，请重试');
      }
    }
  });
};

/** 修改临时额度按钮操作 */
const updateCreditAmountBtn = () => {
  if (ids.value.length !== 1) {
    proxy?.$modal.msgWarning('请选择一条记录');
    return;
  }
  creditForm.customerIds = ids;
  creditForm.temporaryAmount = undefined;
  creditFormRef.value?.resetFields();
  creditDialog.visible = true;
};

/** 提交临时额度 */
const submitCreditAmount = () => {
  creditFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      try {
        await updateCreditAmount(creditForm.customerIds, creditForm.temporaryAmount);
        proxy?.$modal.msgSuccess('修改成功');
        creditDialog.visible = false;
        await getList();
      } catch (error) {
        console.error('修改临时额度失败:', error);
        proxy?.$modal.msgError('修改失败，请重试');
      }
    }
  });
};
/** 设置标签操作 */
const setCustomerInfoTagBtn = () => {
  if (ids.value.length === 0) {
    proxy?.$modal.msgWarning('请至少选择一条记录');
    return;
  }
  // 清空之前选中的标签
  selectedTags.value = [];
  tagDialog.visible = true;
};

/** 提交标签 */
const submitTags = async () => {
  if (selectedTags.value.length === 0) {
    proxy?.$modal.msgWarning('请至少选择一个标签');
    return;
  }
  try {
    await setCustomerInfoTag(ids.value as number[], selectedTags.value as number[]);
    proxy?.$modal.msgSuccess('设置成功');
    tagDialog.visible = false;
    await getList();
  } catch (error) {
    console.error('设置标签失败:', error);
    proxy?.$modal.msgError('设置失败，请重试');
  }
};

/** 转移业务员按钮操作 */
const handleTransferSalesPerson = () => {
  if (ids.value.length === 0) {
    proxy?.$modal.msgWarning('请至少选择一条记录');
    return;
  }
  transferConfirmDialog.visible = true;
};

/** 确认转移 */
const confirmTransfer = () => {
  transferConfirmLoading.value = true;
  setTimeout(() => {
    transferConfirmLoading.value = false;
    transferConfirmDialog.visible = false;
    transferForm.salesPersonId = undefined;
    transferForm.deptId = undefined;
    transferFormRef.value?.resetFields();
    transferDialog.visible = true;
  }, 300);
};

/** 业务员选择变化时获取部门ID */
const handleStaffChange = (staffId: number) => {
  const staff = comStaffList.value.find((item) => item.staffId === staffId);
  if (staff) {
    transferForm.deptId = staff.deptId;
  }
};

/** 提交转移业务员 */
const submitTransfer = () => {
  transferFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      try {
        transferLoading.value = true;
        await transferSalesPerson(ids.value as number[], transferForm.salesPersonId as number, transferForm.deptId);
        proxy?.$modal.msgSuccess('转移成功');
        transferDialog.visible = false;
        await getList();
      } catch (error) {
        console.error('转移业务员失败:', error);
        proxy?.$modal.msgError('转移失败，请重试');
      } finally {
        transferLoading.value = false;
      }
    }
  });
};

/** 转移客服人员按钮操作 */
const handleTransferServiceStaff = () => {
  if (ids.value.length === 0) {
    proxy?.$modal.msgWarning('请至少选择一条记录');
    return;
  }
  transferServiceConfirmDialog.visible = true;
};

/** 确认转移客服人员 */
const confirmServiceTransfer = () => {
  transferServiceConfirmLoading.value = true;
  setTimeout(() => {
    transferServiceConfirmLoading.value = false;
    transferServiceConfirmDialog.visible = false;
    transferServiceForm.serviceStaffId = undefined;
    transferServiceFormRef.value?.resetFields();
    transferServiceDialog.visible = true;
  }, 300);
};

/** 提交转移客服人员 */
const submitServiceTransfer = () => {
  transferServiceFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      try {
        transferServiceLoading.value = true;
        await transferServiceStaff(ids.value as number[], transferServiceForm.serviceStaffId as number);
        proxy?.$modal.msgSuccess('转移成功');
        transferServiceDialog.visible = false;
        await getList();
      } catch (error) {
        console.error('转移客服人员失败:', error);
        proxy?.$modal.msgError('转移失败，请重试');
      } finally {
        transferServiceLoading.value = false;
      }
    }
  });
};

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

/** 删除按钮操作 */
const handleDelete = async (row?: CustomerInfoVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除客户信息编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delCustomerInfo(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'customer/customerInfo/export',
    {
      ...queryParams.value
    },
    `customerInfo_${new Date().getTime()}.xlsx`
  );
};

/** 加载客户标签列表 */
const loadCustomerTags = async () => {
  try {
    const res = await listCustomerTag({ status: '0' } as any); // 只获取启用状态的标签
    customerTagList.value = res.rows;
  } catch (error) {
    console.error('加载客户标签失败:', error);
  }
};

/** 加载行业分类列表 */
const loadIndustryCategories = async () => {
  try {
    const res = await listIndustryCategory({ status: '0', dataSource: 'A10' } as any); // 只获取启用状态的行业
    industryCategoryList.value = res.rows;
  } catch (error) {
    console.error('加载行业分类失败:', error);
  }
};

// 加载客户等级列表
const loadCustomerLevelList = async () => {
  try {
    const res = await listCustomerLevel({ dataSource: 'A10' } as any);
    customerLevelList.value = res.rows || [];
  } catch (error) {
    console.error('加载客户等级列表失败:', error);
  }
};

/** 加载公司列表 */
const loadCompanyList = async () => {
  try {
    const query: any = { isShow: '0', dataSource: 'A10' };
    const res = await listCompany(query);
    companyList.value = res.rows || [];
  } catch (error) {
    console.error('加载公司列表失败:', error);
  }
};

/** 加载员工列表 */
const loadComStaffList = async () => {
  try {
    const query: ComStaffQuery = { status: '0' } as any;
    const res = await listComStaff(query);
    console.log(res);

    comStaffList.value = res.rows || [];
  } catch (error) {
    console.error('加载员工列表失败:', error);
  }
};

/** 加载部门列表 */
const loadComDeptList = async () => {
  try {
    const res = await listComDept();
    comDeptList.value = res.rows || res.data || [];
  } catch (error) {
    console.error('加载部门列表失败:', error);
  }
};

onMounted(() => {
  getList();
  loadCustomerTags();
  loadIndustryCategories();
  loadCompanyList();
  loadComStaffList();
  loadComDeptList();
  loadCustomerLevelList();
});
onActivated(() => {
  getList();
});
</script>
