<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="currentIssueNumber" label="当前期数" width="80" fixed="left" />
          <el-table-column prop="reconciliationType" label="对账类型" width="150">
            <template #default="{ row }">
              {{
                row.currentIssueNumber && row.currentIssueNumber == '1'
                  ? '首期保费对账'
                  : '续期保费对账'
              }}
            </template>
          </el-table-column>
          <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 label="付款银行" prop="payingBank" width="150">
            <template #default="{ row }">
              {{ changeDictLabel('bank', row.payingBank) }}
            </template>
          </el-table-column>
          <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-button link type="primary" size="small">
                    <el-icon><MoreFilled /></el-icon>
                  </el-button>
                </template>

                <el-menu @select="handleSelect($event, row)" popper-class="custom-menu">
                  <el-menu-item
                    v-for="item in getMenuItems(row)"
                    :key="item.value"
                    :index="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"
        @select-change="onSelectChange"
      />
      <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 prop="paymentDate" label="付款日期" width="150">
              <template #default="{ row }">
                {{ row.paymentDate ? formatToDate(row.paymentDate) : '' }}
              </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">
              <template #default="{ row }">
                {{ changeDictLabel('bank', row.payingBank) }}
              </template>
            </el-table-column>
            <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"
      @confirm="confirmAffirm"
      :confirmLoading="settingAffirmLoading"
    >
      <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"
            @uploadSuccess="handleUploadSuccess"
          />
          <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 {
  premiumReconciliationList,
  EditPolicyReceipt,
  editPremiumRemittance,
  addPremiumReconciliation,
  getPremiumReconciliationInfo,
  deletePremiumRemittanceFile,
  getPremiumRemittanceFileList,
  editSiglePremiumRemittance,
  getPremiumRemittanceListApi,
  deletePremiumRemittance,
  getCheckPolicyNoApi,
  editPremiumReconciliation,
  getRemainingUnpaidAmount,
  submitResult,
  addSinglePremiumRemittance
} from '@/api/sign/policy'
import { getBankList } from '@/api/common'
import useUserStore from '@/store/modules/user'
import { loadDicts, getDictLabel } from '@/utils/useDict'
import { getToken } from '@/utils/auth'
import { getNowTime, formatToDate, formatToDateTime } from '@/utils/date'
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 bankOptions = ref([]) //银行options
const currentRow = ref({}) //银行options
const settingAffirmLoading = ref(false)
const searchConfig = ref([
  {
    type: 'select',
    prop: 'insuranceCompanyBizId',
    label: '保险公司',
    api: '/insurance/base/api/insuranceCompany/page',
    keywordField: 'fullName',
    requestParams: { pageNo: 1, pageSize: 20 },
    placeholder: '输入保险公司名称搜索',
    debounceWait: 500, // 自定义防抖时间
    multiple: false,
    valueKey: 'insuranceCompanyBizId',
    labelKey: 'fullName',
    transform: res => {
      console.log(res)
      return res?.data.records || []
    }
  },
  {
    type: 'select',
    prop: 'payingBank',
    label: '付款银行',
    api: '/base/api/bank/page',
    keywordField: 'bankName',
    requestParams: { pageNo: 1, pageSize: 20 },
    placeholder: '输入保险公司名称搜索',
    debounceWait: 500, // 自定义防抖时间
    multiple: false,
    valueKey: 'bankBizId',
    labelKey: 'bankName',
    transform: res => {
      console.log(res)
      return res?.data.records || []
    }
  },
  {
    type: 'input',
    prop: 'payer',
    label: '付款人'
  },
  {
    type: 'input',
    prop: 'policyNo',
    label: '保单号'
  },
  {
    type: 'input',
    prop: 'appointmentNo',
    label: '预约编号'
  },
  {
    type: 'input',
    prop: 'policyHolder',
    label: '投保人'
  },
  {
    type: 'select',
    prop: 'paymentMethod',
    label: '缴费方式',
    multiple: false,
    dictType: 'csf_ap_first_issue'
  },
  {
    type: 'select',
    prop: 'policyFollowStatus',
    label: '新单状态',
    multiple: false,
    dictType: 'csf_policy_follow_status_new'
  },
  {
    type: 'select',
    prop: 'policyStatus',
    label: '保单状态',
    multiple: false,
    dictType: 'csf_policy_status_new'
  },
  {
    type: 'select',
    prop: 'reconciliationType',
    label: '对账类型',
    multiple: false,
    dictType: 'reconciliation_type'
  },
  {
    type: 'date',
    prop: 'paymentDate',
    label: '付款日期',

    maxDate: 'today'
  }
])
// 动态生成操作菜单项
const getMenuItems = row => {
  const items = [{ label: '编辑', value: 'editRecord' }]

  // 只有 reconciliationStatus 不是 'BS_DZ_CG' 时才显示“设置认定结果”
  if (row.reconciliationStatus !== 'BS_DZ_CG') {
    items.push({ label: '设置认定结果', value: 'settingResult' })
  }

  // 未来可继续添加其他条件项，例如：
  // if (row.status === 'xxx') { items.push(...) }

  return items
}
//获取远程搜索下拉框数据，回显数据用
const getSelectOptions = async () => {
  const params4 = {
    pageNo: 1,
    pageSize: 99999
  }
  const response4 = await getBankList(params4)
  if (response4.code == 200) {
    response4.data.records = response4.data.records.map(item => {
      return {
        ...item,
        label: item.bankName,
        value: item.bankBizId
      }
    })
    bankOptions.value = response4.data.records
  }
}
function changeDictLabel(type, value) {
  if (type == 'bank') {
    const bank = bankOptions.value.find(opt => opt.value === value)
    return bank ? bank.label : value || ''
  }
}
// ==============设置认定结果开始============
const showAffirm = ref(false)
const affirmFormRef = ref(null)
const affirmFormModel = ref({})

const affirmConfig = [
  {
    type: 'input',
    prop: 'recognizedAmount',
    label: '保司认定金额',
    inputType: 'decimal',
    decimalDigits: 4,
    rules: [
      { required: true, message: '请输入', trigger: 'blur' },
      { pattern: /^\d+(\.\d{1,4})?$/, message: '最多四位小数', trigger: 'blur' }
    ]
  },
  {
    type: 'select',
    prop: 'recognizedCurrency',
    label: '保司认定币种',
    dictType: 'bx_currency_type',
    rules: [{ required: true, message: '请输入认定币种', trigger: 'blur' }]
  },

  {
    type: 'input',
    prop: 'remainingUnpaidAmount',
    label: '此保单剩余待付金额',

    disabled: true
  },
  {
    type: 'select',
    prop: 'remainingUnpaidCurrency',
    label: '此保单剩余待付币种',
    disabled: true,
    dictType: 'bx_currency_type'
  },
  {
    type: 'date',
    prop: 'effectiveDate',
    label: '保单生效日',
    placeholder: '请选择',
    maxDate: 'today',
    visible: formData =>
      (formData.remainingUnpaidAmount && Number(formData.remainingUnpaidAmount) < 0) ||
      Number(formData.remainingUnpaidAmount) == 0,
    rules: [{ required: true, message: '请输入', trigger: 'blur' }]
  },
  {
    type: 'date',
    prop: 'underwritingDate',
    label: '保单核保日',
    placeholder: '请选择',
    maxDate: 'today',
    rules: [{ required: true, message: '请输入', trigger: 'blur' }],
    visible: formData =>
      (formData.remainingUnpaidAmount && Number(formData.remainingUnpaidAmount) < 0) ||
      Number(formData.remainingUnpaidAmount) == 0
  },
  {
    type: 'select',
    prop: 'status',
    label: '保单状态',
    dictType: 'csf_policy_status_new',
    visible: formData =>
      (formData.remainingUnpaidAmount && Number(formData.remainingUnpaidAmount) < 0) ||
      Number(formData.remainingUnpaidAmount) == 0
  },
  {
    type: 'date',
    prop: 'policyExpirationDate',
    label: '保单截止日',
    placeholder: '请选择',
    // maxDate: 'today',
    visible: formData =>
      (formData.remainingUnpaidAmount && Number(formData.remainingUnpaidAmount) < 0) ||
      Number(formData.remainingUnpaidAmount) == 0
    // rules: [{ required: true, message: '请输入', trigger: 'blur' }]
  },
  {
    type: 'date',
    prop: 'coolingOffEndDate',
    label: '冷静期到期日',
    placeholder: '请选择',
    // maxDate: 'today',
    visible: formData =>
      (formData.remainingUnpaidAmount && Number(formData.remainingUnpaidAmount) < 0) ||
      Number(formData.remainingUnpaidAmount) == 0,
    rules: [{ required: true, message: '请输入', trigger: 'blur' }]
  }
]
//计算待付金额
const calculateAmount = async () => {
  try {
    const params = {
      premiumReconciliationBizId: currentRow.value.premiumReconciliationBizId, //保费对账记录表唯一业务ID, //保费对账记录表唯一业务ID
      recognizedAmount: affirmFormModel.value.recognizedAmount, //当次保司认定金额（客户当次缴纳的金额）
      recognizedCurrency: affirmFormModel.value.recognizedCurrency //当次保司认定币种
    }
    const res = await getRemainingUnpaidAmount(params)
    affirmFormModel.value.remainingUnpaidAmount = res.data.remainingUnpaidAmount
    affirmFormModel.value.remainingUnpaidCurrency = res.data.remainingUnpaidCurrency
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error(error.message || '加载数据失败')
  }
}
const confirmAffirm = async () => {
  settingAffirmLoading.value = true
  try {
    const formData = await affirmFormRef.value.validate()
    console.log(formData.value)
    let newObj = JSON.parse(JSON.stringify(formData))
    for (const key in newObj) {
      if (/Date/.test(key)) {
        newObj[key] = proxy.formatToDateTime(newObj[key])
      }
    }
    newObj.premiumReconciliationBizId = currentRow.value.premiumReconciliationBizId
    let res = await submitResult(newObj)
    if (res.code == 200) {
      settingAffirmLoading.value = false
      ElMessage.success('认定成功')
      showAffirm.value = false
      affirmFormModel.value = {}
      affirmFormRef.value.resetForm()
      loadTableData()
      currentRow.value = {}
    }
  } catch (error) {
    console.log('error', error)
    settingAffirmLoading.value = false
    if (error.message && error.message.includes('Validation')) {
      ElMessage.error('必填项不能为空')
    }
  }
}
// ==============设置认定结果结束============
// ==============新增对账开始============
const addCheckRecordFormModel = ref({ apiPremiumRemittanceDtoList: [] })
const addCheckRecordFormRef = ref(null)
// 设置汇款
const remittanceFormModel = ref({ apiPremiumRemittanceFileDtoList: [] })
const tempOtherFileList = ref([]) //临时存储其他资料数据
const isSubmitReceipts = ref(false) //是否可以提交对账
const tipTxt = 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',
    decimalDigits: 4,
    rules: [
      { required: true, message: '请输入', trigger: 'blur' },
      {
        validator: (rule, value, callback) => {
          if (value === '' || value == null) {
            callback(new Error('请输入付款金额'))
          } else {
            callback()
          }
        },
        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: 'date',
    prop: 'paymentDate',
    label: '付款日期',
    placeholder: '请选择',
    maxDate: 'today'
  },
  {
    type: 'select',
    prop: 'payingBank',
    label: '付款银行',
    api: '/base/api/bank/page',
    keywordField: 'policyNo',
    requestParams: { pageNo: 1, pageSize: 50 },

    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_follow/policyNos',
    keywordField: 'policyNo',
    requestParams: { pageNo: 1, pageSize: 100 },
    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: 'file',
    multiple: true,
    limit: 10,
    maxSize: 10 * 1024 * 1024, // 10MB
    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,
    rules: [{ required: true, message: '请上传支付凭证', trigger: 'blur' }]
  },
  {
    type: 'upload',
    prop: 'accountVerificationList',
    label: '账户证明',
    uploadType: 'file',
    multiple: true,
    limit: 10,
    maxSize: 10 * 1024 * 1024, // 10MB
    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,
    rules: [{ required: true, message: '请上传账户证明', trigger: 'blur' }]
  },
  {
    type: 'upload',
    prop: 'apiPremiumRemittanceFileDtoList',
    label: '其他资料',
    uploadType: 'file',
    multiple: true,
    limit: 10,
    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 handleUploadSuccess = (prop, Model) => {
  if (prop == 'apiPremiumRemittanceFileDtoList') {
    let list = [...Model.apiPremiumRemittanceFileDtoList]
    tempOtherFileList.value = []
    list.forEach(item => {
      // 代表是从新增保单对账开始
      if (item.response) {
        let newObj = JSON.parse(JSON.stringify(item.response.data))
        ;((item.fileName = newObj.originalName), //文件名
          (item.fileType = newObj.fileType), //文件类型
          (item.fileUrl = newObj.url), //文件URL,
          (item.url = newObj.url))
      }
    })
    tempOtherFileList.value = list
  }
}
// 下拉框改变
function onSelectChange(prop, value, item) {
  console.log('【Select 变更】字段:', prop, '新值:', value, '配置:', item)

  // 示例：你可以在这里做任何事
  if (prop === 'policyNo') {
    checkPolicyNo(value)
  }
}
// 新增汇款
const addRemittance = async () => {
  if (tipTxt.value) {
    proxy.$modal.confirm(`${tipTxt.value}`, { showCancel: '0', title: '填写提示' })
    return
  }
  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]
  console.log('删除附件', row)

  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 && row.premiumRemittanceFileBizId) {
        // 调用附件接口，更新附件列表
        otherFileList()
      }
    })
    .catch(() => {})
}
// 检查此保单号是否已经提交过保费对账
const checkPolicyNo = async policyNo => {
  try {
    const res = await getCheckPolicyNoApi(policyNo)
    if (!res.data) {
      proxy.$modal.confirm(`${res.msg}`, { showCancel: '0', title: '填写提示' })
      tipTxt.value = res.msg
    }

    isSubmitReceipts.value = res.data
  } 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 (currentRow.value.premiumReconciliationBizId && !formData.premiumRemittanceBizId) {
      //编辑保费对账状态下新增汇款记录
      const params = {
        ...newFormData,
        premiumReconciliationBizId: currentRow.value.premiumReconciliationBizId
      }
      res = await addSinglePremiumRemittance(params)
      if (res.code === 200) {
        // 更新保费对账详情
        getPremiumReconciliationDetail(addCheckRecordFormModel.value)
      } else {
        ElMessage.error(res.msg || `${remittanceDialogTitle.value}失败`)
      }
    } else if (formData.premiumRemittanceBizId) {
      //编辑保费对账状态下修改汇款记录
      const params = {
        ...newFormData
      }
      res = await editSiglePremiumRemittance(params)
      if (res.code === 200) {
        // 更新保费对账详情
        getPremiumReconciliationDetail(addCheckRecordFormModel.value)
      } 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
          }
        }
      })
    }
  }

  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('汇款删除成功')
        // 重新获取详情拿到最新数据
        getPremiumReconciliationDetail(addCheckRecordFormModel.value)
        // 删除成功要调用保费对账的详情接口，重新汇款记录数据，这里还没做等会做
      }
    })
    .catch(() => {})
}
// ==============新增对账结束============

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_follow/policyNos',
    keywordField: 'policyNo',
    requestParams: { pageNo: 1, pageSize: 100 },
    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 = (command, row) => {
  selectedRow.value = row
  if (command === 'editRecord') {
    currentRow.value = JSON.parse(JSON.stringify(row))
    getPremiumReconciliationDetail(row)
  } else if (command === 'settingResult') {
    affirmFormModel.value = {}
    settingAffirmLoading.value = false
    showAffirm.value = true
    currentRow.value = JSON.parse(JSON.stringify(row))
  }
}
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]
      }
    }

    let params = {}

    let res = {}
    if (formData.premiumReconciliationBizId) {
      params = {
        ...apiPremiumReconciliationDto
      }
      res = await editPremiumReconciliation(params)
    } else {
      params = {
        apiPremiumReconciliationDto: apiPremiumReconciliationDto,
        apiPremiumRemittanceDtoList: apiPremiumRemittanceDtoList
      }
      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
}
// 获取入账状态,字典值转化方法
onMounted(async () => {
  try {
    await getSelectOptions()
    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(affirmFormModel, newVal => {
  if (newVal.recognizedAmount && newVal.recognizedCurrency) {
    calculateAmount()
  } else {
    affirmFormModel.value.remainingUnpaidAmount = 0
    affirmFormModel.value.remainingUnpaidCurrency = ''
  }
})
watch(receiptsFlag, newVal => {
  if (!newVal) {
    isSubmitReceipts.value = false
    tipTxt.value = ''
    addCheckRecordFormModel.value = { apiPremiumRemittanceDtoList: [] }
    receiptsDialogTitle.value = ''
  }
})
</script>

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