<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="cusCustomerQueryBo" :inline="true" :rules="rule">
            <el-form-item label="主客户号" prop="customerNo" label-width="100px">
              <el-input v-model="cusCustomerQueryBo.customerNo" placeholder="请输入主客户号" clearable />
            </el-form-item>
            <el-form-item label="子客户号" prop="subCustomerNo" label-width="100px">
              <el-input v-model="cusCustomerQueryBo.subCustomerNo" placeholder="请输入子客户号" clearable />
            </el-form-item>
            <el-form-item label="姓名" prop="name" label-width="100px">
              <el-input v-model="cusCustomerQueryBo.name" placeholder="请输入姓名" clearable />
            </el-form-item>
            <el-form-item label="证件类型" prop="identificationType" label-width="100px">
              <el-select v-model="cusCustomerQueryBo.identificationType" placeholder="请选择证件类型" style="width: 240px" clearable>
                <el-option
                  v-for="dict in sys_id_type.filter((item) => item.value !== 'd' && item.value !== 'f')"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="证件号码" prop="identificationNumber" label-width="100px">
              <el-input v-model="cusCustomerQueryBo.identificationNumber" placeholder="请输入证件号码" clearable />
            </el-form-item>
            <el-form-item label="客户来源" prop="system" label-width="100px">
              <el-select v-model="cusCustomerQueryBo.system" placeholder="请选择客户来源" style="width: 240px" clearable>
                <el-option
                  v-for="dict in sys_from_system.filter((item) => item.value !== 'CMS' && item.value !== 'Shared')"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="子客户来源" prop="subSystem" label-width="100px">
              <el-select v-model="cusCustomerQueryBo.subSystem" placeholder="请选择子客户来源" style="width: 240px" clearable multiple>
                <el-option
                  v-for="dict in sys_from_system.filter((item) => item.value !== 'CMS' && item.value !== 'Shared')"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="vip客户" prop="vipCustomer" label-width="102px">
              <el-select v-model="cusCustomerQueryBo.vipCustomer" placeholder="请选择vip客户" style="width: 240px" clearable>
                <el-option v-for="dict in vip_customer" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="股东标识" prop="shareholderSign" label-width="100px">
              <el-select v-model="cusCustomerQueryBo.shareholderSign" placeholder="请选择股东标识" style="width: 240px" clearable>
                <el-option v-for="dict in shareholder_sign" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="建立时间" prop="dateValue" label-width="100px">
              <el-date-picker
                v-model="dateValue"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="width: 240px"
              >
              </el-date-picker>
            </el-form-item>
<!--            <el-form-item label="是否黑名单" prop="isBlacklisted" label-width="100px">-->
<!--              <el-select v-model="cusCustomerQueryBo.isBlacklisted" placeholder="是否黑名单" style="width: 240px" clearable>-->
<!--                <el-option v-for="dict in sys_yes_no" :key="dict.value" :label="dict.label" :value="dict.value" />-->
<!--              </el-select>-->
<!--            </el-form-item>-->
            <el-form-item label="渠道" prop="channel" label-width="100px">
              <el-select v-model="cusCustomerQueryBo.channel" placeholder="请选择渠道" style="width: 240px" clearable>
                <el-option v-for="dict in sales_channel" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="机构" prop="org" label-width="100px">
              <el-select v-model="cusCustomerQueryBo.org" placeholder="请选择机构" style="width: 240px" clearable>
                <el-option v-for="dict in sys_managecom" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-row>
              <el-form-item>
                <el-button v-hasPermi="['customer:customerInfo:list']" type="primary" icon="Search" style="margin-left: 40px" @click="queryPageList"
                  >查询
                </el-button>
                <el-button icon="Refresh" style="margin-left: 50px" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-row>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <el-table v-loading="loading" :data="cusCustomerQueryVo" @selection-change="handleSelectionChange">
        <!--        <el-table-column type="selection" width="50" align="center" />-->
        <el-table-column type="index" label="序号" width="50" align="center" />
        <el-table-column label="主客户号" width="150" align="center" prop="customerNo" />
        <el-table-column label="姓名" align="center" prop="name" show-overflow-tooltip />
        <el-table-column label="性别" align="center" prop="gender">
          <template #default="scope">
            <dict-tag :options="sys_user_sex" :value="scope.row.gender" />
          </template>
        </el-table-column>
        <el-table-column label="出生日期" align="center" prop="birthday" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.birthday, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="证件类型" align="center" prop="identificationType" show-overflow-tooltip>
          <template #default="scope">
            <dict-tag :options="sys_id_type" :value="scope.row.identificationType" />
          </template>
        </el-table-column>
        <el-table-column label="证件号码" width="200" align="center" prop="identificationNumber" />
        <!--        <el-table-column label="证件有效期" align="center" prop="verificationExpiryDate" width="180">-->
        <!--          <template #default="scope">-->
        <!--            <span>{{ formatVerificationExpiryDate(scope.row.validFrom, scope.row.validTo) }}</span>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <el-table-column label="渠道" align="center" prop="channel">
          <template #default="scope">
            <dict-tag :options="sales_channel" :value="scope.row.channel" />
          </template>
        </el-table-column>
        <el-table-column label="客户验证标识" align="center" prop="verificationStatus" width="120">
          <template #default="scope">
            <dict-tag :options="verification_status" :value="scope.row.verificationStatus" />
          </template>
        </el-table-column>
        <el-table-column label="股东客户标识" align="center" prop="shareholderSign" width="120">
          <template #default="scope">
            <dict-tag :options="shareholder_sign" :value="scope.row.shareholderSign" />
          </template>
        </el-table-column>
        <el-table-column label="VIP标记" align="center" prop="vipCustomer">
          <template #default="scope">
            <dict-tag :options="vip_customer" :value="scope.row.vipCustomer" />
          </template>
        </el-table-column>
        <el-table-column v-if="false" label="客户状态" align="center" prop="customerStatus">
          <template #default="scope">
            <dict-tag :options="customer_status" :value="scope.row.customerStatus" />
          </template>
        </el-table-column>
        <el-table-column label="客户来源" align="center" prop="system">
          <template #default="scope">
            <dict-tag :options="sys_from_system" :value="scope.row.system" />
          </template>
        </el-table-column>
<!--        <el-table-column label="是否是黑名单" align="center" prop="isBlack" width="120">-->
<!--          <template #default="scope">-->
<!--            <dict-tag :options="sys_yes_no" :value="scope.row.isBlack" />-->
<!--          </template>-->
<!--        </el-table-column>-->
        <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="查看详情" placement="top">
              <el-button v-hasPermi="['customer:customerInfo:list']" link type="primary" icon="View" @click="handleViewCustomer(scope.row)"
                >查看详情</el-button
              >
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        v-model:page="cusCustomerQueryBo.pageNum"
        v-model:limit="cusCustomerQueryBo.pageSize"
        :total="total"
        @pagination="queryPageList"
      />
      <el-button v-hasPermi="['customer:customerInfo:list']" type="warning" plain icon="Download" @click="handleExport">下载</el-button>
    </el-card>

    <!-- 客户基本信息对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="90%" append-to-body @close="handleDialogClose">
      <el-form ref="cusCustomerQueryVoFormRef" v-loading="cusCustomerInfoVoLoading" :model="cusCustomerInfoVo" label-width="80px">
        <el-row>
          <el-form-item label="主客户号" prop="customerNo" label-width="100px">
            <el-input v-model="cusCustomerInfoVo.customerNo" placeholder="" disabled />
          </el-form-item>
          <el-form-item label="姓名" prop="name" label-width="100px">
            <el-input v-model="cusCustomerInfoVo.name" placeholder="" disabled />
          </el-form-item>
          <el-form-item label="性别" prop="gender" label-width="100px">
            <el-select v-model="cusCustomerInfoVo.gender" placeholder="" style="width: 195px" disabled>
              <el-option v-for="dict in sys_user_sex" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="英文名" prop="englishName" label-width="100px">
            <el-input v-model="cusCustomerInfoVo.englishName" placeholder="" disabled />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="出生日期" prop="birthday" label-width="100px">
            <el-date-picker
              v-model="cusCustomerInfoVo.birthday"
              clearable
              type="date"
              value-format="YYYY-MM-DD"
              placeholder=""
              style="width: 190px"
              disabled
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="年龄" prop="age" label-width="100px">
            <el-input v-model="age" placeholder="" disabled />
          </el-form-item>
          <el-form-item label="国籍" prop="country" label-width="100px">
            <el-select v-model="cusCustomerInfoVo.country" placeholder="" style="width: 195px" disabled>
              <el-option v-for="dict in nation" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="婚姻状态" prop="marriage" label-width="100px">
            <el-select v-model="cusCustomerInfoVo.marriage" placeholder="" style="width: 195px" disabled>
              <el-option v-for="dict in sys_yes_no" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="客户验真标识" prop="verificationStatus" label-width="100px">
            <el-select v-model="cusCustomerInfoVo.verificationStatus" placeholder="" style="width: 195px" disabled>
              <el-option v-for="dict in verification_status" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
<!--          <el-form-item label="是否黑名单" prop="blackMark" label-width="100px">-->
<!--            <el-select v-model="cusCustomerInfoVo.blackMark" placeholder="" style="width: 195px" disabled>-->
<!--              <el-option v-for="dict in sys_yes_no" :key="dict.value" :label="dict.label" :value="dict.value" />-->
<!--            </el-select>-->
<!--          </el-form-item>-->
        </el-row>
      </el-form>
      <!--证件信息-->
      <el-collapse v-model="activeNames" @change="handleCustomerIdentification">
        <el-collapse-item title="证件信息" name="CustomerIdentification">
          <el-table v-loading="identificationLoading" :data="cusCustomerIdentificationVo">
            <el-table-column label="证件类型" align="center" prop="identificationType">
              <template #default="scope">
                <dict-tag :options="sys_id_type" :value="scope.row.identificationType" />
              </template>
            </el-table-column>
            <el-table-column label="证件号码" align="center" prop="identificationNumber" show-overflow-tooltip />
            <el-table-column label="证件有效起期" align="center" prop="validFrom" show-overflow-tooltip>
              <template #default="scope">
                <span>{{ parseTime(scope.row.validFrom, '{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>
            <el-table-column label="证件有效止期" align="center" prop="validTo" show-overflow-tooltip>
              <template #default="scope">
                <span>{{ parseTime(scope.row.validTo, '{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>
          </el-table>
        </el-collapse-item>
      </el-collapse>
      <!--客户子客户信息-->
      <el-collapse v-model="activeNames" @change="handleCustomerSubId">
        <el-collapse-item title="子客户信息" name="CustomerSubId">
          <el-table v-loading="customerSubIdLoading" :data="cusCustomerSubId">
            <el-table-column label="序号" align="center" width="50">
              <template #default="scope">
                {{ scope.$index + 1 }}
              </template>
            </el-table-column>
            <el-table-column label="归属系统" align="center" prop="system">
              <template #default="scope">
                <dict-tag :options="sys_from_system" :value="scope.row.system" />
              </template>
            </el-table-column>
            <el-table-column label="子客户号" align="center" prop="subCustomerNo" show-overflow-tooltip />
            <el-table-column label="姓名" align="center" prop="name" show-overflow-tooltip />
            <el-table-column label="性别" align="center" prop="gender" show-overflow-tooltip>
              <template #default="scope">
                <dict-tag :options="sys_user_sex" :value="scope.row.gender" />
              </template>
            </el-table-column>
            <el-table-column label="出生日期" align="center" prop="birthday" show-overflow-tooltip>
              <template #default="scope">
                <span>{{ parseTime(scope.row.birthday, '{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>
            <el-table-column label="证件类型" align="center" prop="identificationType" show-overflow-tooltip>
              <template #default="scope">
                <dict-tag :options="sys_id_type" :value="scope.row.identificationType" />
              </template>
            </el-table-column>
            <el-table-column label="证件号码" align="center" prop="identificationNumber" width="180" show-overflow-tooltip />
            <el-table-column label="创建时间" align="center" prop="createTime">
              <template #default="scope">
                <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
              </template>
            </el-table-column>
          </el-table>
        </el-collapse-item>
      </el-collapse>
      <!--客户标签信息-->
      <el-collapse v-model="activeNames" @change="handleCustomerTagInfo">
        <el-collapse-item title="客户标签信息" name="CustomerTagInfo">
          <el-form ref="cusCustomerTagInfoFormRef" v-loading="customerTagInfoLoading" :model="cusCustomerTagInfoVo" label-width="80px">
            <el-row>
              <el-form-item label="VIP客户" prop="vipCustomer" label-width="120px">
                <el-select v-model="cusCustomerTagInfoVo.vipCustomer" placeholder="VIP客户等级" style="width: 200px" disabled>
                  <el-option v-for="dict in vip_customer" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="客户来源" prop="customerSource" label-width="120px">
                <el-select v-model="cusCustomerTagInfoVo.customerSource" placeholder="客户来源" style="width: 200px" disabled>
                  <el-option v-for="dict in sys_from_system" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="股东客户标识" prop="englishName" label-width="120px">
                <el-select v-model="cusCustomerTagInfoVo.shareholderSign" placeholder="股东客户标识" style="width: 200px" :disabled="true">
                  <el-option v-for="dict in shareholder_sign" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                </el-select>
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item label="理赔类型" prop="claimType" label-width="120px">
                <el-select v-model="cusCustomerTagInfoVo.claimType" placeholder="理赔类型" style="width: 200px" disabled>
                  <el-option v-for="dict in claim_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="是否身故" prop="isDeath" label-width="120px">
                <el-select v-model="cusCustomerTagInfoVo.isDeath" placeholder="是否身故" style="width: 200px" disabled>
                  <el-option v-for="dict in sys_yes_no" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="身故日期" prop="deathTime" label-width="120px">
                <el-date-picker
                  v-model="cusCustomerTagInfoVo.deathTime"
                  type="date"
                  placeholder="选择身故日期"
                  value-format="YYYY-MM-DD"
                  style="width: 200px"
                  disabled
                />
              </el-form-item>
            </el-row>
            <el-row>
              <el-form-item label="渠道" prop="channel" label-width="120px">
                <el-select v-model="cusCustomerTagInfoVo.channel" placeholder="渠道" style="width: 200px" disabled>
                  <el-option v-for="dict in sales_channel" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="机构" prop="institution" label-width="120px">
                <el-select v-model="cusCustomerTagInfoVo.institution" placeholder="机构" style="width: 200px" disabled>
                  <el-option v-for="dict in sys_managecom" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select>
              </el-form-item>
              <el-form-item label="年收入" prop="annualIncome" label-width="120px">
                <el-input v-model="cusCustomerTagInfoVo.annualIncome" placeholder="年收入" style="width: 200px" disabled />
              </el-form-item>
            </el-row>
          </el-form>
        </el-collapse-item>
      </el-collapse>
      <!--联系方式-->
      <el-collapse v-model="activeNames" @change="handleCustomerContact">
        <el-collapse-item title="联系方式" name="CustomerContact">
          <el-table v-loading="customerContactLoading" :data="cusCustomerContactVo">
            <el-table-column label="序号" align="center" width="50">
              <template #default="scope">
                {{ scope.$index + 1 }}
              </template>
            </el-table-column>
            <el-table-column label="系统来源" align="center" prop="system">
              <template #default="scope">
                <dict-tag :options="sys_from_system" :value="scope.row.system" />
              </template>
            </el-table-column>
            <el-table-column label="固定电话" align="center" prop="phoneNumber" show-overflow-tooltip />
            <el-table-column label="手机号码" align="center" prop="mobileNumber" show-overflow-tooltip />
            <el-table-column label="Email" align="center" prop="email" show-overflow-tooltip />
          </el-table>
        </el-collapse-item>
      </el-collapse>
      <!--联系地址-->
      <el-collapse v-model="activeNames" @change="handleCustomerAddress">
        <el-collapse-item title="联系地址" name="CustomerAddress">
          <el-table v-loading="customerAddressLoading" :data="cusCustomerAddressVo">
            <el-table-column label="序号" align="center" width="50">
              <template #default="scope">
                {{ scope.$index + 1 }}
              </template>
            </el-table-column>
            <el-table-column label="系统来源" align="center" prop="system">
              <template #default="scope">
                <dict-tag :options="sys_from_system" :value="scope.row.system" />
              </template>
            </el-table-column>
            <el-table-column label="通讯地址" align="center" prop="fullAddress" show-overflow-tooltip />
            <el-table-column label="通讯地址邮编" align="center" prop="postalCode" show-overflow-tooltip />
          </el-table>
        </el-collapse-item>
      </el-collapse>
      <!--工作单位-->
      <el-collapse v-model="activeNames" @change="handleCustomerEmployment">
        <el-collapse-item title="工作单位" name="CustomerEmployment">
          <el-table v-loading="customerEmploymentLoading" :data="cusCustomerEmploymentVo">
            <el-table-column label="序号" align="center" width="50">
              <template #default="scope">
                {{ scope.$index + 1 }}
              </template>
            </el-table-column>
            <el-table-column label="系统来源" align="center" prop="system">
              <template #default="scope">
                <dict-tag :options="sys_from_system" :value="scope.row.system" />
              </template>
            </el-table-column>
            <el-table-column label="工作单位" align="center" prop="employerName" show-overflow-tooltip />
            <el-table-column label="职业编码" align="center" prop="occupationCode" show-overflow-tooltip />
            <el-table-column label="职业名称" align="center" prop="occupationCode" show-overflow-tooltip>
              <template #default="scope">
                <dict-tag :options="occupation" :value="scope.row.occupationCode" />
              </template>
            </el-table-column>
          </el-table>
        </el-collapse-item>
      </el-collapse>
      <!--银行信息-->
      <el-collapse v-model="activeNames" @change="handleCustomerBankVo">
        <el-collapse-item title="银行信息" name="CustomerBank">
          <el-table v-loading="customerBankLoading" :data="cusCustomerBankVo">
            <el-table-column label="序号" align="center" width="50">
              <template #default="scope">
                {{ scope.$index + 1 }}
              </template>
            </el-table-column>
            <el-table-column label="系统来源" align="center" prop="system">
              <template #default="scope">
                <dict-tag :options="sys_from_system" :value="scope.row.system" />
              </template>
            </el-table-column>
            <el-table-column label="开户银行" align="center" prop="bankCode" show-overflow-tooltip>
              <template #default="scope">
                <dict-tag :options="sys_bank_code" :value="scope.row.bankCode" />
              </template>
            </el-table-column>
            <el-table-column label="户名" align="center" prop="accountName" show-overflow-tooltip />
            <el-table-column label="银行账号" align="center" prop="bankAccountNumber" show-overflow-tooltip />
            <el-table-column label="开户行所在省" align="center" prop="bankProvince" show-overflow-tooltip />
            <el-table-column label="开户行所在市" align="center" prop="bankCity" show-overflow-tooltip />
          </el-table>
        </el-collapse-item>
      </el-collapse>
      <!--保单信息-->
      <el-collapse v-model="activeNames" @change="handleCustomerContVo">
        <el-collapse-item title="保单信息" name="CustomerCont">
          <!--团险险标签-->
          <el-tabs v-model="currentTab" @tab-click="handleCont">
            <el-tab-pane label="团险保单" name="group">
              <el-table v-loading="loading" :data="cusCustomerContVo">
                <el-table-column label="序号" align="center" width="50">
                  <template #default="scope">
                    {{ scope.$index + 1 }}
                  </template>
                </el-table-column>
                <el-table-column label="子客户号" align="center" prop="subCustomerNo" show-overflow-tooltip />
                <el-table-column label="团体保单号" align="center" prop="grpcontno" show-overflow-tooltip />
                <el-table-column label="投保单位" align="center" prop="appntName" show-overflow-tooltip />
                <el-table-column label="产品名称" align="center" prop="riskname" show-overflow-tooltip />
                <el-table-column label="保单状态" align="center" prop="contStatus" show-overflow-tooltip>
                  <template #default="scope">
                    <dict-tag :options="cont_status" :value="scope.row.contStatus" />
                  </template>
                </el-table-column>
                <el-table-column label="保险起期" align="center" prop="startdate" show-overflow-tooltip>
                  <template #default="scope">
                    <span>{{ parseTime(scope.row.startdate, '{y}-{m}-{d}') }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="保险止期" align="center" prop="enddate" show-overflow-tooltip>
                  <template #default="scope">
                    <span>{{ parseTime(scope.row.enddate, '{y}-{m}-{d}') }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="保费(元)" align="center" prop="prem" show-overflow-tooltip />
              </el-table>
            </el-tab-pane>
            <!--个险标签-->
            <el-tab-pane label="个险保单" name="personal">
              <el-table v-loading="loading" :data="cusCustomerContVo">
                <el-table-column label="序号" align="center" width="50">
                  <template #default="scope">
                    {{ scope.$index + 1 }}
                  </template>
                </el-table-column>
                <el-table-column label="子客户号" align="center" prop="subCustomerNo" show-overflow-tooltip />
                <el-table-column label="个人保单号" align="center" prop="contno" show-overflow-tooltip />
                <el-table-column label="投保人" align="center" prop="appntName" show-overflow-tooltip />
                <el-table-column label="产品名称" align="center" prop="riskname" show-overflow-tooltip />
                <el-table-column label="保单状态" align="center" prop="contStatus" show-overflow-tooltip>
                  <template #default="scope">
                    <dict-tag :options="cont_status" :value="scope.row.contStatus" />
                  </template>
                </el-table-column>
                <el-table-column label="保险起期" align="center" prop="startdate" show-overflow-tooltip>
                  <template #default="scope">
                    <span>{{ parseTime(scope.row.startdate, '{y}-{m}-{d}') }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="保险止期" align="center" prop="enddate" show-overflow-tooltip>
                  <template #default="scope">
                    <span>{{ parseTime(scope.row.enddate, '{y}-{m}-{d}') }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="保费(元)" align="center" prop="prem" show-overflow-tooltip />
              </el-table>
            </el-tab-pane>
            <!--健康险标签-->
            <el-tab-pane label="健康险保单" name="health">
              <el-table v-loading="loading" :data="cusCustomerContVo">
                <el-table-column label="序号" align="center" width="50">
                  <template #default="scope">
                    {{ scope.$index + 1 }}
                  </template>
                </el-table-column>
                <el-table-column label="子客户号" align="center" prop="subCustomerNo" show-overflow-tooltip />
                <el-table-column label="健康险保单号" align="center" prop="contno" show-overflow-tooltip />
                <el-table-column label="投保单位" align="center" prop="appntName" show-overflow-tooltip />
                <el-table-column label="产品名称" align="center" prop="riskname" show-overflow-tooltip />
                <el-table-column label="保单状态" align="center" prop="contStatus" show-overflow-tooltip>
                  <template #default="scope">
                    <dict-tag :options="cont_status" :value="scope.row.contStatus" />
                  </template>
                </el-table-column>
                <el-table-column label="保险起期" align="center" prop="startdate" show-overflow-tooltip>
                  <template #default="scope">
                    <span>{{ parseTime(scope.row.startdate, '{y}-{m}-{d}') }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="保险止期" align="center" prop="enddate" show-overflow-tooltip>
                  <template #default="scope">
                    <span>{{ parseTime(scope.row.enddate, '{y}-{m}-{d}') }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="保费(元)" align="center" prop="prem" show-overflow-tooltip />
              </el-table>
            </el-tab-pane>
          </el-tabs>
        </el-collapse-item>
      </el-collapse>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" icon="Check" @click="viewAll">{{ buttonText }}</el-button>
          <el-button
            v-hasPermi="['customer:customerInfo:mergesplit']"
            :loading="buttonLoading"
            type="primary"
            icon="ZoomOut"
            @click="mergeAndSplitRecords"
          >
            合并/拆分记录查询
          </el-button>
          <el-button v-hasPermi="['customer:customerInfo:changetrack']" :loading="buttonLoading" type="primary" icon="Sort" @click="informationChange"
            >重要资料变更查询
          </el-button>
        </div>
      </template>
    </el-dialog>
    <!--相似客户合并/拆分轨迹-->
    <el-dialog v-model="mergeAndSplitRecordsDialog.visible" :title="mergeAndSplitRecordsDialog.title" width="80%" append-to-body>
      <el-table v-loading="loading" :data="customerMergeSplitInfo">
        <el-table-column label="操作时间" align="center" prop="operatingTime" show-overflow-tooltip>
          <template #default="scope">
            <span>{{ parseTime(scope.row.operatingTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="类型" align="center" prop="operatingType">
          <template #default="scope">
            <dict-tag :options="merger_split" :value="scope.row.operatingType" />
          </template>
        </el-table-column>
        <el-table-column label="发起系统" align="center" prop="formSystem">
          <template #default="scope">
            <dict-tag :options="sys_from_system" :value="scope.row.formSystem" />
          </template>
        </el-table-column>
        <el-table-column label="操作人" align="center" prop="operator" show-overflow-tooltip />
        <el-table-column label="被合并客户号" align="center" prop="beforeMerger" show-overflow-tooltip />
        <el-table-column label="合并后客户号" align="center" prop="afterMerger" show-overflow-tooltip />
        <el-table-column label="拆分客户号" align="center" prop="beforeSplit" show-overflow-tooltip />
        <el-table-column label="拆分后客户号" align="center" prop="afterSplit" show-overflow-tooltip />
      </el-table>
    </el-dialog>
    <!--客户信息变更轨迹-->
    <el-dialog v-model="customerInfoChangeDialog.visible" :title="customerInfoChangeDialog.title" width="80%" append-to-body>
      <el-table v-loading="loading" :data="callbackList">
        <el-table-column label="发起时间" align="center" prop="operationDate" width="160">
          <template #default="scope">
            <span>{{ parseTime(scope.row.operationDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="发起系统" align="center" prop="fromSystem" width="160">
          <template #default="scope">
            <dict-tag :options="sys_from_system" :value="scope.row.fromSystem" />
          </template>
        </el-table-column>
        <el-table-column label="变更内容" align="center" prop="changeMsg" width="160" show-overflow-tooltip />
        <el-table-column label="变更前姓名" align="center" prop="oldName" width="160" />
        <el-table-column label="变更前性别" align="center" prop="oldGender" width="160">
          <template #default="scope">
            <dict-tag :options="sys_user_sex" :value="scope.row.oldGender" />
          </template>
        </el-table-column>
        <el-table-column label="变更前出生日期" align="center" prop="oldBirthday" width="160">
          <template #default="scope">
            <span>{{ parseTime(scope.row.oldBirthday, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="变更前证件类型" align="center" prop="oldIdType" width="160">
          <template #default="scope">
            <dict-tag :options="sys_id_type" :value="scope.row.oldIdType" />
          </template>
        </el-table-column>
        <el-table-column label="变更前证件号码" align="center" prop="oldIdNo" width="180" />

        <el-table-column label="变更后姓名" align="center" prop="newName" width="160" />
        <el-table-column label="变更后性别" align="center" prop="newGender" width="160">
          <template #default="scope">
            <dict-tag :options="sys_user_sex" :value="scope.row.newGender" />
          </template>
        </el-table-column>
        <el-table-column label="变更后出生日期" align="center" prop="newBirthday" width="160">
          <template #default="scope">
            <span>{{ parseTime(scope.row.newBirthday, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="变更后证件类型" align="center" prop="newIdType" width="160">
          <template #default="scope">
            <dict-tag :options="sys_id_type" :value="scope.row.newIdType" />
          </template>
        </el-table-column>
        <el-table-column label="变更后证件号码" align="center" prop="newIdNo" width="160" />
      </el-table>
    </el-dialog>
    <!-- 导出进度弹窗 -->
    <el-dialog v-model="exportProgressVisible" title="导出进度" width="400px" :close-on-click-modal="false" :close-on-press-escape="false" :show-close="false">
      <div style="text-align: center; padding: 20px 0">
        <el-progress type="circle" :percentage="exportProgress.percentage" :width="120" :status="exportProgress.percentage === 100 ? 'success' : undefined" />
        <p style="margin-top: 20px; font-size: 14px; color: #606266">已导出 {{ exportProgress.processedCount }} / {{ exportProgress.totalCount }} 条</p>
        <p style="margin-top: 10px; font-size: 12px; color: #909399">点击"后台运行"后任务将继续，完成后自动下载</p>
      </div>
      <template #footer>
        <el-button @click="handleBackgroundFail">取消下载</el-button>
        <el-button @click="handleBackgroundRun">后台运行</el-button>
      </template>
    </el-dialog>

    <!-- 后台运行气泡 -->
    <transition name="el-fade-in">
      <div v-if="showBackgroundTip" class="background-export-tip" @click="reopenProgressDialog">
        <el-icon :size="20" color="#409EFF" style="margin-bottom: 5px"><Loading /></el-icon>
        <div style="font-size: 12px">导出中 {{ exportProgress.percentage }}%</div>
        <div style="font-size: 11px; color: #909399; margin-top: 2px">点击查看</div>
      </div>
    </transition>
  </div>
</template>

<script setup name="CustomerInfo" lang="ts">
import {
  listCustomerInfo,
  queryCusCustomerMergeSplitInfo,
  queryCustomerAddress,
  queryCustomerBank,
  queryCustomerCont,
  queryCustomerContact,
  queryCustomerEmployment,
  queryCustomerIdentification,
  queryCustomerInfo,
  queryCustomerInfoChangeTrack,
  queryCustomerInfoPageList,
  queryCustomerSubIds,
  queryCustomerTagInfo,
  exportCustomerInfoAsync,
  getExportProgress,
  cancelExportTask,
  getLatestRunningTask 
} from '@/api/customer/cus';
import {
  CusCustomerAddressVo,
  CusCustomerBankVo,
  CusCustomerContactVo,
  CusCustomerContVo,
  CusCustomerEmploymentVo,
  CusCustomerIdentificationVo,
  CusCustomerInfoChangeTrackVo,
  CusCustomerInfoVo,
  CusCustomerQueryBo,
  CusCustomerQueryVo,
  CusCustomerSubId,
  CusCustomerTagInfoVo,
  CustomerInfoForm,
  CustomerInfoQuery,
  CustomerInfoVO,
  CustomerMergeSplitInfo
} from '@/api/customer/cus/types';
import { FormRules } from 'element-plus';
import { onMounted, onActivated, getCurrentInstance, toRefs, ref, reactive } from 'vue';
import { ElMessage } from 'element-plus';
import { Loading } from '@element-plus/icons-vue';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const customerInfoList = ref<CustomerInfoVO[]>([]);
const buttonLoading = ref(false);
const loading = 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 callbackList = ref<any[]>([]);

const customerInfoFormRef = ref<ElFormInstance>();
const id_type = ref([]);
const dateRangeApply = ref<[DateModelType, DateModelType]>(['', '']);
const exportProgressVisible = ref(false);
const showBackgroundTip = ref(false);
const exportProgress = reactive({
  taskId: '',//任务ID
  percentage: 0,//进度
  processedCount: 0,//已处理
  totalCount: 0//总数
});
let exportTimer: any; //轮询定时
const isExportCancelled = ref(false); //是否已取消导出
const isDownloaded = ref(false); //是否已经下载
const hasShownFailedMessage = ref(false); //是否已显示失败提示

const initFormData: CustomerInfoForm = {
  customerNo: undefined,
  name: undefined,
  gender: undefined,
  birthday: undefined,
  customerStatus: undefined,
  verificationStatus: undefined,
  verificationExpiryDate: undefined,
  verificationIdentificationTypeId: undefined
};
const data = reactive<PageData<CustomerInfoForm, CustomerInfoQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: undefined,
    gender: undefined,
    birthday: undefined,
    customerStatus: undefined,
    verificationStatus: undefined,
    verificationExpiryDate: undefined,
    verificationIdentificationTypeId: undefined,
    params: {}
  },
  rules: {
    customerNo: [{ required: true, message: '客户号不能为空', trigger: 'blur' }],
    name: [{ required: true, message: '客户姓名不能为空', trigger: 'blur' }],
    gender: [{ required: true, message: '性别不能为空', trigger: 'blur' }],
    birthday: [{ required: true, message: '出生日期不能为空', trigger: 'blur' }],
    customerStatus: [{ required: true, message: '客户状态不能为空', trigger: 'change' }],
    verificationStatus: [{ required: true, message: '验真状态不能为空', trigger: 'change' }],
    verificationExpiryDate: [{ required: true, message: '验真有效期不能为空', trigger: 'blur' }],
    verificationIdentificationTypeId: [{ required: true, message: '验真证件类型id不能为空', trigger: 'blur' }]
  }
});
const { queryParams, form, rules } = toRefs(data);
//客户基本信息查询条件
const queryFormRef = ref<ElFormInstance>();
const cusCustomerQueryBo: CusCustomerQueryBo = ref({
  pageNum: 1,
  pageSize: 10,
  customerNo: undefined,
  subCustomerNo: undefined,
  name: undefined,
  identificationType: undefined,
  identificationNumber: undefined,
  beginDate: undefined,
  endDate: undefined,
  system: undefined,
  shareholderSign: undefined,
  vipCustomer: undefined,
  isBlacklisted: undefined,
  channel: undefined,
  org: undefined,
  subSystem: []
});
//表单规则
const rule: FormRules<typeof cusCustomerQueryBo> = reactive({
  // customerNo: [{ required: true, validator: checkAtLeastOneFilled, trigger: 'blur' }],
  // subCustomerNo: [{ required: true, validator: checkAtLeastOneFilled, trigger: 'blur' }],
  // name: [{ required: true, validator: checkAtLeastOneFilled, trigger: 'blur' }],
  // identificationType: [{ required: true, validator: checkAtLeastOneFilled, trigger: 'blur' }],
  // identificationNumber: [{ required: true, validator: checkAtLeastOneFilled, trigger: 'blur' }]
  // dateValue: [{ required: true, validator: checkAtLeastOneFilled, trigger: 'blur' }],
  // system: [{ required: true, validator: checkAtLeastOneFilled, trigger: 'blur' }],
  // shareholderSign: [{ required: true, validator: checkAtLeastOneFilled, trigger: 'blur' }],
  // vipCustomer: [{ required: true, validator: checkAtLeastOneFilled, trigger: 'blur' }],
  // isBlacklisted: [{ required: true, validator: checkAtLeastOneFilled, trigger: 'blur' }]
});

function checkAtLeastOneFilled() {
  if (
    (cusCustomerQueryBo.value.customerNo !== undefined && cusCustomerQueryBo.value.customerNo !== '') ||
    (cusCustomerQueryBo.value.subCustomerNo !== undefined && cusCustomerQueryBo.value.subCustomerNo !== '') ||
    (cusCustomerQueryBo.value.name !== undefined && cusCustomerQueryBo.value.name !== '') ||
    (cusCustomerQueryBo.value.identificationType !== undefined && cusCustomerQueryBo.value.identificationType !== '') ||
    (cusCustomerQueryBo.value.identificationNumber !== undefined && cusCustomerQueryBo.value.identificationNumber !== '') ||
    (cusCustomerQueryBo.value.beginDate !== undefined && cusCustomerQueryBo.value.beginDate !== '') ||
    (cusCustomerQueryBo.value.endDate !== undefined && cusCustomerQueryBo.value.endDate !== '') ||
    (cusCustomerQueryBo.value.system !== undefined && cusCustomerQueryBo.value.system !== '') ||
    (cusCustomerQueryBo.value.shareholderSign !== undefined && cusCustomerQueryBo.value.shareholderSign !== '') ||
    (cusCustomerQueryBo.value.vipCustomer !== undefined && cusCustomerQueryBo.value.vipCustomer !== '') ||
    (cusCustomerQueryBo.value.isBlacklisted !== undefined && cusCustomerQueryBo.value.isBlacklisted !== '') ||
    (cusCustomerQueryBo.value.channel !== undefined && cusCustomerQueryBo.value.channel !== '') ||
    (cusCustomerQueryBo.value.org !== undefined && cusCustomerQueryBo.value.org !== '') ||
    (Array.isArray(cusCustomerQueryBo.value.subSystem) && cusCustomerQueryBo.value.subSystem.length > 0)
  ) {
    return true;
  } else {
    return false;
  }
}

//查询条件，建立时间的数据
const dateValue = ref<DatePickerValueType | null>(null);
//监听dateValue的值变化
watch(dateValue, (newValue) => {
  if (newValue) {
    cusCustomerQueryBo.value.beginDate = newValue[0];
    cusCustomerQueryBo.value.endDate = newValue[1];
  } else {
    cusCustomerQueryBo.value.beginDate = null;
    cusCustomerQueryBo.value.endDate = null;
  }
});
//客户信息列表
const cusCustomerQueryVo = ref<CusCustomerQueryVo>();
const cusCustomerQueryVoFormRef = ref<ElFormInstance>();
//证件有效期显示处理
const formatVerificationExpiryDate = (from, to) => {
  if (from && to) {
    const formatDate = (dateStr) => new Date(dateStr).toISOString().slice(0, 10);
    return `${formatDate(from)} - ${formatDate(to)}`;
  } else {
    return '';
  }
};
//字典转换
const {
  sys_id_type,
  sys_user_sex,
  verification_status,
  shareholder_sign,
  vip_customer,
  sys_from_system,
  customer_status,
  cont_status,
  merger_split,
  nation,
  sys_yes_no,
  occupation,
  sys_bank_code,
  sys_province,
  sys_city,
  sys_district,
  sales_channel,
  sales_intitution,
  sys_managecom,
  claim_type
} = toRefs<any>(
  proxy?.useDict(
    'sys_id_type',
    'sys_user_sex',
    'verification_status',
    'shareholder_sign',
    'vip_customer',
    'sys_from_system',
    'customer_status',
    'cont_status',
    'merger_split',
    'nation',
    'sys_yes_no',
    'occupation',
    'sys_bank_code',
    'sys_province',
    'sys_city',
    'sys_district',
    'sales_channel',
    'sales_intitution',
    'sys_managecom',
    'claim_type'
  )
);
// 根据条件查询客户信息方法（去除表单验证）
const queryPageList = async () => {
  if (!checkAtLeastOneFilled()) {
    proxy?.$modal.alert('请至少录入一项查询条件');
    return; // 直接返回，不执行查询
  }

  // 直接执行查询（不再进行表单验证）
  loading.value = true;
  try {
    const res = await queryCustomerInfoPageList(cusCustomerQueryBo.value);
    cusCustomerQueryVo.value = res.rows;
    total.value = res.total;
  } catch (error) {
    ElMessage.error('查询失败，请稍后重试');
  } finally {
    loading.value = false;
  }
};
//客户信息弹窗控制
const dialog = reactive<DialogOption>({
  visible: false,
  title: '客户基本信息'
});
//客户基本信息form初始化
const cusCustomerInfoVo: CusCustomerInfoVo = ref({
  customerNo: undefined,
  name: undefined,
  gender: undefined,
  birthday: undefined,
  customerStatus: undefined,
  verificationStatus: undefined,
  verificationExpiryDate: undefined,
  verificationIdentificationTypeId: undefined,
  namePinyin: undefined,
  englishName: undefined,
  country: undefined,
  blackMark: undefined,
  marriage: undefined
});
//年龄
const age = ref();
//年龄计算
const calculateAge = (birthdate) => {
  const today = new Date();
  const birthDate = new Date(birthdate);
  let age = today.getFullYear() - birthDate.getFullYear();
  const m = today.getMonth() - birthDate.getMonth();
  if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
    age--;
  }
  return age;
};

const handleViewCustomer = (row) => {
  proxy.$router.push({
    path: `/customer/cus-info1/customerInfo`,
    query: {
      customerNo: row.customerNo,
      customerSign: 'cusCustomer' // 添加 customerSign 参数
    }
  });
};

const cusCustomerInfoVoLoading = ref(false);
//双击查询个人客户详细信息
const handleRowDblClick = (row) => {
  dialog.visible = true;
  cusCustomerInfoVoLoading.value = true;
  queryCustomerInfo(row.customerNo).then((res) => {
    cusCustomerInfoVo.value = res;
    age.value = calculateAge(cusCustomerInfoVo.value.birthday);
    cusCustomerInfoVoLoading.value = false;
  });
};
// 用于控制各个折叠面板展开状态的对象
const activeNames = ref([]);
const handleDialogClose = () => {
  //直接清空 activeNames
  activeNames.value = [];
};
//证件信息
const cusCustomerIdentificationVo = ref<CusCustomerIdentificationVo>();
const identificationLoading = ref(false);
const handleCustomerIdentification = () => {
  identificationLoading.value = true;
  queryCustomerIdentification(cusCustomerInfoVo.value.customerNo)
    .then((res) => {
      cusCustomerIdentificationVo.value = res;
      identificationLoading.value = false;
    })
    .catch((err) => {});
};
//子客户号信息
const cusCustomerSubId = ref<CusCustomerSubId>();
const customerSubIdLoading = ref(false);
const handleCustomerSubId = () => {
  customerSubIdLoading.value = true;
  queryCustomerSubIds(cusCustomerInfoVo.value.customerNo)
    .then((res) => {
      cusCustomerSubId.value = res;
      customerSubIdLoading.value = false;
    })
    .catch((err) => {});
};
//客户标签
const cusCustomerTagInfoVo: CusCustomerTagInfoVo = ref({
  vipCustomer: undefined,
  customerSource: undefined,
  shareholderSign: undefined,
  claimType: undefined,
  isDeath: undefined,
  deathTime: undefined,
  channel: undefined,
  institution: undefined,
  annualIncome: undefined
});
const customerTagInfoLoading = ref(false);
const handleCustomerTagInfo = () => {
  customerTagInfoLoading.value = true;
  queryCustomerTagInfo(cusCustomerInfoVo.value.customerNo).then((res) => {
    cusCustomerTagInfoVo.value = res;
    customerTagInfoLoading.value = false;
  });
};
//联系方式
const cusCustomerContactVo = ref<CusCustomerContactVo>();
const customerContactLoading = ref(false);
const handleCustomerContact = () => {
  customerContactLoading.value = true;
  queryCustomerContact(cusCustomerInfoVo.value.customerNo).then((res) => {
    cusCustomerContactVo.value = res;
    customerContactLoading.value = false;
  });
};
//联系地址
const cusCustomerAddressVo = ref<CusCustomerAddressVo>();
const customerAddressLoading = ref(false);
const handleCustomerAddress = () => {
  customerAddressLoading.value = true;
  queryCustomerAddress(cusCustomerInfoVo.value.customerNo).then((res) => {
    cusCustomerAddressVo.value = res;
    cusCustomerAddressVo.value.forEach((customerAddress) => {
      let province = sys_province.value.find((dict) => dict.value === customerAddress.province);
      let city = sys_city.value.find((dict) => dict.value === customerAddress.city);
      let district = sys_district.value.find((dict) => dict.value === customerAddress.district);
      customerAddress.fullAddress =
        (province ? province.label : '') + (city ? city.label : '') + (district ? district.label : '') + customerAddress.detailedAddress;
    });
    customerAddressLoading.value = false;
  });
};
//工作单位
const cusCustomerEmploymentVo = ref<CusCustomerEmploymentVo>();
const customerEmploymentLoading = ref(false);
const handleCustomerEmployment = () => {
  customerEmploymentLoading.value = true;
  queryCustomerEmployment(cusCustomerInfoVo.value.customerNo).then((res) => {
    cusCustomerEmploymentVo.value = res;
    customerEmploymentLoading.value = false;
  });
};
//银行信息
const cusCustomerBankVo = ref<CusCustomerBankVo>();
const customerBankLoading = ref(false);
const handleCustomerBankVo = () => {
  customerBankLoading.value = true;
  queryCustomerBank(cusCustomerInfoVo.value.customerNo).then((res) => {
    cusCustomerBankVo.value = res;
    customerBankLoading.value = false;
  });
};

//保单信息
const cusCustomerContVo = ref<CusCustomerContVo>();
const handleCont = (tab) => {
  if (tab.props.name === 'group') {
    handleGroupCont();
  } else if (tab.props.name === 'personal') {
    handlePersonalCont();
  } else if (tab.props.name === 'health') {
    handleHealthCont();
  }
};
//团险保单
const handleGroupCont = () => {
  loading.value = true;
  queryCustomerCont(cusCustomerInfoVo.value.customerNo, 'GRP').then((res) => {
    cusCustomerContVo.value = res;
    loading.value = false;
  });
};
//个险保单
const handlePersonalCont = () => {
  loading.value = true;
  queryCustomerCont(cusCustomerInfoVo.value.customerNo, 'IND').then((res) => {
    cusCustomerContVo.value = res;
    loading.value = false;
  });
};
//健康险保单
const handleHealthCont = () => {
  loading.value = true;
  queryCustomerCont(cusCustomerInfoVo.value.customerNo, 'CORP').then((res) => {
    cusCustomerContVo.value = res;
    loading.value = false;
  });
};
// 当前选中的标签页，初始化为“团体保单”标签页
const currentTab = ref('group');
//打开标签,默认显示团险信息
const handleCustomerContVo = () => {
  currentTab.value = 'group';
  handleGroupCont();
};
// 按钮显示的文本，初始为"查看全部"
const buttonText = ref('查看全部');
const viewAll = () => {
  if (buttonText.value === '查看全部') {
    activeNames.value = [
      'CustomerIdentification',
      'CustomerSubId',
      'CustomerTagInfo',
      'CustomerAddress',
      'CustomerEmployment',
      'CustomerBank',
      'CustomerCont',
      'CustomerContact'
    ];
    handleCustomerIdentification();
    handleCustomerSubId();
    handleCustomerTagInfo();
    handleCustomerContact();
    handleCustomerAddress();
    handleCustomerEmployment();
    handleCustomerBankVo();
    handleGroupCont();
    buttonText.value = '折叠全部';
  } else {
    activeNames.value = [];
    buttonText.value = '查看全部';
  }
};
//合并/拆分记录查询弹窗控制
const mergeAndSplitRecordsDialog = reactive<DialogOption>({
  visible: false,
  title: '相似客户合并/拆分轨迹'
});
//合并/拆分轨迹对象
const customerMergeSplitInfo = ref<CustomerMergeSplitInfo>();
//合并/拆分轨迹查询
const mergeAndSplitRecords = () => {
  mergeAndSplitRecordsDialog.visible = true;
  queryCusCustomerMergeSplitInfo(cusCustomerInfoVo.value.customerNo)
    .then((res) => {
      customerMergeSplitInfo.value = res;
    })
    .catch((err) => {
      //  console.log('系统异常，请联系管理员');
    });
};
//客户信息变更轨迹查询弹窗控制
const customerInfoChangeDialog = reactive<DialogOption>({
  visible: false,
  title: '客户信息变更轨迹'
});
//客户信息变更轨迹对象
const cusCustomerInfoChangeTrackVo = ref<CusCustomerInfoChangeTrackVo>();
//客户信息变更轨迹查询
const informationChange = () => {
  customerInfoChangeDialog.visible = true;
  queryCustomerInfoChangeTrack(cusCustomerInfoVo.value.customerNo)
    .then((res) => {
      callbackList.value = res.data.recordList;
    })
    .catch((err) => {
      //  console.log('系统异常，请联系管理员');;
    });
};

/** 重置按钮操作 */
const resetQuery = () => {
  // 重置表单字段
  queryFormRef.value?.resetFields();

  // 手动重置 dateValue
  dateValue.value = null;

  // 重置查询参数为初始状态，保留 pageNum 和 pageSize
  cusCustomerQueryBo.value = {
    pageNum: 1,
    pageSize: 10,
    customerNo: undefined,
    subCustomerNo: undefined,
    name: undefined,
    identificationType: undefined,
    identificationNumber: undefined,
    beginDate: undefined,
    endDate: undefined,
    system: undefined,
    shareholderSign: undefined,
    vipCustomer: undefined,
    isBlacklisted: undefined
  };

  // 清空表格数据
  cusCustomerQueryVo.value = [];
  total.value = 0;
};

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

//下载按钮
const handleExport = async () => {
  try {
    loading.value = true;
    const exportParams = proxy?.addDateRange({ ...cusCustomerQueryBo.value }, dateValue.value, 'beginDate');
    const res = await exportCustomerInfoAsync(exportParams);
    const taskId = res.msg || res.data;
    if (!taskId) {
      proxy?.$modal.msgError('获取任务ID失败');
      return;
    }
    exportProgress.taskId = taskId;
    proxy?.$modal.msgSuccess('导出任务已提交，正在后台生成文件...');
    showExportProgress();
  } catch (error) {
    proxy?.$modal.msgError('导出任务提交失败');
  } finally {
    loading.value = false;
  }
};

/** 取消下载按钮操作 */
const handleBackgroundFail = async() => {
  if (!exportProgress.taskId) return;
  isExportCancelled.value = true;
  isDownloaded.value = false;
  hasShownFailedMessage.value = true;
  clearInterval(exportTimer);
  exportTimer = null;
  exportProgressVisible.value = false;
  showBackgroundTip.value = false;
  try {
    await cancelExportTask(exportProgress.taskId);
  } catch (error) {}
  proxy?.$modal.msgWarning('导出任务已取消');
  exportProgress.taskId = '';
};

/** 显示导出进度弹窗 */
const showExportProgress = () => {
  exportProgress.percentage = 0;
  exportProgress.processedCount = 0;
  exportProgress.totalCount = 0;
  exportProgressVisible.value = true;
  showBackgroundTip.value = false;
  isExportCancelled.value = false;
  isDownloaded.value = false;
  hasShownFailedMessage.value = false;
  const cleanupExport = () => {
    clearInterval(exportTimer);
    exportTimer = null;
    exportProgressVisible.value = false;
    showBackgroundTip.value = false;
  };

  const checkProgress = async () => {
    try {
      if (!exportProgress.taskId) return;
      const res = await getExportProgress(exportProgress.taskId);
      const task = res.data;
      if (!task) {
        cleanupExport();
        return;
      }
      exportProgress.percentage = task.progress || 0;
      exportProgress.processedCount = task.processedCount || 0;
      exportProgress.totalCount = task.totalCount || 0;
      
      if (task.status === 'completed') {
        if (!isExportCancelled.value && !isDownloaded.value) {
          isDownloaded.value = true;
          cleanupExport();
          proxy?.download(
            'customer/cus/exportCustomerInfo/download/' + exportProgress.taskId,
            {},
            task.fileName || '客户信息.xlsx'
          );
          proxy?.$modal.msgSuccess('导出完成！文件下载中...');
        }else{
          cleanupExport();
        }
      } else if (task.status === 'failed') {
        cleanupExport();
        if(!hasShownFailedMessage.value){
          hasShownFailedMessage.value = true;
          if (isExportCancelled.value || (task.errorMessage && task.errorMessage.indexOf('取消') !== -1)) {
            proxy?.$modal.msgWarning('导出任务已取消');
          } else {
            proxy?.$modal.msgError('导出失败：' + (task.errorMessage || '未知错误'));
          }
        }
      }
    } catch (error: any) {
      if (error?.message?.includes('任务不存在') || error?.message?.includes('已过期')){
        cleanupExport();
        return;
      }
      cleanupExport();
      proxy?.$modal.msgError('查询导出进度失败');
    }
  };
  checkProgress();
  if (exportTimer) {
    clearInterval(exportTimer);
    exportTimer = null;
  }
  exportTimer = setInterval(checkProgress, 500);
};

const handleBackgroundRun = () => {
  exportProgressVisible.value = false;
  showBackgroundTip.value = true;
  ElMessage.info('任务将在后台继续，完成后自动下载');
};

const reopenProgressDialog = () => {
  exportProgressVisible.value = true;
  showBackgroundTip.value = false;
};

/** 恢复未完成的导出任务 */
const restoreExportTask = async () => {
  try {
    const res = await getLatestRunningTask();
    const task = res.data;
    if (task && task.taskId) {
      const fileName = task.fileName || '';
      if (fileName && fileName.indexOf('客户信息') === -1 && fileName.indexOf('customerInfo') === -1) {
        return;
      }
      exportProgress.taskId = task.taskId;
      exportProgress.percentage = task.progress || 0;
      exportProgress.processedCount = task.processedCount || 0;
      exportProgress.totalCount = task.totalCount || 0;

      if (task.status != 'completed') {
        showBackgroundTip.value = true;
        showExportProgress();
      }
    }
  } catch (error) {}
};

const initIdSysteFrom = computed(() => {
  return sys_from_system.value.filter((item) => item.value != 'CRP');
});

onMounted(() => {
  //initIdSysteFrom();
  restoreExportTask();
});
</script>
<style scoped>
.background-export-tip {
  position: fixed;
  right: 30px;
  bottom: 30px;
  width: 100px;
  height: 100px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  z-index: 1000;
  transition: all 0.3s;
  border: 1px solid #e4e7ed;
}

.background-export-tip:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.15);
  border-color: #409EFF;
}
</style>
