<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>
        <!-- 统计信息卡片  v-if="statisticsData.totalInAmount > 0"-->
        <div class="statistics-container">
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :md="4" class="text-center mb-4">
              <el-statistic
                title="入账金额"
                :value="statisticsData.totalInAmount"
                :formatter="value => formatCurrency(value)"
              />
            </el-col>
            <el-col :xs="24" :sm="12" :md="4" class="text-center mb-4">
              <el-statistic title="总保单数" :value="statisticsData.totalPolicyCount" />
            </el-col>
            <el-col :xs="24" :sm="12" :md="4" class="text-center mb-4">
              <el-statistic
                title="总保费（HKD）"
                :value="statisticsData.totalPremium"
                :formatter="value => formatCurrency(value)"
              />
            </el-col>
            <el-col :xs="24" :sm="12" :md="4" class="text-center mb-4">
              <el-statistic
                title="待出账金额"
                :value="statisticsData.pendingOutAmount"
                :formatter="value => formatCurrency(value)"
              />
            </el-col>
            <el-col :xs="24" :sm="12" :md="4" class="text-center mb-4">
              <el-statistic
                title="可出账金额"
                :value="statisticsData.availableOutAmount"
                :formatter="value => formatCurrency(value)"
              />
            </el-col>
            <el-col :xs="24" :sm="12" :md="4" class="text-center mb-4">
              <el-statistic
                title="差额（估）"
                :value="statisticsData.differenceAmount"
                :formatter="value => formatCurrency(value)"
              />
            </el-col>
          </el-row>
        </div>
        <el-table
          ref="multipleTableRef"
          :data="tableData"
          row-key="fortuneBizId"
          @selection-change="handleSelectionChange"
          height="400"
          border
          highlight-current-row
          style="width: 100%"
          v-loading="loading"
        >
          <el-table-column type="selection" width="40" fixed="left" :selectable="isSelectable" />
          <el-table-column prop="payableNo" label="业务编号" width="150" fixed="left" />
          <el-table-column prop="status" label="出账状态" width="160" sortable fixed="left">
            <template #default="{ row }">
              {{ selectDictLabel(csf_fortune_status, row.status) }}
            </template>
          </el-table-column>
          <el-table-column prop="policyNo" label="保单号" width="120" sortable fixed="left" />
          <el-table-column
            prop="insuranceCompany"
            label="保险公司"
            width="120"
            sortable
            fixed="left"
          />
          <el-table-column prop="broker" label="转介人" width="130" sortable fixed="left" />
          <el-table-column
            prop="commissionPaidAmount"
            label="累积已入账金额"
            width="120"
            sortable
            :formatter="row => formatCurrency(row.commissionPaidAmount || 0)"
          />
          <el-table-column prop="reconciliationYearMonth" label="检核年月" width="130" sortable />
          <el-table-column
            prop="commissionPendingRatio"
            label="达成率缺口"
            width="120"
            sortable
            :formatter="row => `${row.commissionPendingRatio ? row.commissionPendingRatio : 0}%`"
          />
          <el-table-column prop="fortuneName" label="出账项目" width="130" sortable />
          <el-table-column prop="fortunePeriod" label="出账期数" width="130" sortable />
          <el-table-column prop="fortuneTotalPeriod" label="总期数" width="120" sortable />

          <el-table-column prop="brokerGradeName" label="转介人职级" width="100" />
          <el-table-column prop="team" label="所属团队" width="120" sortable />
          <el-table-column
            prop="exchangeRate"
            label="结算汇率（估）"
            width="140"
            :formatter="row => formatNumberToMaxDigits(row.exchangeRate, 5, '-')"
          >
          </el-table-column>
          <el-table-column
            prop="hkdAmount"
            label="应出账金额（HKD）"
            width="160"
            sortable
            :formatter="row => formatCurrency(row.hkdAmount || 0)"
          />
          <el-table-column prop="payoutCurrency" label="出账币种" width="130" sortable />
          <el-table-column
            prop="fortunePaidAmount"
            label="已出账金额"
            width="160"
            sortable
            :formatter="row => formatCurrency(row.fortunePaidAmount || 0)"
          />
          <el-table-column
            prop="fortuneUnpaidAmount"
            label="剩余出账金额"
            width="160"
            sortable
            :formatter="row => formatCurrency(row.fortuneUnpaidAmount || 0)"
          />
          <!-- <el-table-column prop="currentPaymentAmount" label="本期出账金额" width="120" sortable/> -->
          <el-table-column
            prop="currentPaymentHkdAmount"
            label="本期出账金额（HKD）"
            width="160"
            sortable
            :formatter="row => formatCurrency(row.currentPaymentHkdAmount || 0)"
          />
          <el-table-column
            prop="fortuneUnpaidRatio"
            label="剩余出账比例"
            width="120"
            sortable
            :formatter="row => `${row.fortuneUnpaidRatio}%`"
          />

          <el-table-column
            prop="premium"
            label="期交保费"
            width="120"
            sortable
            :formatter="row => formatCurrency(row.premium || 0)"
          />
          <el-table-column prop="policyCurrency" label="保单币种" width="120" sortable />
          <el-table-column prop="payoutDate" label="出账月（估）" width="120" sortable />
          <el-table-column prop="actualPayoutDate" label="出账月（实）" width="120" sortable />
          <el-table-column prop="isPart" label="是否拆分出账" width="120">
            <template #default="scope">
              <dict-tag :options="sys_no_yes" :value="scope.row.isPart" />
            </template>
          </el-table-column>
          <el-table-column prop="fortuneBizType" label="应付单类型" width="120" sortable>
            <template #default="{ row }">
              {{ getFortuneBizTypeLabel(row.fortuneBizType) }}
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" width="120" sortable />
          <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 getOperateItems(row)"
                    :key="item.value"
                    >{{ item.label }}</el-menu-item
                  >
                </el-menu>
              </el-popover>
            </template>
          </el-table-column>
        </el-table>
        <!-- 表格操作菜单 -->
        <div class="tableOptionContainer">
          <el-button
            type="primary"
            :icon="EditPen"
            :disabled="updatePayRollStatusDisable"
            @click="batchSettingBillYearMonth"
            >批量设置出账年月(实)</el-button
          >
          <el-button
            type="primary"
            :icon="Select"
            :disabled="updatePayRollStatusDisable"
            @click="downloadPolicyFortuneAccountapi"
            >完成检核</el-button
          >
        </div>
      </template>
    </CommonPage>
    <!-- 新增出账检核页面-->
    <CommonDialog
      dialogTitle="新增出账检核"
      dialogWidth="80%"
      :openDialog="addCheckRecordFormDialogFlag"
      :showAction="true"
      :showClose="true"
      @close="addCheckRecordFormDialogFlag = false"
      @confirm="addCheckRecordaddBatchapi"
    >
      <SearchForm
        ref="addCheckRecordFormRef"
        :config="addCheckRecordConfig"
        v-model="addCheckRecordFormModel"
        @inputChange="(prop, value, item) => handleInputChange('addCheckRecord', prop, value, item)"
      />
    </CommonDialog>
    <!-- 导入出账检核页面 -->
    <CommonDialog
      dialogTitle="新增出账检核"
      dialogWidth="80%"
      :openDialog="importCheckRecordFlag"
      :showAction="true"
      :showClose="true"
      @close="importCheckRecordFlag = false"
    >
      <FileUploadPreview
        :header-row="0"
        :required-fields="'amount,exchangeRate'"
        :use-chinese-header="true"
        :transform-submit-data="transformToBackend"
        @submit="onSubmit"
      />
    </CommonDialog>
    <!-- 设置本期出账金额 -->
    <CommonDialog
      dialogTitle="设置本期出账金额"
      dialogWidth="80%"
      :openDialog="setPayoutAmountDialogFlag"
      :showAction="true"
      :showClose="true"
      @close="setPayoutAmountDialogFlag = false"
      @confirm="updatePayoutAmountapi"
    >
      <SearchForm
        ref="setPayoutAmountFormRef"
        :config="setPayoutAmountConfig"
        v-model="setPayoutAmountFormModel"
      />
    </CommonDialog>
    <!-- 分期出账弹窗 -->
    <CommonDialog
      dialogTitle="分期出账"
      dialogWidth="90%"
      confirmText="提交"
      :openDialog="installmentsBillFlag"
      :showAction="true"
      :showClose="true"
      @close="installmentsBillFlag = false"
      @confirm="handleSpiltSubmit"
    >
      <editTable
        ref="editTableRef"
        addBtnTxt="添加出账"
        v-model:table-data="splitTableData"
        :columns="splitTableColumns"
        row-id-key="id"
        show-operation
        @delete="handleSpiltDelete"
        @add="addSpiltRecord"
        @cell-change="handleSplitCellChange"
      />
    </CommonDialog>
    <!-- 设置出账年月弹窗 -->
    <CommonDialog
      dialogTitle="设置本期出账年月(实)"
      dialogWidth="80%"
      :openDialog="settingBillYearMonthFlag"
      :showAction="true"
      :showClose="true"
      @close="settingBillYearMonthFlag = false"
      @confirm="submitSettingBillYearMonth"
    >
      <SearchForm
        ref="settingBillYearMonthRef"
        :config="settingBillTimeConfig"
        v-model="settingBillTimeForm"
      />
    </CommonDialog>
    <!-- 修改结算汇率 -->
    <CommonDialog
      dialogTitle="修改结算汇率"
      dialogWidth="80%"
      :openDialog="rateExchangeFlag"
      :showAction="true"
      :showClose="true"
      @close="rateExchangeFlag = false"
      @confirm="confirmRateExchange"
    >
      <SearchForm
        ref="rateExchangeFormRef"
        :config="rateExchangeConfig"
        v-model="rateExchangeForm"
        @inputChange="(prop, value, item) => handleInputChange('rateExchange', prop, value, item)"
      />
    </CommonDialog>
  </div>
</template>

<script setup>
import { round } from 'lodash-es' // 或者自己实现小数保留
import { ref, reactive, nextTick, watch } from 'vue'
import CommonPage from '@/components/commonPage'
import editTable from '@/components/Table/editTable.vue'
import CommonDialog from '@/components/commonDialog'
import SearchForm from '@/components/SearchForm/SearchForm.vue'
import { ElMessage } from 'element-plus'
import { formatCurrency, calculateAmount, formatNumberToMaxDigits } from '@/utils/number'
import { Select, EditPen } from '@element-plus/icons-vue'

// 接口
import {
  getPolicyFortuneList,
  addCheckRecordaddBatch,
  updatePayoutAmount,
  downloadPolicyFortuneAccount,
  billSplitApi,
  commissionExchangeRateApi,
  actualPayoutDateApi,
  editExchangeRateApi,
  batchActualPayoutDate,
  statisticsFortune
} from '@/api/financial/commission'
import useUserStore from '@/store/modules/user'
const spiltDigit = ref(2)
const rateExchangeFormRef = ref(null)
const rateExchangeFlag = ref(false)
const rateExchangeForm = ref({})
const billTimeType = ref('single')
const settingBillTimeForm = ref({})
const splitTableData = ref([])
const installmentsBillFlag = ref(false)
const settingBillYearMonthFlag = ref(false)
const { proxy } = getCurrentInstance()
const { csf_fortune_status, sys_no_yes } = proxy.useDict('csf_fortune_status', 'sys_no_yes')
const multipleTableRef = ref(null)
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 oldStaticData = ref({})
// 动态生成操作菜单项（根据行数据）
const getOperateItems = row => {
  const items = []

  // 条件：isPart == 1 时不显示分期出账（使用宽松相等，兼容字符串 '1'）
  if (!(row.isPart == 1 || row.status == '2')) {
    items.push({ label: '分期出账', value: 'billInstallments' })
  }
  // 出账状态不为已出帐的都可以修改结算汇率
  if (row.status !== '2') {
    items.push({ label: '修改结算汇率', value: 'editExchangeRate' })
  }

  // 始终显示的菜单项（保持原始顺序）
  items.push({ label: '设置出账年月(实)', value: 'settingBillYearMonth' })

  return items
}
const searchConfig = ref([
  {
    type: 'input',
    prop: 'policyNo',
    label: '保单号'
  },
  {
    type: 'input',
    prop: 'brokerName',
    label: '转介人'
  },
  {
    type: 'select',
    prop: 'statusList',
    label: '出账状态',
    multiple: true,
    dictType: 'csf_fortune_status'
  },
  {
    type: 'select',
    prop: 'insuranceCompanyBizIdList',
    label: '保险公司',
    api: '/insurance/base/api/insuranceCompany/page',
    keywordField: 'queryContent',
    requestParams: { pageNo: 1, pageSize: 20 },
    placeholder: '输入保险公司名称搜索',
    debounceWait: 500, // 自定义防抖时间
    multiple: true,
    valueKey: 'insuranceCompanyBizId',
    labelKey: 'fullName',
    transform: res => {
      console.log(res)
      return res?.data.records || []
    }
  },
  {
    type: 'select',
    prop: 'productLaunchBizIdList',
    label: '产品计划',
    api: '/product/api/relProjectProductLaunch/parameter/page',
    keywordField: 'productName',
    requestParams: {
      tenantBizId: userStore.projectInfo.tenantBizId || '',
      projectBizId: userStore.projectInfo.projectBizId || '',
      fieldBizId: 'field_olk1qZe81qHHKXbw',
      fieldValueBizId: 'field_value_uOfJH5ucA2YwJpbn',
      pageNo: 1,
      pageSize: 20
    },
    placeholder: '输入产品计划名称搜索',
    debounceWait: 500, // 自定义防抖时间
    multiple: true,
    valueKey: 'productLaunchBizId',
    labelKey: 'productName',
    transform: res => {
      return res?.data.records || []
    }
  },
  {
    type: 'month',
    prop: 'reconciliationYearMonth',
    label: '检核年月',
    startPlaceholder: '开始时间',
    endPlaceholder: '结束时间'
  },
  {
    type: 'monthrange',
    prop: 'actualPayoutDate',
    label: '出账月（实）',
    startPlaceholder: '开始时间',
    endPlaceholder: '结束时间'
  },
  {
    type: 'monthrange',
    prop: 'payoutDate',
    label: '出账月（估）',
    startPlaceholder: '开始时间',
    endPlaceholder: '结束时间'
  },
  {
    type: 'select',
    prop: 'commissionStatusList',
    label: '入账状态',
    multiple: true,
    dictType: 'csf_expected_commission_status'
  }
])
const editTableRef = ref(null)
const splitTableColumns = ref([
  {
    prop: 'splitRatio',
    label: '出账比例(%)',
    editType: 'input',
    inputType: 'decimal', // integer / decimalNumber / decimal
    decimalDigits: 2, // 小数位数，默认2
    required: true,
    placeholder: '请输入出账比例',
    width: 150
  },
  {
    editType: 'select',
    prop: 'ruleCurrency',
    label: '保单币种',
    dictType: 'bx_currency_type',
    required: true,
    width: 150
  },
  {
    editType: 'select',
    prop: 'originalCurrency',
    label: '原币种',
    dictType: 'bx_currency_type',
    required: true,
    width: 150
  },
  {
    editType: 'select',
    prop: 'payoutCurrency',
    label: '发放币种',
    dictType: 'bx_currency_type',
    required: true,
    width: 150
  },
  {
    editType: 'input',
    prop: 'originalAmount',
    label: '原币种金额',
    inputType: 'decimalNumber',
    required: true,
    width: 150
  },
  // 汇率3(原币种->港币)
  {
    editType: 'input',
    prop: 'originalToHkdRate',
    label: '原币种->港币(汇率)',
    inputType: 'decimal',
    decimalDigits: 5,
    required: true,
    width: 150
  },
  {
    editType: 'input',
    prop: 'hkdAmount',
    label: '港币金额',
    inputType: 'decimal',

    required: true,
    width: 150
  },
  // 汇率1(港币->发放币种)
  {
    editType: 'input',
    prop: 'hkdToPayoutRate',
    label: '港币->发放币种(汇率)',
    inputType: 'decimal',
    decimalDigits: 5,
    required: true,
    width: 150
  },

  {
    editType: 'input',
    prop: 'payoutAmount',
    label: '实际发放金额',
    inputType: 'decimal',
    required: true,
    width: 150
  },
  // 汇率2(保单币种->港币)入账检核汇率
  {
    editType: 'input',
    prop: 'exchangeRate',
    label: '保单币种->港币(入账检核汇率)',
    inputType: 'decimal',
    decimalDigits: 5,
    required: true,
    width: 150
    // defaultValue: 1
  },
  {
    editType: 'input',
    prop: 'ruleAmount',
    label: '保单币种金额',
    inputType: 'decimal',
    required: true,
    width: 150
  },

  {
    prop: 'payoutYearMonth',
    label: '出账年月（估）',
    editType: 'month',
    required: true,
    width: 150
  },
  {
    prop: 'remark',
    label: '备注',
    editType: 'input',
    inputType: 'textarea',
    required: false,
    width: 150
  }
  // {
  //   prop: 'userId',
  //   label: '负责人',
  //   editType: 'select',
  //   api: '/insurance/base/api/insuranceCompany/page', // 接口地址
  //   valueKey: 'insuranceCompanyBizId', // 选项 value 字段名
  //   labelKey: 'fullName', // 选项 label 字段名
  //   preload: true, // 初始化时自动加载
  //   requestParams: { pageNo: 1, pageSize: 20 }, // 固定参数
  //   // 远程搜索配置
  //   filterable: true,
  //   keywordField: 'keyword',
  //   debounceWait: 300
  // },
  // {
  //   prop: 'status',
  //   label: '状态',
  //   editType: 'select',
  //   dictType: 'sys_status', // 系统字典类型
  //   required: true
  // }
])
const settingBillTimeConfig = ref([
  {
    type: 'month',
    prop: 'actualPayoutDate',
    label: '出账年月(实)',
    placeholder: '出账年月(实)',
    rules: [{ required: true, message: '请选择出账年月(实)', trigger: 'blur' }]
  }
])
const rateExchangeConfig = [
  {
    type: 'select',
    prop: 'ruleCurrency',
    label: '保单币种',
    dictType: 'bx_currency_type',
    rules: [{ required: true, message: '必填项', trigger: 'blur' }]
  },
  {
    type: 'select',
    prop: 'originalCurrency',
    label: '原币种',
    dictType: 'bx_currency_type',
    rules: [{ required: true, message: '必填项', trigger: 'blur' }]
  },
  {
    type: 'select',
    prop: 'payoutCurrency',
    label: '发放币种',
    dictType: 'bx_currency_type',
    rules: [{ required: true, message: '必填项', trigger: 'blur' }]
  },
  {
    type: 'input',
    prop: 'originalAmount',
    label: '原币种金额',
    inputType: 'decimalNumber',
    rules: [{ required: true, message: '只能输入正整数和小数', trigger: 'blur' }]
  },
  // 汇率3(原币种->港币)
  {
    type: 'input',
    prop: 'originalToHkdRate',
    label: '原币种->港币(汇率)',
    inputType: 'decimal',
    decimalDigits: 5,
    rules: [{ required: true, message: '只能输入正整数和小数', trigger: 'blur' }]
    // defaultValue: 1
  },
  {
    type: 'input',
    prop: 'hkdAmount',
    label: '港币金额',
    inputType: 'decimal',
    rules: [{ required: true, message: '只能输入正整数和小数', trigger: 'blur' }]
  },
  // 汇率1(港币->发放币种)
  {
    type: 'input',
    prop: 'hkdToPayoutRate',
    label: '港币->发放币种(汇率)',
    inputType: 'decimal',
    decimalDigits: 5,
    rules: [{ required: true, message: '只能输入正整数和小数', trigger: 'blur' }]
    // defaultValue: 1
  },

  {
    type: 'input',
    prop: 'payoutAmount',
    label: '实际发放金额',
    inputType: 'decimal',
    rules: [{ required: true, message: '只能输入正整数和小数', trigger: 'blur' }]
  },
  //汇率2(保单币种->港币)入账检核汇率
  {
    type: 'input',
    prop: 'exchangeRate',
    label: '保单币种->港币(入账检核汇率)',
    inputType: 'decimal',
    decimalDigits: 5,
    rules: [{ required: true, message: '只能输入正整数和小数', trigger: 'blur' }]
    // defaultValue: 1
  },
  {
    type: 'input',
    prop: 'ruleAmount',
    label: '保单币种金额',
    inputType: 'decimal',
    rules: [{ required: true, message: '只能输入正整数和小数', trigger: 'blur' }]
  }
]

// 应收单类型
const fortuneBizTypeOptions = [
  { value: 'R', label: '关联保单应付单' },
  { value: 'U', label: '非关联保单应付单' }
]
// 可选性校验
const isSelectable = row => {
  // status 为 6 的行禁止勾选
  return row.status !== '6'
}
const confirmRateExchange = async () => {
  let formData = await rateExchangeFormRef.value.validate()
  formData.fortuneBizId = selectedRow.value.fortuneBizId
  try {
    const res = await editExchangeRateApi(formData)
    ElMessage.success('结算汇率修改成功')
    rateExchangeFlag.value = false
    const params = searchFormRef.value.getFormData()
    loadTableData(params)
  } catch (error) {
    ElMessage.error('结算汇率修改失败')
    rateExchangeFlag.value = true
    if (error.message && error.message.includes('Validation')) {
      ElMessage.error('必填项不能为空')
    }
  }
}
const handleInputChange = async (formType, prop, value, item) => {
  if (formType == 'rateExchange') {
    // 1.计算港币金额
    if (prop === 'originalToHkdRate' && value && rateExchangeForm.value.originalAmount) {
      // 计算港币金额   原币种金额*原币种->港币
      const originalAmount = rateExchangeForm.value.originalAmount
      const originalToHkdRate = value
      const hkdAmount = calculateAmount(originalAmount, originalToHkdRate, 2)
      await nextTick()
      rateExchangeForm.value.hkdAmount = hkdAmount
      const hkdToPayoutRate = rateExchangeForm.value.hkdToPayoutRate
      if (hkdToPayoutRate) {
        const payoutAmount = calculateAmount(hkdAmount, hkdToPayoutRate, 2)
        await nextTick()
        rateExchangeForm.value.payoutAmount = payoutAmount
      }
      const exchangeRate = rateExchangeForm.value.exchangeRate
      if (exchangeRate) {
        const ruleAmount = calculateAmount(hkdAmount, exchangeRate, 2, 'Divided')
        await nextTick()
        rateExchangeForm.value.ruleAmount = ruleAmount
      }
    } else if (prop === 'originalAmount' && value && rateExchangeForm.value.originalToHkdRate) {
      // 计算港币金额
      const originalAmount = value
      const originalToHkdRate = rateExchangeForm.value.originalToHkdRate
      const hkdAmount = calculateAmount(originalAmount, originalToHkdRate, 2)
      await nextTick()
      rateExchangeForm.value.hkdAmount = hkdAmount
      const hkdToPayoutRate = rateExchangeForm.value.hkdToPayoutRate
      if (hkdToPayoutRate) {
        const payoutAmount = calculateAmount(hkdAmount, hkdToPayoutRate, 2)
        await nextTick()
        rateExchangeForm.value.payoutAmount = payoutAmount
      }
      const exchangeRate = rateExchangeForm.value.exchangeRate
      if (exchangeRate) {
        const ruleAmount = calculateAmount(hkdAmount, exchangeRate, 2, 'Divided')

        await nextTick()
        rateExchangeForm.value.ruleAmount = ruleAmount
      }
    }
    //2.计算实际发放金额   港币金额*港币->发放币种汇率
    if (prop == 'hkdAmount' && value && rateExchangeForm.value.hkdToPayoutRate) {
      // 计算实际发放金额
      const hkdToPayoutRate = rateExchangeForm.value.hkdToPayoutRate
      const hkdAmount = value
      const payoutAmount = calculateAmount(hkdAmount, hkdToPayoutRate, 2)
      await nextTick()
      rateExchangeForm.value.payoutAmount = payoutAmount
    } else if (prop == 'hkdToPayoutRate' && value && rateExchangeForm.value.hkdAmount) {
      // 计算实际发放金额
      const hkdToPayoutRate = value
      const hkdAmount = rateExchangeForm.value.hkdAmount
      const payoutAmount = calculateAmount(hkdAmount, hkdToPayoutRate, 2)
      await nextTick()
      rateExchangeForm.value.payoutAmount = payoutAmount
    }

    //3.计算保单币种金额   港币金额*保单币种->港币汇率
    if (prop == 'hkdAmount' && value && rateExchangeForm.value.exchangeRate) {
      // 计算保单币种金额
      const exchangeRate = rateExchangeForm.value.exchangeRate
      const hkdAmount = value
      const ruleAmount = calculateAmount(hkdAmount, exchangeRate, 2, 'Divided')
      await nextTick()
      rateExchangeForm.value.ruleAmount = ruleAmount
    } else if (prop == 'exchangeRate' && value && rateExchangeForm.value.hkdAmount) {
      // 计算保单币种金额
      const exchangeRate = value
      const hkdAmount = rateExchangeForm.value.hkdAmount
      const ruleAmount = calculateAmount(hkdAmount, exchangeRate, 2, 'Divided')
      await nextTick()
      rateExchangeForm.value.ruleAmount = ruleAmount
    }
  } else if (formType == 'addCheckRecord') {
    await nextTick()
    let policyNo = addCheckRecordFormModel.value.policyNo
    let fortunePeriod = addCheckRecordFormModel.value.fortunePeriod
    if ((prop == 'policyNo' || prop == 'fortunePeriod') && fortunePeriod && policyNo) {
      //等待后端接口
      const res = await commissionExchangeRateApi({
        policyNo: policyNo,
        commissionPeriod: fortunePeriod
      })
      if (res.code == 200) {
        addCheckRecordFormModel.value.exchangeRate = res.data
      } else {
        ElMessage.error('查询结算汇率失败')
      }
    }
    // 1.计算港币金额
    if (prop === 'originalToHkdRate' && value && addCheckRecordFormModel.value.originalAmount) {
      // 计算港币金额   原币种金额*原币种->港币
      const originalAmount = addCheckRecordFormModel.value.originalAmount
      const originalToHkdRate = value
      const hkdAmount = calculateAmount(originalAmount, originalToHkdRate, 2)
      await nextTick()
      addCheckRecordFormModel.value.hkdAmount = hkdAmount

      const hkdToPayoutRate = addCheckRecordFormModel.value.hkdToPayoutRate
      if (hkdToPayoutRate) {
        const payoutAmount = calculateAmount(hkdAmount, hkdToPayoutRate, 2)
        await nextTick()
        addCheckRecordFormModel.value.payoutAmount = payoutAmount
      }
      const exchangeRate = addCheckRecordFormModel.value.exchangeRate
      if (exchangeRate) {
        const ruleAmount = calculateAmount(hkdAmount, exchangeRate, 2, 'Divided')
        await nextTick()
        addCheckRecordFormModel.value.ruleAmount = ruleAmount
      }
    } else if (
      prop === 'originalAmount' &&
      value &&
      addCheckRecordFormModel.value.originalToHkdRate
    ) {
      // 计算港币金额
      const originalAmount = value
      const originalToHkdRate = addCheckRecordFormModel.value.originalToHkdRate
      const hkdAmount = calculateAmount(originalAmount, originalToHkdRate, 2)
      console.log('新增', hkdAmount)
      await nextTick()
      addCheckRecordFormModel.value.hkdAmount = hkdAmount
      const hkdToPayoutRate = addCheckRecordFormModel.value.hkdToPayoutRate
      if (hkdToPayoutRate) {
        const payoutAmount = calculateAmount(hkdAmount, hkdToPayoutRate, 2)
        await nextTick()
        addCheckRecordFormModel.value.payoutAmount = payoutAmount
      }
      const exchangeRate = addCheckRecordFormModel.value.exchangeRate
      if (exchangeRate) {
        const ruleAmount = calculateAmount(hkdAmount, exchangeRate, 2, 'Divided')
        await nextTick()
        addCheckRecordFormModel.value.ruleAmount = ruleAmount
      }
    }
    //2.计算实际发放金额   港币金额*港币->发放币种汇率
    if (prop == 'hkdAmount' && value && addCheckRecordFormModel.value.hkdToPayoutRate) {
      // 计算实际发放金额
      const hkdToPayoutRate = addCheckRecordFormModel.value.hkdToPayoutRate
      const hkdAmount = value
      const payoutAmount = calculateAmount(hkdAmount, hkdToPayoutRate, 2)
      await nextTick()
      addCheckRecordFormModel.value.payoutAmount = payoutAmount
    } else if (prop == 'hkdToPayoutRate' && value && addCheckRecordFormModel.value.hkdAmount) {
      // 计算实际发放金额
      const hkdToPayoutRate = value
      const hkdAmount = addCheckRecordFormModel.value.hkdAmount
      const payoutAmount = calculateAmount(hkdAmount, hkdToPayoutRate, 2)
      await nextTick()
      addCheckRecordFormModel.value.payoutAmount = payoutAmount
    }

    //3.计算保单币种金额   港币金额*保单币种->港币汇率
    if (prop == 'hkdAmount' && value && addCheckRecordFormModel.value.exchangeRate) {
      // 计算保单币种金额
      const exchangeRate = addCheckRecordFormModel.value.exchangeRate
      const hkdAmount = value
      const ruleAmount = calculateAmount(hkdAmount, exchangeRate, 2, 'Divided')
      await nextTick()
      addCheckRecordFormModel.value.ruleAmount = ruleAmount
    } else if (prop == 'exchangeRate' && value && addCheckRecordFormModel.value.hkdAmount) {
      // 计算保单币种金额
      const exchangeRate = value
      const hkdAmount = addCheckRecordFormModel.value.hkdAmount
      const ruleAmount = calculateAmount(hkdAmount, exchangeRate, 2, 'Divided')
      await nextTick()
      addCheckRecordFormModel.value.ruleAmount = ruleAmount
    }
  }
}
// 精确乘法并保留小数位数
const multiply = (a, b, digits = 2, calculatedType) => {
  if (a == null || b == null) return null
  const numA = parseFloat(a)
  const numB = parseFloat(b)
  if (isNaN(numA) || isNaN(numB)) return null
  if (calculatedType && calculatedType == 'Divided') {
    return round(numA / numB, digits)
  }
  return round(numA * numB, digits)
}

const handleSplitCellChange = ({ row, col, newValue, oldValue, rowIndex, prop }) => {
  // 避免同一字段重复触发（如修改 chuAmount 会触发 hkdAmount 计算，该计算会再次触发 cell-change）

  const currentRow = splitTableData.value[rowIndex]
  if (!currentRow) return
  let needUpdate = false
  const updatedRow = { ...currentRow }
  // 联动规则1：计算原币种金额    应出账比例*应出账金额（HKD）
  if (prop === 'splitRatio' && selectedRow.value.originalAmount) {
    let ratio = prop === 'splitRatio' ? newValue : currentRow.splitRatio
    if (ratio) {
      ratio = ratio / 100
    }
    console.log('出账', selectedRow.value.originalAmount, ratio)

    const originalAmount = calculateAmount(
      selectedRow.value.originalAmount,
      ratio,
      spiltDigit.value
    )
    updatedRow.originalAmount = originalAmount
    // 原币种金额发生变化更新港币金额
    if (updatedRow.originalToHkdRate) {
      updatedRow.hkdAmount = calculateAmount(
        updatedRow.originalAmount,
        updatedRow.originalToHkdRate,
        spiltDigit.value
      )
    }
    //港币金额发生变化 更新实际发放金额
    if (updatedRow.hkdToPayoutRate && updatedRow.hkdAmount) {
      updatedRow.payoutAmount = calculateAmount(
        updatedRow.hkdAmount,
        updatedRow.hkdToPayoutRate,
        spiltDigit.value
      )
    }
    //港币金额发生变化 更新保单币种金额
    if (updatedRow.exchangeRate && updatedRow.hkdAmount) {
      updatedRow.ruleAmount = calculateAmount(
        updatedRow.hkdAmount,
        updatedRow.exchangeRate,
        spiltDigit.value,
        'Divided'
      )
    }
    needUpdate = true
  }

  // 联动规则2：原币种->港币 或 原币种金额 变化 → 重算 港币金额 = 原币种金额*原币种->港币
  if (prop === 'originalToHkdRate' || prop === 'originalAmount') {
    const originalToHkdRate = prop === 'originalToHkdRate' ? newValue : currentRow.originalToHkdRate
    const originalAmount = prop === 'originalAmount' ? newValue : currentRow.originalAmount
    const hkdAmount = calculateAmount(originalAmount, originalToHkdRate, spiltDigit.value)
    updatedRow.hkdAmount = hkdAmount
    //港币金额发生变化 更新实际发放金额
    if (updatedRow.hkdToPayoutRate && updatedRow.hkdAmount) {
      updatedRow.payoutAmount = calculateAmount(
        updatedRow.hkdAmount,
        updatedRow.hkdToPayoutRate,
        spiltDigit.value
      )
    }
    //港币金额发生变化 更新保单币种金额
    if (updatedRow.exchangeRate && updatedRow.hkdAmount) {
      updatedRow.ruleAmount = calculateAmount(
        updatedRow.hkdAmount,
        updatedRow.exchangeRate,
        spiltDigit.value,
        'Divided'
      )
    }
    needUpdate = true
  }
  // 联动规则3：港币->发放币种 或 港币金额 变化 → 重算 实际发放金额 = 港币金额*港币->发放币种汇率
  if (prop === 'hkdToPayoutRate' || prop === 'hkdAmount') {
    const hkdToPayoutRate = prop === 'hkdToPayoutRate' ? newValue : currentRow.hkdToPayoutRate
    const hkdAmount = prop === 'hkdAmount' ? newValue : currentRow.hkdAmount
    const payoutAmount = calculateAmount(hkdAmount, hkdToPayoutRate, spiltDigit.value)
    updatedRow.payoutAmount = payoutAmount
    needUpdate = true
  }
  // 联动规则4：保单币种->港币 或 港币金额 变化 → 重算 保单币种金额 = 港币金额/保单币种->港币汇率
  if (prop === 'exchangeRate' || prop === 'hkdAmount') {
    const exchangeRate = prop === 'exchangeRate' ? newValue : currentRow.exchangeRate
    const hkdAmount = prop === 'hkdAmount' ? newValue : currentRow.hkdAmount
    const ruleAmount = calculateAmount(hkdAmount, exchangeRate, spiltDigit.value, 'Divided')
    updatedRow.ruleAmount = ruleAmount
    needUpdate = true
  }

  // 如果用户手动修改了 hkdAmount，不做反向联动（符合需求）
  if (needUpdate) {
    // 更新表格数据（整体替换，触发视图更新）
    const newData = [...splitTableData.value]
    newData[rowIndex] = updatedRow
    splitTableData.value = newData
  }
}
const handleSpiltSubmit = async () => {
  // 调用组件的校验方法
  const isValid = await editTableRef.value.validateAndShow()

  if (isValid) {
    try {
      let params = {
        fortuneBizId: selectedRow.value.fortuneBizId,
        fortuneSplitDtoList: splitTableData.value
      }
      console.log('分期出账参数', params)
      const res = await billSplitApi(params)
      console.log('分期出账结果', res)
      installmentsBillFlag.value = false
      ElMessage.success('分期出账已保存')
      const searchParams = searchFormRef.value.getFormData()
      loadTableData(searchParams)
    } catch (error) {
      installmentsBillFlag.value = true
      console.log('分期出账错误', error)
      ElMessage.error('分期出账失败')
    }
  }
}
const handleSpiltDelete = row => {
  let index = splitTableData.value.findIndex(item => item.id == row.id)
  splitTableData.value.splice(index, 1)
}
// 生成临时唯一ID
let nextId = 1
const generateId = () => Date.now() + nextId++
// 添加出账
const addSpiltRecord = () => {
  if (splitTableData.value.length > 0) {
    let ratio = 0
    splitTableData.value.forEach(item => {
      ratio += Number(item.splitRatio)
    })
    console.log('比例', ratio)

    if (ratio > 100 || ratio == 100) {
      ElMessage.error('出账比例不能大于100%')
      return
    }
  }
  const newRow = {
    id: generateId(), // 必须有 rowIdKey 对应的字段（默认 'id'）
    payoutCurrency: 'HKD',
    ruleCurrency: selectedRow.value.ruleCurrency,
    originalCurrency: selectedRow.value.originalCurrency,
    hkdToPayoutRate: '1',
    exchangeRate: selectedRow.value.exchangeRate
  }
  if (selectedRow.value.originalCurrency && selectedRow.value.originalCurrency == 'HKD') {
    newRow.originalToHkdRate = '1'
  }
  // 插入到表格数据最前面
  splitTableData.value.push(newRow)
}
// 应付单类型通过value转成label
const getFortuneBizTypeLabel = value => {
  const item = fortuneBizTypeOptions.find(item => item.value === value)
  return item?.label || ''
}
// 新增出账检核
const addCheckRecordFormModel = ref({})
const addCheckRecordFormRef = ref(null)
const addCheckRecordFormDialogFlag = ref(false)
const addCheckRecordConfig = [
  {
    type: 'select',
    prop: 'fortuneBizType',
    label: '应付单类型',
    options: fortuneBizTypeOptions,
    rules: [{ required: true, message: '应付单类型必填', trigger: 'blur' }]
  },
  {
    type: 'select',
    prop: 'status',
    label: '出账状态',
    dictType: 'csf_expected_fortune_status',
    rules: [{ required: true, message: '出账状态必填', trigger: 'blur' }]
  },
  {
    type: 'input',
    prop: 'policyNo',
    label: '关联保单号',
    visible: formData => formData.fortuneBizType === 'R'
  },
  {
    type: 'input',
    prop: 'fortunePeriod',
    label: '佣金期数',
    inputType: 'decimal',
    visible: formData => formData.fortuneBizType === 'R',
    rules: [{ required: true, pattern: /^\d+$/, message: '只能输入正整数', trigger: 'blur' }]
  },
  {
    type: 'input',
    prop: 'fortuneTotalPeriod',
    label: '总期数',
    inputType: 'decimal',
    visible: formData => formData.fortuneBizType === 'R',
    rules: [{ pattern: /^\d+$/, message: '只能输入正整数', trigger: 'blur' }]
  },

  {
    type: 'month',
    prop: 'payoutDate',
    label: '出账月(估)',
    placeholder: '请选择',
    // maxDate: 'today',
    rules: [{ required: true, message: '出账月(估)必填', trigger: 'blur' }]
  },
  {
    type: 'month',
    prop: 'actualPayoutDate',
    label: '出账月(实)',
    placeholder: '请选择',
    maxDate: 'today',
    rules: [{ required: true, message: '出账月(实)必填', trigger: 'blur' }]
  },
  // {
  //   type: 'input',
  //   prop: 'amount',
  //   label: '出账金额',
  //   inputType: 'decimalNumber',
  //   decimalDigits: 4,
  //   rules: [{ pattern: /^-?\d+(\.\d+)?$/, message: '请输入有效的数字', trigger: 'blur' }]
  // },
  // {
  //   type: 'select',
  //   prop: 'currency',
  //   label: '出账币种',
  //   dictType: 'bx_currency_type'
  // },
  // {
  //   type: 'input',
  //   prop: 'fortuneName',
  //   label: '出账项目名称',
  //   rules: [{ required: true, message: '出账项目名称必填', trigger: 'blur' }]
  // },
  {
    type: 'select',
    prop: 'fortuneType',
    label: '出账项目类型',
    dictType: 'csf_fortune_type',
    rules: [{ required: true, message: '出账项目类型必填', trigger: 'blur' }],
    onChangeExtraFields: {
      fortuneName: 'itemLabel'
    }
  },
  {
    type: 'select',
    prop: 'brokerBizId',
    label: '转介人',
    api: '/insurance/base/api/userSaleExpand/page',
    keywordField: 'realName',
    requestParams: { pageNo: 1, pageSize: 200 },
    placeholder: '输入转介人名称搜索',
    debounceWait: 500, // 自定义防抖时间
    valueKey: 'clientUserBizId',
    labelKey: 'realName',
    onChangeExtraFields: {
      broker: 'realName', // 自动同步 raw.name 到 reconciliationCompany
      reconciliationCompanyCode: 'code'
      // team: 'deptName',
      // teamBizId: 'deptBizId'
    },
    transform: res => {
      return res?.data.records || []
    },
    rules: [{ required: true, message: '转介人必填', trigger: 'blur' }]
  },
  {
    type: 'select',
    prop: 'teamBizId',
    label: '所属团队',
    api: '/csf/api/team/page',
    keywordField: 'teamName',
    requestParams: { pageNo: 1, pageSize: 200 },
    placeholder: '输入所属团队名称搜索',
    debounceWait: 500, // 自定义防抖时间
    valueKey: 'teamBizId',
    labelKey: 'teamName',
    onChangeExtraFields: {
      // broker: 'realName', // 自动同步 raw.name 到 reconciliationCompany
      // reconciliationCompanyCode: 'code',
      team: 'teamName',
      teamBizId: 'teamBizId'
    },
    transform: res => {
      return res?.data.records || []
    }
    // rules: [{ required: true, message: '所属团队必填', trigger: 'blur' }]
  },

  {
    type: 'select',
    prop: 'ruleCurrency',
    label: '保单币种',
    dictType: 'bx_currency_type',
    rules: [{ required: true, message: '保单币种必填', trigger: 'blur' }]
  },
  {
    type: 'select',
    prop: 'originalCurrency',
    label: '原币种',
    dictType: 'bx_currency_type',
    rules: [{ required: true, message: '原币种必填', trigger: 'blur' }]
  },
  {
    type: 'select',
    prop: 'payoutCurrency',
    label: '发放币种',
    dictType: 'bx_currency_type',
    rules: [{ required: true, message: '发放币种必填', trigger: 'blur' }]
  },
  {
    type: 'input',
    prop: 'originalAmount',
    label: '原币种金额',
    inputType: 'decimalNumber',
    rules: [{ required: true, message: '只能输入正整数和小数', trigger: 'blur' }]
  },
  // 汇率3(原币种->港币)
  {
    type: 'input',
    prop: 'originalToHkdRate',
    label: '原币种->港币(汇率)',
    decimalDigits: 5,
    inputType: 'decimal',
    rules: [{ required: true, message: '只能输入正整数和小数', trigger: 'blur' }]
    // defaultValue: 1
  },
  {
    type: 'input',
    prop: 'hkdAmount',
    label: '港币金额',
    inputType: 'decimal',
    rules: [{ required: true, message: '只能输入正整数和小数', trigger: 'blur' }]
  },
  // 汇率1(港币->发放币种)
  {
    type: 'input',
    prop: 'hkdToPayoutRate',
    label: '港币->发放币种(汇率)',
    inputType: 'decimal',
    decimalDigits: 5,
    rules: [{ required: true, message: '只能输入正整数和小数', trigger: 'blur' }]
    // defaultValue: 1
  },

  {
    type: 'input',
    prop: 'payoutAmount',
    label: '实际发放金额',
    inputType: 'decimal',
    rules: [{ required: true, message: '只能输入正整数和小数', trigger: 'blur' }]
  },
  // 汇率2(保单币种->港币)入账检核汇率
  {
    type: 'input',
    prop: 'exchangeRate',
    label: '保单币种->港币(入账检核汇率)',
    inputType: 'decimal',
    decimalDigits: 5,
    rules: [{ required: true, message: '只能输入正整数和小数', trigger: 'blur' }]
    // defaultValue: 1
  },
  {
    type: 'input',
    prop: 'ruleAmount',
    label: '保单币种金额',
    inputType: 'decimal',
    rules: [{ required: true, message: '只能输入正整数和小数', trigger: 'blur' }]
  },
  {
    type: 'input',
    prop: 'remark',
    label: '备注'
  }
]

// 设置本期出账金额
const setPayoutAmountFormModel = ref({})
const setPayoutAmountFormRef = ref(null)
const setPayoutAmountDialogFlag = ref(false)
const setPayoutAmountConfig = [
  {
    type: 'input',
    prop: 'currentPaymentHkdAmount',
    label: '本期出账金额（HKD）',
    inputType: 'decimal',
    rules: [{ pattern: /^\d+$/, message: '只能输入正整数', trigger: 'blur' }]
  },
  // {
  //   type: 'select',
  //   prop: 'currency',
  //   label: '出账币种',
  //   dictType: 'bx_currency_type'
  // },
  {
    type: 'select',
    prop: 'status',
    label: '出账状态',
    dictType: 'csf_expected_fortune_status'
  }
  //  {
  //   type: 'input',
  //   prop: 'exchangeRate',
  //   label: '结算汇率',
  //   defaultValue: 1
  // }
]

// 统计信息
const statisticsData = ref({})
// 弹窗相关
const dialogFlag = ref(false)

// 按钮事件处理
const handleAdd = () => {
  addCheckRecordFormModel.value = {}
  addCheckRecordFormDialogFlag.value = true
}
const handleImport = () => {
  importCheckRecordFlag.value = true
}
const handleExport = () => {
  ElMessage.info('点击导出按钮')
}
const handleReset = () => {
  // 重置搜索表单
  searchFormRef.value.resetForm()
  loadTableData()
  console.log('表单已重置')
}
const handleQuery = async () => {
  currentPage.value = 1
  const params = searchFormRef.value.getFormData()
  loadTableData(params)
}
const visibleDefaultButtons = ref(['add', 'export', '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,
      payoutDateStart: searchParams.payoutDate?.[0] || undefined,
      payoutDateEnd: searchParams.payoutDate?.[1] || undefined,
      actualPayoutDateStart: searchParams.actualPayoutDate?.[0] || undefined,
      actualPayoutDateEnd: searchParams.actualPayoutDate?.[1] || undefined,
      actualPayoutDate: undefined,
      payoutDate: undefined
    }
    const res = await getPolicyFortuneList(params)
    tableData.value = res.data.page.records || []
    pageTotal.value = res.data.page.total || 0
    pageSize.value = res.data.page.size || 0
    // 统计信息
    statisticsData.value = oldStaticData.value = res.data.statisticsVO || {}
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error(error.message || '加载数据失败')
  } finally {
    loading.value = false
  }
}
loadTableData()
// 分页事件
const handleSizeChange = val => {
  pageSize.value = val
  const params = searchFormRef.value.getFormData()
  loadTableData(params)
}
const handleCurrentChange = val => {
  currentPage.value = val
  const params = searchFormRef.value.getFormData()
  loadTableData(params)
}
// 表格数据
const tableData = ref([])

const handleSelect = (e, row) => {
  console.log('选中行:', e, row)
  selectedRow.value = row
  if (e === 'setPayRoll') {
    setPayoutAmountDialogFlag.value = true
  } else if (e == 'billInstallments') {
    splitTableData.value = []
    installmentsBillFlag.value = true
  } else if (e == 'settingBillYearMonth') {
    billTimeType.value = 'single'
    settingBillTimeForm.value = {}
    settingBillYearMonthFlag.value = true
  } else if (e == 'editExchangeRate') {
    rateExchangeForm.value = {
      ...row,
      originalAmount: row.originalAmount ? Number(row.originalAmount).toFixed(2) : '',
      ruleCurrency: row.ruleCurrency,
      originalCurrency: row.originalCurrency,
      payoutCurrency: row.payoutCurrency,
      // hkdToPayoutRate: '',
      exchangeRate: row.exchangeRate ? row.exchangeRate : '',
      // originalToHkdRate: '',
      payoutAmount: row.payoutAmount ? Number(row.payoutAmount).toFixed(2) : '',
      ruleAmount: row.ruleAmount ? Number(row.ruleAmount).toFixed(2) : '',
      hkdAmount: row.hkdAmount ? Number(row.hkdAmount).toFixed(2) : ''
    }
    rateExchangeFlag.value = true
  }
}
const addCheckRecordaddBatchapi = async data => {
  let formData = await addCheckRecordFormRef.value.validate()
  // const formData = addCheckRecordFormRef.value.getFormData()
  console.log('新增出账检核记录:', formData)
  // return
  const params = [{ ...formData }]
  try {
    const res = await addCheckRecordaddBatch(params)
    if (res.code === 200) {
      ElMessage.success('新增出账检核记录成功')
      addCheckRecordFormDialogFlag.value = false
      addCheckRecordFormRef.value.resetForm()
      loadTableData()
    } else {
      ElMessage.error(res.msg || '新增出账检核记录失败')
    }
  } catch (error) {
    console.error('新增出账检核记录失败:', error)
    ElMessage.error(error.message || '新增出账检核记录失败')
  }
}

// 设置本期出账金额
const updatePayoutAmountapi = async data => {
  console.log('设置本期出账金额:', data)
  const params = {
    ...setPayoutAmountFormRef.value.getFormData(),
    fortuneBizId: selectedRow.value.fortuneBizId
  }
  try {
    const res = await updatePayoutAmount(params)
    if (res.code === 200) {
      ElMessage.success('设置本期出账金额成功')
      loadTableData()
      setPayoutAmountDialogFlag.value = false
    } else {
      ElMessage.error(res.msg || '设置本期出账金额失败')
    }
  } catch (error) {
    console.error('设置本期出账金额失败:', error)
    ElMessage.error(error.message || '设置本期出账金额失败')
  }
}
const updatePayRollStatusDisable = ref(true)
const multipleSelection = ref([])
// 获取统计
const getStaticData = async data => {
  try {
    const res = await statisticsFortune(data)
    console.log('====================================')
    console.log('统计数据', res)
    console.log('====================================')
    if (res.code === 200) {
      statisticsData.value = res.data || {}
    } else {
      ElMessage.error(res.msg || '获取统计数据失败')
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
    ElMessage.error(error.message || '获取统计数据失败')
  }
}
const handleSelectionChange = val => {
  let fortuneIdList = val.map(item => item.id) || []
  if (fortuneIdList.length > 0) {
    getStaticData({ fortuneIdList })
  } else {
    statisticsData.value = JSON.parse(JSON.stringify(oldStaticData.value))
  }

  multipleSelection.value = val
  console.log('全选:', val)
  // 完成检核按钮是否禁用
  updatePayRollStatusDisable.value = val.length === 0
}
const submitSettingBillYearMonth = async () => {
  if (billTimeType.value == 'multiple') {
    //等后端接口
    try {
      const res = await batchActualPayoutDate({
        fortuneBizIdList: multipleSelection.value.map(item => item.fortuneBizId),
        actualPayoutDate: settingBillTimeForm.value.actualPayoutDate
      })
      if (res.code === 200) {
        settingBillYearMonthFlag.value = false
        ElMessage.success(res.data)
        const params = await searchFormRef.value.getFormData()
        loadTableData(params)
      }
    } catch (error) {
      console.error('检核失败:', error)
      settingBillYearMonthFlag.value = true
      ElMessage.error(error.response?.data?.msg || '检核失败')
    }
  } else if (billTimeType.value == 'single') {
    const params = {
      fortuneBizId: selectedRow.value.fortuneBizId,
      actualPayoutDate: settingBillTimeForm.value.actualPayoutDate
    }
    try {
      const singleRes = await actualPayoutDateApi(params)
      ElMessage.success('设置出账年月成功')
      settingBillYearMonthFlag.value = false
      const searchParams = await searchFormRef.value.getFormData()
      loadTableData(searchParams)
    } catch (error) {
      ElMessage.error('设置出账年月失败')
      settingBillYearMonthFlag.value = true
    }
  }
}
const batchSettingBillYearMonth = () => {
  settingBillYearMonthFlag.value = true
  settingBillTimeForm.value = {}
  billTimeType.value = 'multiple'
}
const downloadPolicyFortuneAccountapi = async data => {
  console.log('生成出账清单:', data)

  try {
    const res = await downloadPolicyFortuneAccount({
      fortuneBizIdList: multipleSelection.value.map(item => item.fortuneBizId)
    })
    if (res.code === 200) {
      ElMessage.success('完成检核，等待关账')
      const searchParams = await searchFormRef.value.getFormData()
      loadTableData(searchParams)
    }
  } catch (error) {
    console.error('检核失败:', error)
    ElMessage.error(error.response?.data?.msg || '检核失败')
  }
}
import FileUploadPreview from '@/components/fileUploadPreview/fileUploadPreview.vue'

const importCheckRecordFlag = ref(false)
// 如果后端接收的就是当前格式，可直接透传
const formatForBackend = rows => {
  return rows.map(row => ({
    ...row,
    amount: Number(row.amount) || 0,
    exchangeRate: Number(row.exchangeRate) || 1
  }))
}

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

onMounted(async () => {})
// 数据变化时清空选中
watch(
  () => tableData,
  () => {
    nextTick(() => {
      multipleTableRef.value?.clearSelection()
      multipleSelection.value = []
    })
  },
  { deep: true }
)
</script>

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