<template>
  <div class="container">
    <CommonPage
      :operationBtnList="operationBtnList"
      :visibleDefaultButtons="visibleDefaultButtons"
      :showSearchForm="true"
      :show-pagination="true"
      :total="pageTotal"
      :current-page="currentPage"
      :page-size="pageSize"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    >
      <!-- 搜索区域 -->
      <template #searchForm>
        <SearchForm ref="searchFormRef" :config="searchConfig" />
      </template>
      <!-- 列表区域 -->
      <template #table>
        <el-table
          :data="tableData"
          @selection-change="handleSelectionChange"
          height="400"
          border
          highlight-current-row
          style="width: 100%"
          v-loading="loading"
        >
          <el-table-column type="selection" width="40" />
          <el-table-column prop="policyNo" label="保单号" width="150" fixed="left" />
          <el-table-column prop="insuranceCompany" label="保险公司" width="150" />

          <el-table-column prop="policyFollowStatus" label="新单状态" width="150">
            <template #default="{ row }">
              {{ getDictLabel('csf_policy_follow_status_new', row.policyFollowStatus) }}
            </template>
          </el-table-column>
          <el-table-column prop="reconciliationStatus" label="对账状态" width="150">
            <template #default="{ row }">
              {{ getDictLabel('reconciliation_status', row.reconciliationStatus) }}
            </template>
          </el-table-column>
          <el-table-column prop="policyStatus" label="保单状态" width="150">
            <template #default="{ row }">
              {{ getDictLabel('csf_policy_status_new', row.policyStatus) }}
            </template>
          </el-table-column>

          <el-table-column prop="remainingUnpaidAmount" label="待付款金额" width="150">
            <template #default="{ row }">
              {{ row.remainingUnpaidAmount ? formatCurrency(row.remainingUnpaidAmount) : '' }}
            </template>
          </el-table-column>
          <el-table-column prop="remainingUnpaidCurrency" label="待付款币种" width="150">
            <template #default="{ row }">
              {{ getDictLabel('bx_currency_type', row.remainingUnpaidCurrency) }}
            </template>
          </el-table-column>
          <el-table-column prop="paymentAmount" label="付款金额" width="150">
            <template #default="{ row }">
              {{ row.paymentAmount ? formatCurrency(row.paymentAmount) : '' }}
            </template>
          </el-table-column>
          <el-table-column prop="paymentCurrency" label="付款币种" width="150">
            <template #default="{ row }">
              {{ getDictLabel('bx_currency_type', row.paymentCurrency) }}
            </template>
          </el-table-column>
          <el-table-column prop="paymentMethod" label="缴费方式" width="150">
            <template #default="{ row }">
              {{ getDictLabel('csf_ap_first_issue', row.paymentMethod) }}
            </template>
          </el-table-column>
          <el-table-column prop="recognizedAmount" label="保司认定金额" width="150">
            <template #default="{ row }">
              {{ row.recognizedAmount ? formatCurrency(row.recognizedAmount) : '' }}
            </template>
          </el-table-column>
          <el-table-column prop="recognizedCurrency" label="保司对账币种" width="150">
            <template #default="{ row }">
              {{ getDictLabel('bx_currency_type', row.recognizedCurrency) }}
            </template>
          </el-table-column>
          <el-table-column prop="payingBank" label="付款银行" width="150" />
          <el-table-column prop="payer" label="付款人" width="150" />
          <el-table-column prop="policyHolder" label="投保人" width="150" />
          <el-table-column prop="insured" label="受保人" width="150" />
          <el-table-column prop="brokerName" label="转介人" width="150" />
          <el-table-column prop="createTime" label="创建时间" width="150">
            <template #default="{ row }">
              {{ row.createTime ? formatToDate(row.createTime) : '' }}
            </template>
          </el-table-column>
          <el-table-column prop="updateTime" label="更新时间" width="150">
            <template #default="{ row }">
              {{ row.updateTime ? formatToDate(row.updateTime) : '' }}
            </template>
          </el-table-column>
          <el-table-column prop="reconciliationCompany" label="对账公司" width="150">
          </el-table-column>

          <el-table-column fixed="right" label="操作" min-width="120">
            <template #default="{ row }">
              <el-popover placement="right" :width="200" trigger="click">
                <template #reference>
                  <el-icon>
                    <MoreFilled />
                  </el-icon>
                </template>
                <el-menu @select="handleSelect($event, row)" popper-class="custom-menu">
                  <el-menu-item
                    :index="item.value"
                    v-for="item in dropdownItems"
                    :key="item.value"
                    >{{ item.label }}</el-menu-item
                  >
                </el-menu>
              </el-popover>
            </template>
          </el-table-column>
        </el-table>
      </template>
    </CommonPage>
    <!-- 新增保单对账-->
    <CommonDialog
      :dialogTitle="receiptsDialogTitle"
      dialogWidth="80%"
      :openDialog="receiptsFlag"
      :showAction="true"
      :showClose="true"
      @close="receiptsFlag = false"
      @confirm="addReceipts"
    >
      <SearchForm
        ref="addCheckRecordFormRef"
        :config="addCheckRecordConfig"
        v-model="addCheckRecordFormModel"
      />
      <div>
        <el-button type="primary" icon="plus" @click="addRemittance" style="margin-bottom: 10px"
          >新增汇款记录</el-button
        >

        <div
          v-if="
            addCheckRecordFormModel.apiPremiumRemittanceDtoList &&
            addCheckRecordFormModel.apiPremiumRemittanceDtoList.length > 0
          "
          class="otherFileBox"
        >
          <el-table border :data="addCheckRecordFormModel.apiPremiumRemittanceDtoList" size="small">
            <el-table-column label="缴费方式" prop="paymentMethod">
              <template #default="{ row }">
                {{ getDictLabel('csf_ap_first_issue', row.paymentMethod) }}
              </template>
            </el-table-column>
            <el-table-column label="付款金额" prop="paymentAmount" />
            <el-table-column label="付款币种" prop="paymentCurrency">
              <template #default="{ row }">
                {{ getDictLabel('bx_currency_type', row.paymentCurrency) }}
              </template>
            </el-table-column>
            <el-table-column label="付款人与保单关系" prop="paymentRel">
              <template #default="{ row }">
                {{ getDictLabel('rel_pay_policy', row.paymentRel) }}
              </template>
            </el-table-column>
            <el-table-column label="付款人" prop="payer" />
            <el-table-column label="付款银行" prop="payingBank" />
            <el-table-column label="付款账号" prop="paymentAccount" />
            <el-table-column label="操作" width="100">
              <template #default="{ row, $index }">
                <el-button type="primary" link @click="editRemittance(row, $index)">
                  修改
                </el-button>
                <el-button type="danger" link @click="removeRemittance(row, $index)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </CommonDialog>
    <!-- 设置认定结果 -->
    <CommonDialog
      dialogTitle="设置认定结果"
      dialogWidth="80%"
      :openDialog="showAffirm"
      :showAction="true"
      :showClose="true"
      @close="showAffirm = false"
    >
      <SearchForm ref="affirmFormRef" :config="affirmConfig" v-model="affirmFormModel" />
    </CommonDialog>
    <!-- 汇款弹窗 -->
    <CommonDialog
      :dialogTitle="remittanceDialogTitle"
      dialogWidth="80%"
      :openDialog="showRemittance"
      :showAction="true"
      :showClose="true"
      @close="showRemittance = false"
      @confirm="confirmRemittance"
    >
      <el-scrollbar max-height="500px">
        <div
          :style="{
            marginBottom: remittanceFormModel.apiPremiumRemittanceFileDtoList?.length
              ? '0px'
              : '100px'
          }"
        >
          <SearchForm
            ref="remittanceFormRef"
            :config="remittanceConfig"
            v-model="remittanceFormModel"
          />
          <div
            v-if="remittanceFormModel.apiPremiumRemittanceFileDtoList?.length"
            class="otherFileBox"
          >
            <el-table border :data="tempOtherFileList" size="small">
              <el-table-column prop="fileName" label="文件名" />
              <el-table-column prop="fileType" label="文件类型" />
              <el-table-column prop="creatorName" label="上传人" />
              <el-table-column prop="createTime" label="上传时间">
                <template #default="{ row }">
                  {{ row.createTime ? formatToDate(row.createTime) : '' }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="100">
                <template #default="{ row, $index }">
                  <el-button type="danger" link @click="removeOtherFile(row, $index)">
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </el-scrollbar>
    </CommonDialog>
  </div>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import CommonPage from '@/components/commonPage'
import CommonDialog from '@/components/commonDialog'
import SearchForm from '@/components/SearchForm/SearchForm.vue'
import { ElMessage } from 'element-plus'
import { formatCurrency } from '@/utils/number'
// 接口
import { updatePayoutAmount } from '@/api/financial/commission'
import {
  premiumReconciliationList,
  EditPolicyReceipt,
  editPremiumRemittance,
  addPremiumReconciliation,
  getPremiumReconciliationInfo,
  deletePremiumRemittanceFile,
  getPremiumRemittanceFileList,
  editSiglePremiumRemittance,
  getPremiumRemittanceListApi
} from '@/api/sign/policy'
import useUserStore from '@/store/modules/user'
import { loadDicts, getDictLabel } from '@/utils/useDict'
import { getToken } from '@/utils/auth'
const { proxy } = getCurrentInstance()
const userStore = useUserStore()
// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const pageTotal = ref(0)
const loading = ref(false)
const selectedRow = ref(null)
const searchFormRef = ref(null)
const searchParams = ref({})
const receiptsFlag = ref(false) //回执弹窗
const receiptsDialogTitle = ref('新增保单回执')
const remittanceDialogTitle = ref('新增汇款')
const showRemittance = ref(false)
const remittanceFormRef = ref(null)

const searchConfig = ref([
  {
    type: 'select',
    prop: 'insurer',
    label: '保险公司',
    api: '/insurance/base/api/insuranceCompany/page',
    keywordField: 'queryContent',
    requestParams: { pageNo: 1, pageSize: 20 },
    placeholder: '输入保险公司名称搜索',
    debounceWait: 500, // 自定义防抖时间
    multiple: false,
    valueKey: 'insuranceCompanyBizId',
    labelKey: 'abbreviation',
    transform: res => {
      console.log(res)
      return res?.data.records || []
    }
  },
  {
    type: 'select',
    prop: 'insurer',
    label: '付款银行',
    api: '/insurance/base/api/insuranceCompany/page',
    keywordField: 'queryContent',
    requestParams: { pageNo: 1, pageSize: 20 },
    placeholder: '输入保险公司名称搜索',
    debounceWait: 500, // 自定义防抖时间
    multiple: false,
    valueKey: 'insuranceCompanyBizId',
    labelKey: 'abbreviation',
    transform: res => {
      console.log(res)
      return res?.data.records || []
    }
  },
  {
    type: 'input',
    prop: 'appointmentNo',
    label: '付款人'
  },
  {
    type: 'input',
    prop: 'policyNo',
    label: '保单号'
  },
  {
    type: 'input',
    prop: 'policyNo',
    label: '预约编号'
  },
  {
    type: 'input',
    prop: 'policyNo',
    label: '投保人'
  },
  {
    type: 'select',
    prop: 'receiptStatus',
    label: '缴费方式',
    multiple: false,
    dictType: 'receipt_status'
  },
  {
    type: 'select',
    prop: 'receiptStatus',
    label: '新单状态',
    multiple: false,
    dictType: 'receipt_status'
  },
  {
    type: 'select',
    prop: 'receiptStatus',
    label: '保单状态',
    multiple: false,
    dictType: 'receipt_status'
  },
  {
    type: 'select',
    prop: 'receiptStatus',
    label: '对账类型',
    multiple: false,
    dictType: 'receipt_status'
  },

  {
    type: 'date',
    prop: 'receiptDate',
    label: '付款日期',
    placeholder: '请选择',
    maxDate: 'today'
  }
])
// 表格操作菜单
const dropdownItems = [
  { label: '设置认定结果', value: 'settingResult' },
  { label: '编辑', value: 'editRecord' }
  // { label: '查看记录', value: 'viewRecord' }
]
// 应收单类型
const fortuneBizTypeOptions = [
  { value: 'R', label: '关联保单应付单' },
  { value: 'U', label: '非关联保单应付单' }
]
// ==============设置认定结果开始============
const showAffirm = ref(false)
const affirmFormRef = ref(null)
const affirmFormModel = ref({})
const affirmConfig = [
  {
    type: 'input',
    prop: 'paymentAmount',
    label: '保司认定金额',
    inputType: 'decimal',
    rules: [
      { required: true, message: '请输入', trigger: 'blur' },
      { pattern: /^\d+$/, message: '只能输入正整数', trigger: 'blur' }
    ]
  },
  {
    type: 'select',
    prop: 'paymentCurrency',
    label: '保司认定币种',
    dictType: 'bx_currency_type',
    rules: [{ required: true, message: '请输入认定币种', trigger: 'blur' }]
  },

  {
    type: 'input',
    prop: 'insured',
    label: '此保单剩余待付金额',
    disabled: true
  },
  {
    type: 'input',
    prop: 'insurede',
    label: '此保单剩余待付币种',
    disabled: true
  }
]
// ==============设置认定结果结束============
// ==============新增对账开始============
const addCheckRecordFormModel = ref({ apiPremiumRemittanceDtoList: [] })
const addCheckRecordFormRef = ref(null)
// 设置汇款
const remittanceFormModel = ref({ apiPremiumRemittanceFileDtoList: [] })
const tempOtherFileList = ref([]) //临时存储其他资料数据

const deleteObjkeys = {
  reconciliationType: 'reconciliationType',
  applicant: 'applicant',
  policyNo: 'policyNo',
  insured: 'insured',
  insuranceCompany: 'insuranceCompany'
}
const remittanceConfig = [
  {
    type: 'select',
    prop: 'paymentMethod',
    label: '缴费方式',
    dictType: 'csf_ap_first_issue',
    rules: [{ required: true, message: '请输入缴费方式', trigger: 'blur' }]
  },
  {
    type: 'input',
    prop: 'paymentAmount',
    label: '付款金额',
    inputType: 'decimal',
    rules: [
      { required: true, message: '请输入', trigger: 'blur' },
      { pattern: /^\d+$/, message: '只能输入正整数', trigger: 'blur' }
    ]
  },
  {
    type: 'select',
    prop: 'paymentCurrency',
    label: '付款币种',
    dictType: 'bx_currency_type',
    rules: [{ required: true, message: '请输入付款币种', trigger: 'blur' }]
  },
  {
    type: 'select',
    prop: 'paymentRel',
    label: '付款人与保单关系',
    dictType: 'rel_pay_policy',
    rules: [{ required: true, message: '请输入', trigger: 'blur' }]
  },
  {
    type: 'input',
    prop: 'payer',
    label: '付款人',
    rules: [{ required: true, message: '请输入', trigger: 'blur' }]
  },
  {
    type: 'select',
    prop: 'payingBank',
    label: '付款银行',
    api: '/base/api/bank/page',
    keywordField: 'policyNo',
    requestParams: { pageNo: 1, pageSize: 20 },
    placeholder: '输入转介人名称搜索',
    debounceWait: 500, // 自定义防抖时间
    valueKey: 'bankBizId',
    labelKey: 'bankName',
    // onChangeExtraFields: {
    //   insured: 'insured', // 选择了保单号码，自动填充保单受保人
    //   policyHolder: 'policyHolder',
    //   insuranceCompany: 'insuranceCompany',
    //   productName: 'productName',
    //   currency: 'currency',
    //   paymentPremium: 'paymentPremium',
    //   paymentTerm: 'paymentTerm'
    // },
    transform: res => {
      return res?.data.records || []
    }
  },
  {
    type: 'input',
    prop: 'paymentAccount',
    label: '付款账号'
  },
  {
    type: 'input',
    prop: 'applicant',
    label: '申请人',
    disabled: true
  },
  {
    type: 'select',
    prop: 'policyNo',
    label: '保单号码',
    api: '/csf/api/policy/list/page/vo',
    keywordField: 'policyNo',
    requestParams: { pageNo: 1, pageSize: 20 },
    placeholder: '输入转介人名称搜索',
    debounceWait: 500, // 自定义防抖时间
    valueKey: 'policyNo',
    labelKey: 'policyNo',
    onChangeExtraFields: {
      insured: 'insured', // 选择了保单号码，自动填充保单受保人
      policyHolder: 'policyHolder',
      insuranceCompany: 'insuranceCompany',
      productName: 'productName',
      currency: 'currency',
      paymentPremium: 'paymentPremium',
      paymentTerm: 'paymentTerm'
    },
    transform: res => {
      return res?.data.records || []
    },
    disabled: true
  },
  {
    type: 'input',
    prop: 'insured',
    label: '被保人',
    disabled: true
  },
  {
    type: 'input',
    prop: 'insuranceCompany',
    label: '保险公司',
    disabled: true
  },
  {
    type: 'select',
    prop: 'reconciliationType',
    label: '对账类型',
    disabled: true,
    dictType: 'reconciliation_type'
  },
  {
    type: 'upload',
    prop: 'paymentVoucherList',
    label: '支付凭证',
    uploadType: 'image',
    multiple: true,
    limit: 5,
    maxSize: 5 * 1024 * 1024, // 5MB
    accept: '.png,.jpg,.jpeg,.webp', // ✅ 改成扩展名！
    action: import.meta.env.VITE_APP_BASE_API + '/oss/api/oss/upload',
    headers: { Authorization: 'Bearer ' + getToken() },
    listType: 'picture-card',
    defaultValue: [],
    span: 24,
    rules: [{ required: true, message: '请上传支付凭证', trigger: 'blur' }]
  },
  {
    type: 'upload',
    prop: 'accountVerificationList',
    label: '账户证明',
    uploadType: 'image',
    multiple: true,
    limit: 5,
    maxSize: 5 * 1024 * 1024, // 5MB
    accept: '.png,.jpg,.jpeg,.webp', // ✅ 改成扩展名！
    action: import.meta.env.VITE_APP_BASE_API + '/oss/api/oss/upload',
    headers: { Authorization: 'Bearer ' + getToken() },
    listType: 'picture-card',
    defaultValue: [],
    span: 24,
    rules: [{ required: true, message: '请上传账户证明', trigger: 'blur' }]
  },
  {
    type: 'upload',
    prop: 'apiPremiumRemittanceFileDtoList',
    label: '其他资料',
    uploadType: 'file',
    multiple: true,
    limit: 5,
    maxSize: 10 * 1024 * 1024, // 5MB
    accept: '.png,.jpg,.jpeg,.webp,.pdf,.doc,.docx,.xls,.xlsx,.txt', // ✅ 支持多种格式
    action: import.meta.env.VITE_APP_BASE_API + '/oss/api/oss/upload',
    headers: { Authorization: 'Bearer ' + getToken() },
    listType: 'text', // ← 按钮样式（非图片卡片）
    defaultValue: [],
    span: 24,
    link: false,
    showFileList: false
  }
]
// 新增汇款
const addRemittance = async () => {
  try {
    //  汇款记录详情也需要回显保费对账得一些字段
    const formData = await addCheckRecordFormRef.value.validate()
    remittanceFormModel.value = {
      ...formData
    }
    remittanceFormModel.value.apiPremiumRemittanceFileDtoList = []
    tempOtherFileList.value = []
    remittanceDialogTitle.value = '新增汇款'
    showRemittance.value = true
  } catch (error) {
    // ❌ 校验失败或提交异常都会进入这里
    console.error('操作失败:', error)
    ElMessage.warning('必填项不能为空')
  }
}
// 删除其他资料附件函数
function removeOtherFile(row, index) {
  const list = [...remittanceFormModel.value.apiPremiumRemittanceFileDtoList]
  proxy.$modal
    .confirm('是否确认删除这个附件？')
    .then(function () {
      if (row.premiumRemittanceFileBizId) {
        console.log('远程删除')

        return deletePremiumRemittanceFile(row.premiumRemittanceFileBizId)
      } else {
        // 本地临时数据，直接从列表中移除
        list.splice(index, 1)
        // ⚠️ 关键：直接赋值触发响应式更新（SearchForm 会收到新值）
        remittanceFormModel.value.apiPremiumRemittanceFileDtoList = tempOtherFileList.value = list
        // 注意：这里不需要 return Promise，因为是同步操作
        // 但为了统一 then 链，可以 return 一个成功标识
        return { code: 200 } // 模拟成功
      }
    })
    .then(res => {
      if (res && res.code == 200) {
        // 调用附件接口，更新附件列表
        otherFileList()
      }
    })
    .catch(() => {})
}
// 获取汇款记录列表
const getPremiumRemittanceList = async () => {
  try {
    const params = {
      premiumReconciliationBizId: addCheckRecordFormModel.value.premiumReconciliationBizId,
      pageNo: 1,
      pageSize: 9999
    }
    const res = await getPremiumRemittanceListApi(params)
    addCheckRecordFormModel.value.apiPremiumRemittanceDtoList = res.data.records
    ElMessage.success(`${remittanceDialogTitle.value}成功`)
    showRemittance.value = false // ✅ 校验 & 提交成功后才关闭
    remittanceFormRef.value.resetForm()
    proxy.$modal.msgSuccess('汇款记录修改成功')
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error(error.message || '加载数据失败')
  }
}
// 获取其他资料得附件列表
const otherFileList = async () => {
  try {
    const params = {
      premiumRemittanceBizId: remittanceFormModel.value.premiumRemittanceBizId,
      pageNo: 1,
      pageSize: 9999
    }
    const res = await getPremiumRemittanceFileList(params)
    remittanceFormModel.value.apiPremiumRemittanceFileDtoList = tempOtherFileList.value =
      res.data.records
    proxy.$modal.msgSuccess('附件删除成功')
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error(error.message || '加载数据失败')
  }
}
// 确认汇款记录
const confirmRemittance = async data => {
  try {
    // ✅ 正确：await validate()，成功时返回表单数据
    const formData = await remittanceFormRef.value.validate()
    let newFormData = JSON.parse(JSON.stringify(formData))
    // 因为汇款记录回显了保费对账的一些字段，但提交汇款记录的时候这些回显的字段是不能提交的，所以在这里做删除
    for (const key in newFormData) {
      if (key == deleteObjkeys[key]) delete newFormData[key]
      // 文件上传的数据格式在这里统一处理
      if (key == 'apiPremiumRemittanceFileDtoList' && newFormData[key].length > 0) {
        newFormData[key] = newFormData[key].map(item => {
          // 有response说明是新上传得，要处理返回格式和字段
          if (item.response) {
            let newObj = item.response.data
            return {
              fileName: newObj.originalName, //文件名
              fileType: newObj.fileType, //文件类型
              fileUrl: newObj.url, //文件URL,
              url: newObj.url //文件URL
            }
          } else {
            return item
          }
        })
      } else if (
        (key == 'paymentVoucherList' || key == 'accountVerificationList') &&
        newFormData[key].length > 0
      ) {
        newFormData[key] = newFormData[key].map(item => item.url)
      }
    }
    let res = {}
    // 编辑状态下修改汇款记录
    if (formData.premiumRemittanceBizId) {
      //编辑单个对账的先写到这里，等会在对接
      const params = {
        ...newFormData
      }
      res = await editSiglePremiumRemittance(params)
      if (res.code === 200) {
        // 更新保费对账详情
        getPremiumReconciliationDetail(addCheckRecordFormModel.value)
        // getPremiumRemittanceList()
      } else {
        ElMessage.error(res.msg || `${remittanceDialogTitle.value}失败`)
      }
    } else {
      // 新增汇款记录状态修改或新增
      if (!newFormData.addRemittanceId) {
        // 新增汇款记录自己家id,便于新增情况下做修改
        newFormData.addRemittanceId = new Date().getTime()
      }
      let index = addCheckRecordFormModel.value.apiPremiumRemittanceDtoList.findIndex(
        item => newFormData.addRemittanceId == item.addRemittanceId
      )

      if (index == -1) {
        // 添加新得汇款记录
        addCheckRecordFormModel.value.apiPremiumRemittanceDtoList.push(newFormData)
      } else {
        // 已经新增过汇款记录只是做修改
        addCheckRecordFormModel.value.apiPremiumRemittanceDtoList[index] = newFormData
      }
    }
    showRemittance.value = false
  } catch (error) {
    // ❌ 校验失败或提交异常都会进入这里
    console.error('操作失败:', error)
    // ⚠️ 不设置 receiptsFlag = false，弹窗保持打开
    ElMessage.warning('请检查表单填写是否正确')
  }
}
// 修改汇款记录
const editRemittance = row => {
  let newObj = JSON.parse(JSON.stringify(row))
  // 添加保费对账弹窗得form表单便于汇款回显
  newObj.reconciliationType = addCheckRecordFormModel.value.reconciliationType
  newObj.applicant = addCheckRecordFormModel.value.applicant
  newObj.policyNo = addCheckRecordFormModel.value.policyNo
  newObj.insured = addCheckRecordFormModel.value.insured
  newObj.insuranceCompany = addCheckRecordFormModel.value.insuranceCompany
  // 上传回显得格式是[{url:''}]所以要处理一下
  for (const key in newObj) {
    if (
      (key == 'paymentVoucherList' ||
        key == 'accountVerificationList' ||
        key == 'apiPremiumRemittanceFileDtoList') &&
      newObj[key] &&
      newObj[key].length > 0
    ) {
      newObj[key] = newObj[key].map(item => {
        if (key == 'apiPremiumRemittanceFileDtoList') {
          return {
            ...item,
            url: item.fileUrl
          }
        } else {
          return {
            url: item
          }
        }
      })
    }
  }
  console.log('====================================')
  console.log('汇款修改', newObj)
  console.log('====================================')
  remittanceFormModel.value = newObj
  showRemittance.value = true
}
// 删除汇款记录
function removeRemittance(row, index) {
  const list = [...addCheckRecordFormModel.value.apiPremiumRemittanceDtoList]
  proxy.$modal
    .confirm('是否确认删除此行数据？')
    .then(function () {
      if (row.premiumRemittanceBizId) {
        console.log('远程删除')

        return deletePremiumRemittance(row.premiumRemittanceBizId)
      } else {
        // 本地临时数据，直接从列表中移除
        const index = list.findIndex(item => item.id === row.id)
        if (index !== -1) {
          list.splice(index, 1)
        }
        addCheckRecordFormModel.value.apiPremiumRemittanceDtoList = list
        console.log(
          'addCheckRecordFormModel.value.apiPremiumRemittanceDtoList',
          addCheckRecordFormModel.value
        )

        // 注意：这里不需要 return Promise，因为是同步操作
        // 但为了统一 then 链，可以 return 一个成功标识
        return { code: 200 } // 模拟成功
      }
    })
    .then(res => {
      if (res && res.code == 200) {
        proxy.$modal.msgSuccess('汇款删除成功')
        // 删除成功要调用保费对账的详情接口，重新汇款记录数据，这里还没做等会做
      }
    })
    .catch(() => {})
}
// ==============新增对账结束============
// 应付单类型通过value转成label
const getFortuneBizTypeLabel = value => {
  const item = fortuneBizTypeOptions.find(item => item.value === value)
  return item?.label || ''
}

const addCheckRecordConfig = [
  {
    type: 'select',
    prop: 'reconciliationType',
    label: '对账类型',
    dictType: 'reconciliation_type',
    rules: [{ required: true, message: '请输入对账类型', trigger: 'blur' }]
  },
  {
    type: 'input',
    prop: 'applicant',
    label: '申请人',
    rules: [{ required: true, message: '请输入申请人', trigger: 'blur' }]
  },
  {
    type: 'select',
    prop: 'policyNo',
    label: '保单号码',
    api: '/csf/api/policy/list/page/vo',
    keywordField: 'policyNo',
    requestParams: { pageNo: 1, pageSize: 20 },
    placeholder: '输入转介人名称搜索',
    debounceWait: 500, // 自定义防抖时间
    valueKey: 'policyNo',
    labelKey: 'policyNo',
    onChangeExtraFields: {
      insured: 'insured', // 选择了保单号码，自动填充保单被保人
      insuranceCompany: 'insuranceCompany'
    },
    transform: res => {
      return res?.data.records || []
    },
    rules: [{ required: true, message: '请输入保单号码', trigger: 'blur' }]
  },
  {
    type: 'input',
    prop: 'insured',
    label: '被保人',
    disabled: true
  },
  {
    type: 'input',
    prop: 'insuranceCompany',
    label: '保险公司',
    disabled: true
  }
]

const apiPremiumReconciliationDto = ref({})
// 获取对账详情
const getPremiumReconciliationDetail = async row => {
  try {
    const res = await getPremiumReconciliationInfo(row.premiumReconciliationBizId)
    apiPremiumReconciliationDto.value = res.data.apiPremiumReconciliationDto
    addCheckRecordFormModel.value = {
      ...res.data.apiPremiumReconciliationDto,
      apiPremiumRemittanceDtoList: res.data.apiPremiumRemittanceDtoList
    }
    receiptsFlag.value = true
    receiptsDialogTitle.value = '编辑保单对账'
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error(error.message || '加载数据失败')
    receiptsFlag.value = false
  }
}
// 按钮事件处理
const handleAdd = () => {
  console.log(addCheckRecordFormModel.value)

  receiptsDialogTitle.value = '新增保单对账'
  receiptsFlag.value = true
}

const handleExport = () => {
  ElMessage.info('点击导出按钮')
}
const handleReset = () => {
  // 重置搜索表单
  searchFormRef.value.resetForm()
  console.log('表单已重置')
  currentPage.value = 1
  loadTableData()
}
const handleQuery = async () => {
  const params = searchFormRef.value.getFormData()
  console.log('params', params)

  loadTableData(params)
}
const visibleDefaultButtons = ref(['add', 'reset', 'query'])
// 按钮配置
const operationBtnList = ref([
  {
    key: 'add',
    direction: 'left',
    label: '新增保费对账',
    click: handleAdd
  },

  // {
  //   key: 'export',
  //   direction: 'right',
  //   click: handleExport
  // },
  {
    key: 'reset',
    direction: 'right',
    click: handleReset
  },
  {
    key: 'query',
    direction: 'right',
    click: handleQuery
  }
])

// 加载表格数据
const loadTableData = async (searchParams = {}) => {
  loading.value = true
  try {
    const params = {
      pageNo: currentPage.value,
      pageSize: pageSize.value,
      ...searchParams
    }
    const res = await premiumReconciliationList(params)
    tableData.value = res.data.records || []

    pageTotal.value = res.data.total || 0
    pageSize.value = res.data.size || 0
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error(error.message || '加载数据失败')
  } finally {
    loading.value = false
  }
}

// 分页事件
const handleSizeChange = val => {
  pageSize.value = val
  loadTableData()
}
const handleCurrentChange = val => {
  currentPage.value = val
  loadTableData()
}
// 表格数据
const tableData = ref([])

const handleSelect = (e, row) => {
  console.log('选中行:', e, row)
  selectedRow.value = row
  if (e == 'editRecord') {
    getPremiumReconciliationDetail(row)
  } else if (e == 'settingResult') {
    affirmFormModel.value = {}
    showAffirm.value = true
  }
}
const addReceipts = async () => {
  try {
    // ✅ 正确：await validate()，成功时返回表单数据
    const formData = await addCheckRecordFormRef.value.validate()
    let apiPremiumReconciliationDto = {}
    let apiPremiumRemittanceDtoList = JSON.parse(
      JSON.stringify(formData.apiPremiumRemittanceDtoList)
    )
    for (const key in formData) {
      if (!Array.isArray(formData[key])) {
        apiPremiumReconciliationDto[key] = formData[key]
      }
    }
    // if (apiPremiumRemittanceDtoList.length > 0) {
    //   apiPremiumRemittanceDtoList.forEach(item => {
    //     if (item.paymentVoucherList && item.paymentVoucherList.length > 0) {
    //       item.paymentVoucherList = item.paymentVoucherList.map(item1 => item1.url)
    //     }
    //     if (item.accountVerificationList && item.accountVerificationList.length > 0) {
    //       item.accountVerificationList = item.accountVerificationList.map(item1 => item1.url)
    //     }
    //   })
    // }
    const params = {
      apiPremiumReconciliationDto: apiPremiumReconciliationDto,
      apiPremiumRemittanceDtoList: apiPremiumRemittanceDtoList
    }
    // console.log('新增保单对账:', params)
    // return
    let res = {}
    if (formData.policyReceiptBizId) {
      params.policyReceiptBizId = formData.policyReceiptBizId
      res = await EditPolicyReceipt(params)
    } else {
      res = await addPremiumReconciliation(params)
    }
    if (res.code === 200) {
      ElMessage.success(`${receiptsDialogTitle.value}成功`)
      receiptsFlag.value = false // ✅ 校验 & 提交成功后才关闭
      addCheckRecordFormRef.value.resetForm()
      loadTableData()
    } else {
      ElMessage.error(res.msg || `${receiptsDialogTitle.value}失败`)
    }
  } catch (error) {
    // ❌ 校验失败或提交异常都会进入这里
    console.error('操作失败:', error)
    // ⚠️ 不设置 receiptsFlag = false，弹窗保持打开
    ElMessage.warning('请检查表单填写是否正确')
    // 注意：Element Plus 的 validate 失败时，错误信息已自动显示在表单项下方
  }
}

const updatePayRollStatusDisable = ref(true)
const multipleSelection = ref([])
const handleSelectionChange = val => {
  multipleSelection.value = val
  console.log('全选:', val)
  // 完成检核按钮是否禁用
  updatePayRollStatusDisable.value = val.length === 0
}

import FileUploadPreview from '@/components/fileUploadPreview/fileUploadPreview.vue'

const onSubmit = data => {
  console.log('提交给后端的数据:', data)
  // 调用保存 API
}

// 获取入账状态,字典值转化方法
onMounted(async () => {
  try {
    await loadDicts([
      'csf_ap_first_issue',
      'csf_policy_follow_status_new',
      'csf_policy_status_new',
      'reconciliation_status',
      'bx_currency_type',
      'reconciliation_type',
      'rel_pay_policy'
    ])
    loadTableData()
  } catch (error) {
    console.error('字典加载失败', error)
  } finally {
    loading.value = false
  }
})
watch(
  () => remittanceFormModel.value.apiPremiumRemittanceFileDtoList,
  newVal => {
    console.log('newVal', newVal)

    if (newVal && newVal.length > 0) {
      newVal.forEach(item => {
        // 代表是从新增保单对账开始
        if (item.response) {
          let newObj = JSON.parse(JSON.stringify(item.response.data))
          // tempOtherFileList这个变量便于其他资料文件表格得展示使用
          tempOtherFileList.value.push({
            fileName: newObj.originalName, //文件名
            fileType: newObj.fileType, //文件类型
            fileUrl: newObj.url, //文件URL,
            url: newObj.url //文件URL
          })
        } else {
          // 从编辑对账或已经新增过汇款要修改汇款
          tempOtherFileList.value = JSON.parse(JSON.stringify(newVal))
        }
      })
    }
  },
  { deep: true }
)

watch(receiptsFlag, newVal => {
  if (!newVal) {
    addCheckRecordFormModel.value = {}
    receiptsDialogTitle.value = ''
  }
})
</script>

<style scoped>
.tableOptionContainer {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}
.otherFileBox {
  margin-bottom: 50px;
}
</style>
