<template>
  <div>
    <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>
        <!-- 统计信息卡片 -->
        <div class="statistics-container" v-if="statisticsData.totalPolicyCount > 0">
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :md="4" class="text-center mb-4">
              <el-statistic
                title="应出账总金额"
                :value="statisticsData.totalExpectedAmount"
                :formatter="value => formatCurrency(value)"
              />
            </el-col>
            <el-col :xs="24" :sm="12" :md="4" class="text-center mb-4">
              <el-statistic
                title="已出账金额"
                :value="statisticsData.totalPaidAmount"
                :formatter="value => formatCurrency(value)"
              />
            </el-col>
            <el-col :xs="24" :sm="12" :md="4" class="text-center mb-4">
              <el-statistic
                title="待出账金额"
                :value="statisticsData.totalUnpaidAmount"
                :formatter="value => formatCurrency(value)"
              />
            </el-col>
            <el-col :xs="24" :sm="12" :md="4" class="text-center mb-4">
              <el-statistic
                title="已出账比例"
                :value="statisticsData.paidAmountRatio"
                :formatter="value => formatCurrency(value, '', 2) + '%'"
              />
            </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="总保费"
                :value="statisticsData.totalPremiumAmount"
                :formatter="value => formatCurrency(value)"
              />
            </el-col>
          </el-row>
        </div>
        <!-- 应付款管理列表 -->
        <el-table
          :data="tableData"
          height="400"
          border
          highlight-current-row
          style="width: 100%"
          v-loading="loading"
        >
          <el-table-column
            v-for="(column, index) in payableReportTableColumns"
            :key="index"
            :prop="column.prop"
            :label="column.label"
            :width="column.width"
            :sortable="column.sortable"
            :formatter="column.formatter"
          />
          <el-table-column fixed="right" label="操作" min-width="120">
            <template #default="scope">
              <el-button link type="primary" size="small" @click="viewDetail(scope.row)">
                查看明细
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>
    </CommonPage>
    <!-- 查看明细列表 -->
    <CommonDialog
      dialogTitle="应付明细"
      dialogWidth="80%"
      :openDialog="detailDialogVisible"
      :showAction="true"
      :showClose="true"
      @close="detailDialogVisible = false"
      @confirm="detailDialogVisible = false"
    >
      <div class="statistics-container" v-if="detailRecordStatistics.totalPolicyCount > 0">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="4" class="text-center mb-4">
            <el-statistic
              title="应出账总金额"
              :value="detailRecordStatistics.totalExpectedAmount"
              :formatter="value => formatCurrency(value)"
            />
          </el-col>
          <el-col :xs="24" :sm="12" :md="4" class="text-center mb-4">
            <el-statistic
              title="已出账金额"
              :value="detailRecordStatistics.totalPaidAmount"
              :formatter="value => formatCurrency(value)"
            />
          </el-col>
          <el-col :xs="24" :sm="12" :md="4" class="text-center mb-4">
            <el-statistic
              title="待出账金额"
              :value="detailRecordStatistics.totalUnpaidAmount"
              :formatter="value => formatCurrency(value)"
            />
          </el-col>
          <el-col :xs="24" :sm="12" :md="4" class="text-center mb-4">
            <el-statistic
              title="已出账比例"
              :value="detailRecordStatistics.paidAmountRatio"
              :formatter="value => formatCurrency(value, '', 2) + '%'"
            />
          </el-col>
          <el-col :xs="24" :sm="12" :md="4" class="text-center mb-4">
            <el-statistic title="总保单数" :value="detailRecordStatistics.totalPolicyCount" />
          </el-col>
          <el-col :xs="24" :sm="12" :md="4" class="text-center mb-4">
            <el-statistic
              title="总保费"
              :value="detailRecordStatistics.totalPremiumAmount"
              :formatter="value => formatCurrency(value)"
            />
          </el-col>
        </el-row>
      </div>
      <el-table
        :data="payableReportTableData"
        border
        style="width: 100%; margin-bottom: 10px"
        :row-class-name="getRowClassName"
      >
        <el-table-column
          v-for="item in payableReportListTableColumns"
          :key="item.property"
          :property="item.property"
          :label="item.label"
          :width="item.width"
          :formatter="item.formatter"
        />
        <el-table-column fixed="right" label="操作" min-width="120">
          <template #default="{ row }">
            <el-popover placement="right" :width="200" trigger="click" v-if="row.type == '1'">
              <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>
      <el-pagination
        v-model:current-page="detailPageInfo.currentPage"
        v-model:page-size="detailPageInfo.pageSize"
        :page-sizes="[50, 100, 200, 300]"
        size="default"
        layout="total, sizes, prev, pager, next, jumper"
        :total="detailPageInfo.total"
        @size-change="handleSizeChangeDetailRecord"
        @current-change="handleCurrentChangeDetailRecord"
      />
    </CommonDialog>
    <!-- 出账记录表格弹窗-->
    <CommonDialog
      dialogTitle="出账记录"
      dialogWidth="80%"
      :openDialog="payRecordDialogTableVisible"
      :showAction="true"
      :showClose="true"
      @close="payRecordDialogTableVisible = false"
      @confirm="payRecordDialogTableVisible = false"
    >
      <el-table :data="payRecordDialogTableData" border style="width: 100%">
        <el-table-column
          v-for="item in payRecordDialogTableColumns"
          :key="item.property"
          :property="item.property"
          :label="item.label"
          :width="item.width"
          :formatter="item.formatter"
        />
      </el-table>
    </CommonDialog>
    <!-- 新增出账记录 -->
    <CommonDialog
      :dialogTitle="editStatus === 'add' ? '新增出账记录' : '修改出账记录'"
      dialogWidth="80%"
      :openDialog="addPayRecordDialogVisible"
      :showAction="true"
      :showClose="true"
      @close="resetAddPayRecordForm"
      @confirm="handleConfirmAddPayRecord"
    >
      <SearchForm
        ref="addPayRecordFormRef"
        :config="addPayRecordFormConfig"
        v-model="addPayRecordFormModel"
        @inputChange="(prop, value, item) => handleInputChange('addPayRecord', prop, value, item)"
      />
    </CommonDialog>
    <!-- 修改出账记录 -->
    <CommonDialog
      dialogTitle="修改出账记录"
      dialogWidth="80%"
      :openDialog="updatePayRecordDialogVisible"
      :showAction="true"
      :showClose="true"
      @close="updatePayRecordDialogVisible = false"
      @confirm="handleConfirmUpdatePayRecord"
    >
      <SearchForm
        ref="updatePayRecordFormRef"
        :config="updatePayRecordFormConfig"
        v-model="updatePayRecordFormModel"
        @inputChange="
          (prop, value, item) => handleInputChange('updatePayRecord', prop, value, item)
        "
      />
    </CommonDialog>
    <!-- 设置出账状态 -->
    <CommonDialog
      dialogTitle="设置出账状态"
      dialogWidth="80%"
      :openDialog="setPayRecordStatusDialogVisible"
      :showAction="true"
      :showClose="true"
      @close="setPayRecordStatusDialogVisible = false"
      @confirm="handleConfirmSetPayRecordStatus"
    >
      <SearchForm ref="setPayRecordStatusFormRef" :config="setPayRecordStatusFormConfig" />
    </CommonDialog>
  </div>
</template>

<script setup name="Payables">
import CommonPage from '@/components/commonPage'
import { ref, reactive, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { formatCurrency, calculateAmount, formatNumberToMaxDigits } from '@/utils/number'
import {
  expectedFortuneList,
  payRecordList,
  addPayRecord,
  updatePayRecord,
  exportPayRecord,
  payableReport,
  commissionExchangeRateApi
} from '@/api/financial/commission'
import SearchForm from '@/components/SearchForm/SearchForm.vue'
import CommonDialog from '@/components/commonDialog'
import { loadDicts, getDictLabel } from '@/utils/useDict'
import useUserStore from '@/store/modules/user'
import { safeDownload } from '@/utils/safeDownload'
const updatePayRecordFormModel = ref({})
const updatePayRecordFormRef = ref(null)
const updatePayRecordDialogVisible = ref(false)
const payableReportTableData = ref([])
const payableReportTableColumns = ref([
  {
    prop: 'policyNo',
    label: '保单号',
    sortable: true,
    width: '150',
    formatter: row => row.policyNo || '-'
  },
  {
    prop: 'policyHolder',
    label: '投保人',
    sortable: true,
    width: '120',
    formatter: row => row.policyHolder || '-'
  },
  {
    prop: 'broker',
    label: '转介人(主)',
    sortable: true,
    width: '150',
    formatter: row => row.broker || '-'
  },
  {
    prop: 'brokerGradeName',
    label: '职级',
    sortable: true,
    width: '80',
    formatter: row => row.brokerGradeName || '-'
  },
  {
    prop: 'fortunePeriod',
    label: '出账期数',
    sortable: true,
    width: '120',
    formatter: row => row.fortunePeriod || '-'
  },
  {
    prop: 'fortuneTotalPeriod',
    label: '出账总期数',
    sortable: true,
    width: '120',
    formatter: row => row.fortuneTotalPeriod || '-'
  },
  { prop: 'payoutDate', label: '出账年月（估）', sortable: true, width: '130' },
  {
    prop: 'paidRatio',
    label: '已出账比例',
    sortable: true,
    width: '120',
    formatter: row => (row.paidRatio || 0) + '%' || '-'
  },
  {
    prop: 'unpaidRatio',
    label: '待出账比例',
    sortable: true,
    width: '120',
    formatter: row => (row.unpaidRatio || 0) + '%' || '-'
  },
  {
    prop: 'paidAmount',
    label: '已出账金额',
    sortable: true,
    width: '120',
    formatter: row => formatCurrency(row.paidAmount || 0)
  },
  {
    prop: 'unpaidAmount',
    label: '待出账金额',
    sortable: true,
    width: '120',
    formatter: row => formatCurrency(row.unpaidAmount || 0)
  },
  {
    prop: 'hkdAmount',
    label: '应出账金额（估）',
    sortable: true,
    width: '120',
    formatter: row => formatCurrency(row.hkdAmount || 0)
  },
  {
    prop: 'currency',
    label: '出账币种',
    sortable: true,
    width: '120',
    formatter: row => row.currency || '-'
  },
  {
    prop: 'premium',
    label: '期交保费',
    sortable: true,
    width: '120',
    formatter: row => formatCurrency(row.premium || 0)
  },
  {
    prop: 'insuranceCompany',
    label: '保险公司',
    sortable: true,
    width: '120',
    formatter: row => row.insuranceCompany || '-'
  },
  {
    prop: 'productName',
    label: '产品计划',
    sortable: true,
    width: '120',
    formatter: row => row.productName || '-'
  },
  {
    prop: 'policyCurrency',
    label: '保单币种',
    sortable: true,
    width: '120',
    formatter: row => row.policyCurrency || '-'
  }
])
const detailDialogVisible = ref(false)

// 应付明细列表
const payableReportListTableColumns = ref([
  // { prop: 'fortuneBizType', label: '应付款类型', sortable: true, width: '120', formatter: (row) => getFortuneBizTypeLabel(row.fortuneBizType) || '-' },
  // { prop: 'payableNo', label: '应付账款编号', sortable: true, width: '120', formatter: (row) => row.payableNo || '-' },
  {
    prop: 'type',
    label: '是否实际出账',
    sortable: true,
    width: '80',
    formatter: row => getTypeLabel(row.type) || '-'
  },

  {
    prop: 'payableNo',
    label: '业务编号',
    sortable: true,
    width: '130',
    formatter: row => row.payableNo || '-'
  },
  // {
  //   prop: 'policyNo',
  //   label: '关联业务编号',
  //   sortable: true,
  //   width: '130',
  //   formatter: row => row.policyNo || '-'
  // },
  {
    prop: 'policyNo',
    label: '保单号',
    sortable: true,
    width: '130',
    formatter: row => row.policyNo || '-'
  },
  {
    prop: 'broker',
    label: '转介人',
    sortable: true,
    width: '120',
    formatter: row => row.broker || '-'
  },
  {
    prop: 'brokerGradeName',
    label: '职级',
    sortable: true,
    width: '120',
    formatter: row => row.brokerGradeName || '-'
  },
  {
    prop: 'fortuneName',
    label: '出账项目',
    sortable: true,
    width: '120',
    formatter: row => row.fortuneName || '-'
  },
  {
    prop: 'status',
    label: '出账状态',
    sortable: true,
    width: '120',
    formatter: row => getDictLabel('csf_expected_fortune_status', row.status) || '-'
  },
  {
    prop: 'payoutCurrency',
    label: '出账币种',
    sortable: true,
    width: '100',
    formatter: row => row.payoutCurrency || '-'
  },
  {
    prop: 'fortunePeriod',
    label: '出账期数',
    sortable: true,
    width: '100',
    formatter: row => row.fortunePeriod || '-'
  },
  {
    prop: 'fortuneTotalPeriod',
    label: '出账总期数',
    sortable: true,
    width: '100',
    formatter: row => row.fortuneTotalPeriod || '-'
  },
  {
    prop: 'payoutDate',
    label: '出账年月（估）',
    sortable: true,
    width: '120',
    formatter: row => row.payoutDate || '-'
  },

  {
    prop: 'actualPayoutDate',
    label: '出账年月（实）',
    sortable: true,
    width: '120',
    formatter: row => row.actualPayoutDate || '-'
  },
  {
    prop: 'paidRatio',
    label: '已出账比例',
    sortable: true,
    width: '120',
    formatter: row => (row.paidRatio || 0) + '%' || '-'
  },
  {
    prop: 'unpaidRatio',
    label: '待出账比例',
    sortable: true,
    width: '120',
    formatter: row => (row.unpaidRatio || 0) + '%' || '-'
  },
  // { prop: 'commissionRatio', label: '职级对应积分比例', sortable: true, width: '120', formatter: (row) => (row.commissionRatio || 0)  || '-' },
  {
    prop: 'hkdAmount',
    label: 'HKD应出账金额',
    sortable: true,
    width: '120',
    formatter: row => formatCurrency(row.hkdAmount || 0)
  },
  // {
  //   prop: 'exchangeRate',
  //   label: '保单币种->HKD(汇率)',
  //   sortable: true,
  //   width: '140',
  //   formatter: row => formatCurrency(row.exchangeRate || 0, '', 5)
  // },
  {
    prop: 'exchangeRate',
    label: '保单币种->HKD(汇率)',
    sortable: true,
    width: '140',
    formatter: row => formatNumberToMaxDigits(row.exchangeRate, 5, '-')
  },

  {
    prop: 'paidAmount',
    label: '已出账金额(HKD)',
    sortable: true,
    width: '120',
    formatter: row => formatCurrency(row.paidAmount || 0)
  },

  {
    prop: 'unpaidAmount',
    label: '待出账金额(估)',
    sortable: true,
    width: '120',
    formatter: row => formatCurrency(row.unpaidAmount || 0)
  },
  {
    prop: 'currentPaymentHkdAmount',
    label: '本期待出账金额',
    sortable: true,
    width: '120',
    formatter: row => formatCurrency(row.currentPaymentHkdAmount || 0)
  },
  {
    prop: 'exchangeRate',
    label: '本期结算汇率(实)',
    sortable: true,
    width: '120',
    formatter: row => formatNumberToMaxDigits(row.exchangeRate, 5, '-')
  },
  {
    prop: 'brokerRatio',
    label: '持有比例',
    sortable: true,
    width: '100',
    formatter: row => (row.brokerRatio || 0) + '%' || '-'
  },
  {
    prop: 'premium',
    label: '期交保费',
    sortable: true,
    width: '120',
    formatter: row => formatCurrency(row.premium || 0)
  },
  {
    prop: 'insuranceCompany',
    label: '保险公司',
    sortable: true,
    width: '120',
    formatter: row => row.insuranceCompany || '-'
  },
  {
    prop: 'productName',
    label: '产品计划',
    sortable: true,
    width: '120',
    formatter: row => row.productName || '-'
  },
  {
    prop: 'remark',
    label: '备注',
    sortable: true,
    width: '120',
    formatter: row => row.remark || '-'
  },
  // {
  //   prop: 'statusDesc',
  //   label: '修改理由',
  //   sortable: true,
  //   width: '120',
  //   formatter: row => row.statusDesc || '-'
  // },
  {
    prop: 'creatorName',
    label: '创建人',
    sortable: true,
    width: '120',
    formatter: row => row.creatorName || '-'
  },
  {
    prop: 'createTime',
    label: '创建时间',
    sortable: true,
    width: '180',
    formatter: row => row.createTime || '-'
  }
])

// 设置出账状态
const setPayRecordStatusDialogVisible = ref(false)
const selectedRow = ref(null)
const setPayRecordStatusFormRef = ref(null)
const setPayRecordStatusFormConfig = ref([
  {
    type: 'select',
    prop: 'status',
    label: '出账状态',
    dictType: 'csf_expected_fortune_status'
  },
  {
    type: 'textarea',
    prop: 'statusDesc',
    label: '修改理由'
  }
])
const visibleDefaultButtons = ref(['add', 'export', 'reset', 'query'])
const userStore = useUserStore()
// 应收单类型
const fortuneBizTypeOptions = [
  { value: 'R', label: '关联保单应付单' },
  { value: 'U', label: '非关联保单应付单' }
]
// 应付单类型通过value转成label
const getFortuneBizTypeLabel = value => {
  const item = fortuneBizTypeOptions.find(item => item.value === value)
  return item?.label || ''
}
const searchFormRef = ref(null)
const searchParams = ref({})
const searchConfig = ref([
  {
    type: 'input',
    prop: 'policyNo',
    label: '保单号'
  },
  {
    type: 'input',
    prop: 'policyHolder',
    label: '投保人'
  },
  {
    type: 'select',
    prop: 'brokerBizIdList',
    label: '转介人',
    api: '/insurance/base/api/userSaleExpand/page',
    keywordField: 'realName',
    requestParams: { pageNo: 1, pageSize: 20 },
    placeholder: '输入转介人名称搜索',
    debounceWait: 500, // 自定义防抖时间
    valueKey: 'clientUserBizId',
    labelKey: 'realName',
    multiple: true,
    transform: res => {
      return res?.data.records || []
    }
  },
  {
    type: 'monthrange',
    prop: 'payoutDate',
    label: '出账月（估）',
    startPlaceholder: '开始时间',
    endPlaceholder: '结束时间'
  },
  {
    type: 'select',
    prop: 'statusList',
    label: '出账状态',
    multiple: true,
    dictType: 'csf_expected_fortune_status'
  },
  {
    type: 'input',
    prop: 'fortunePeriod',
    label: '出账期数',
    inputType: 'decimal',
    rules: [{ pattern: /^\d+$/, message: '只能输入正整数', trigger: 'blur' }]
  },
  {
    type: 'select',
    prop: 'fortuneType',
    label: '出账项目',
    dictType: 'csf_fortune_type'
  },
  {
    type: 'select',
    prop: 'insuranceCompanyBizIdList',
    label: '保险公司',
    api: '/insurance/base/api/insuranceCompany/page',
    keywordField: 'queryContent',
    requestParams: { pageNo: 1, pageSize: 20 },
    placeholder: '输入保险公司名称搜索',
    debounceWait: 500, // 自定义防抖时间
    valueKey: 'insuranceCompanyBizId',
    labelKey: 'fullName',
    multiple: true,
    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, // 自定义防抖时间
    valueKey: 'productLaunchBizId',
    labelKey: 'productName',
    multiple: true,
    transform: res => {
      return res?.data.records || []
    }
  },
  {
    type: 'select',
    prop: 'fortuneBizType',
    label: '应付单类型',
    options: [
      { value: 'R', label: '关联保单应付单' },
      { value: 'U', label: '非关联保单应付单' }
    ]
  },
  {
    type: 'select',
    prop: 'teamBizIdList',
    label: '出单团队',
    api: '/csf/api/team/page',
    keywordField: 'teamName',
    requestParams: { pageNo: 1, pageSize: 20 },
    placeholder: '输入出单团队名称搜索',
    debounceWait: 500, // 自定义防抖时间
    multiple: true,
    valueKey: 'teamBizId',
    labelKey: 'teamName',
    transform: res => {
      return res?.data.records || []
    }
  }
])

const payRecordDialogTableVisible = ref(false)
// 新增出账记录
const addPayRecordFormModel = ref({
  fortuneBizType: 'R'
})
const addPayRecordDialogVisible = ref(false)
const addPayRecordFormRef = ref()
const updatePayRecordFormConfig = [
  {
    type: 'select',
    prop: 'fortuneBizType',
    label: '应付单类型',
    options: [
      { value: 'R', label: '关联保单应付单' },
      { value: 'U', label: '非关联保单应付单' }
    ]
  },
  {
    type: 'input',
    prop: 'policyNo',
    label: '关联保单号',
    visible: formData => formData.fortuneBizType === 'R',
    rules: [{ required: true, message: '关联保单号必填', trigger: 'blur' }]
  },
  {
    type: 'month',
    prop: 'payoutDate',
    label: '出账月（估）',
    placeholder: '请选择'
  },
  {
    type: 'month',
    prop: 'actualPayoutDate',
    label: '出账月（实）',
    placeholder: '请选择',
    maxDate: 'today'
  },
  // {
  //   type: 'input',
  //   prop: 'fortuneName',
  //   label: '出账项目'
  // },
  {
    type: 'select',
    prop: 'fortuneType',
    label: '出账项目类型',
    dictType: 'csf_fortune_type',
    onChangeExtraFields: {
      fortuneName: 'itemLabel'
    }
  },
  {
    type: 'input',
    prop: 'fortunePeriod',
    label: '佣金期数',
    inputType: 'decimal',
    visible: formData => formData.fortuneBizType === 'R'
    // rules: [{ pattern: /^\d+$/, message: '只能输入正整数', trigger: 'blur' }]
  },
  {
    type: 'input',
    prop: 'fortuneTotalPeriod',
    label: '总期数',
    inputType: 'decimal',
    visible: formData => formData.fortuneBizType === 'R'
    // rules: [{ pattern: /^\d+$/, message: '只能输入正整数', trigger: 'blur' }]
  },
  {
    type: 'select',
    prop: 'currency',
    label: '出账币种',
    dictType: 'bx_currency_type',
    defaultValue: 'HKD'
  },
  {
    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'
    },
    transform: res => {
      return res?.data.records || []
    }
  },
  {
    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: false, 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: 'decimal',
    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' }]
  },
  {
    type: 'input',
    prop: 'remark',
    label: '备注'
  }

  // {
  //   type: 'input',
  //   prop: 'hkdAmount',
  //   label: '出账金额',
  //   rules: [
  //      { required: true, message: '请输入', trigger: 'blur' },
  //     { pattern: /^-?\d+(\.\d{1,2})?$/, message: '小数（最多两位）', trigger: 'blur' }
  //   ]
  // },

  //  {
  //   type: 'input',
  //   prop: 'defaultExchangeRate',
  //   label: '结算汇率（入账检核时的汇率）',
  //   rules: [
  //     { required: true, message: '请输入', trigger: 'blur' },
  //     { pattern: /^-?\d+(\.\d{1,6})?$/, message: '小数（最多6位）', trigger: 'blur' }
  //   ]
  // },

  // {
  //   type: 'select',
  //   prop: 'status',
  //   label: '出账状态',
  //   dictType: 'csf_expected_fortune_status'
  // },
  // {
  //   type: 'input',
  //   prop: 'exchangeRate',
  //   label: '结算汇率',
  //   inputType: 'decimal',
  //   rules: [{ required: true, message: '只能输入正整数和小数', trigger: 'blur' }]
  //   // defaultValue: 1
  // },
  // {
  //   type: 'input',
  //   prop: 'remark',
  //   label: '备注'
  // }
]
// const addPayRecordFormConfig = [
//   {
//     type: 'select',
//     prop: 'fortuneBizType',
//     label: '应付单类型',
//     options: [
//       { value: 'R', label: '关联保单应付单' },
//       { value: 'U', label: '非关联保单应付单' }
//     ]
//   },
//   {
//     type: 'input',
//     prop: 'policyNo',
//     label: '关联保单号',
//     visible: formData => formData.fortuneBizType === 'R'
//   },
//   {
//     type: 'input',
//     prop: 'fortunePeriod',
//     label: '佣金期数',
//     inputType: 'decimal',
//     visible: formData => formData.fortuneBizType === 'R',
//     rules: [{ pattern: /^\d+$/, message: '只能输入正整数', trigger: 'blur' }]
//   },
//   {
//     type: 'input',
//     prop: 'fortuneTotalPeriod',
//     label: '总期数',
//     inputType: 'decimal',
//     visible: formData => formData.fortuneBizType === 'R',
//     rules: [{ pattern: /^\d+$/, message: '只能输入正整数', trigger: 'blur' }]
//   },
//   {
//     type: 'date',
//     prop: 'payoutDate',
//     label: '出账日（估）',
//     placeholder: '请选择'
//   },
//   {
//     type: 'date',
//     prop: 'actualPayoutDate',
//     label: '出账日（实）',
//     placeholder: '请选择',
//     maxDate: 'today'
//   },
//   {
//     type: 'input',
//     prop: 'hkdAmount',
//     label: '出账金额',
//     rules: [
//       { required: true, message: '请输入', trigger: 'blur' },
//       { pattern: /^-?\d+(\.\d{1,2})?$/, message: '小数（最多两位）', trigger: 'blur' }
//     ]
//   },
//   {
//     type: 'select',
//     prop: 'currency',
//     label: '出账币种',
//     dictType: 'bx_currency_type',
//     defaultValue: 'HKD'
//   },
//   {
//     type: 'input',
//     prop: 'defaultExchangeRate',
//     label: '结算汇率（入账检核时的汇率）',
//     rules: [
//       { required: true, message: '请输入', trigger: 'blur' },
//       { pattern: /^-?\d+(\.\d{1,6})?$/, message: '小数（最多6位）', trigger: 'blur' }
//     ]
//   },
//   {
//     type: 'select',
//     prop: 'fortuneType',
//     label: '出账项目',
//     dictType: 'csf_fortune_type'
//   },
//   {
//     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'
//     },
//     transform: res => {
//       return res?.data.records || []
//     }
//   },
//   {
//     type: 'select',
//     prop: 'status',
//     label: '出账状态',
//     dictType: 'csf_expected_fortune_status'
//   },
//   {
//     type: 'input',
//     prop: 'exchangeRate',
//     label: '结算汇率',
//     inputType: 'decimal',
//     rules: [{ required: true, message: '只能输入正整数和小数', trigger: 'blur' }]
//     // defaultValue: 1
//   },
//   {
//     type: 'input',
//     prop: 'remark',
//     label: '备注'
//   }
// ]
const addPayRecordFormConfig = [
  {
    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: '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: 'statusDesc',
    label: '修改理由'
  },
  // {
  //   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: '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: '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: 20 },
    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: 'input',
  //   prop: 'defaultExchangeRate',
  //   label: '结算汇率（入账检核时的汇率）',
  //   rules: [
  //     { required: true, message: '请输入', trigger: 'blur' },
  //     { pattern: /^-?\d+(\.\d{1,6})?$/, message: '小数（最多6位）', 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: 'decimal',
    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: 'defaultExchangeRate',
    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 typeOptions = [
  { value: 1, label: '预计' },
  { value: 2, label: '实际' }
]

// 是否实收通过value转成label
const getTypeLabel = value => {
  const item = typeOptions.find(item => item.value === value)
  return item?.label || ''
}

// 定义行类名方法
const getRowClassName = ({ row }) => {
  // type == 1 表示“预计”，添加高亮类名
  return row.type === 1 ? 'estimated-row' : ''
}

const handleInputChange = async (formType, prop, value, item) => {
  if (formType == 'addPayRecord') {
    await nextTick()
    let policyNo = addPayRecordFormModel.value.policyNo
    let fortunePeriod = addPayRecordFormModel.value.fortunePeriod
    if ((prop == 'policyNo' || prop == 'fortunePeriod') && fortunePeriod && policyNo) {
      const res = await commissionExchangeRateApi({
        policyNo: policyNo,
        commissionPeriod: fortunePeriod
      })
      if (res.code == 200) {
        addPayRecordFormModel.value.defaultExchangeRate = res.data
      } else {
        ElMessage.error('查询结算汇率失败')
      }
    }
    // 1.计算港币金额
    if (prop === 'originalToHkdRate' && value && addPayRecordFormModel.value.originalAmount) {
      // 计算港币金额   原币种金额*原币种->港币
      const originalAmount = addPayRecordFormModel.value.originalAmount
      const originalToHkdRate = value
      const hkdAmount = calculateAmount(originalAmount, originalToHkdRate, 2)
      await nextTick()
      addPayRecordFormModel.value.hkdAmount = hkdAmount

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

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

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

    //3.计算保单币种金额   港币金额*保单币种->港币汇率
    if (prop == 'hkdAmount' && value && updatePayRecordFormModel.value.exchangeRate) {
      // 计算保单币种金额
      const exchangeRate = updatePayRecordFormModel.value.exchangeRate
      const hkdAmount = value
      const ruleAmount = calculateAmount(hkdAmount, exchangeRate, 2, 'Divided')
      await nextTick()
      updatePayRecordFormModel.value.ruleAmount = ruleAmount
    } else if (prop == 'exchangeRate' && value && updatePayRecordFormModel.value.hkdAmount) {
      // 计算保单币种金额
      const exchangeRate = value
      const hkdAmount = updatePayRecordFormModel.value.hkdAmount
      const ruleAmount = calculateAmount(hkdAmount, exchangeRate, 2, 'Divided')
      await nextTick()
      updatePayRecordFormModel.value.ruleAmount = ruleAmount
    }
  }
}
const handleConfirmAddPayRecord = async () => {
  if (editStatus.value === 'add') {
    const handleConfirmAddPayRecordparams = addPayRecordFormRef.value.getFormData()
    try {
      await addPayRecord([handleConfirmAddPayRecordparams])
      ElMessage.success('新增出账记录成功')
      addPayRecordDialogVisible.value = false
      addPayRecordFormRef.value.resetForm()
      expectedFortuneListData()
    } catch (error) {
      ElMessage.error(error.message)
    }
  } else if (editStatus.value === 'edit') {
    try {
      const params = {
        expectedFortuneBizId: selectedRow.value.expectedFortuneBizId,
        ...addPayRecordFormModel.value
      }
      await updatePayRecord(params)
      ElMessage.success('更新出账记录成功')
      updatePayRecordDialogVisible.value = false
      updatePayRecordFormRef.value.resetForm()
      loadPayRecordTableData(selectedRow.value.expectedFortuneBizId)
      expectedFortuneListData()
    } catch (error) {
      ElMessage.error(error.message)
    }
  }
}
const handleConfirmUpdatePayRecord = async () => {
  if (selectedRow.value.type == '1') {
    try {
      const formData = await updatePayRecordFormRef.value.validate()
      console.log('====================================')
      console.log('formData', formData)
      console.log('====================================')
      if (!formData) {
        return
      }
      const params = {
        ...formData,
        expectedFortuneBizId: selectedRow.value.expectedFortuneBizId
      }
      await updatePayRecord(params)
      ElMessage.success('更新出账记录成功')
      updatePayRecordDialogVisible.value = false
      updatePayRecordFormRef.value.resetForm()

      loadPayRecordTableData(selectedRow.value.expectedFortuneBizId)
      expectedFortuneListData()
      loadTableData()
    } catch (error) {
      if (error.message && error.message.includes('Validation')) {
        ElMessage.error('必填项不能为空')
      }
      ElMessage.error('更新失败')
    }
  }
}
// 弹窗表单重置
const resetAddPayRecordForm = () => {
  addPayRecordFormRef.value.resetForm()
  editStatus.value = 'add'
  addPayRecordDialogVisible.value = false
}

const editStatus = ref('add')
// 出账记录
const payRecordDialogTableData = ref([])
const payRecordDialogTableColumns = ref([])
const handleSelect = async (e, row) => {
  selectedRow.value = { ...row }
  if (e === 'payRecord') {
    payRecordDialogTableVisible.value = true
    loadPayRecordTableData(selectedRow.value.expectedFortuneBizId)
    payRecordDialogTableColumns.value = [
      { property: 'broker', label: '转介人', width: '100' },
      { property: 'fortuneName', label: '出账项目', width: '150' },
      {
        property: 'currentPaymentHkdAmount',
        label: '出账金额',
        width: '150',
        formatter: row => formatCurrency(row.currentPaymentHkdAmount || 0)
      },
      { property: 'currency', label: '出账币种', width: '150' },
      {
        property: 'currentPaymentRatio',
        label: '出账比例',
        width: '150',
        formatter: row => `${row.currentPaymentRatio}%`
      },
      {
        property: 'fortuneUnpaidRatio',
        label: '待出账比例',
        width: '150',
        formatter: row => `${row.fortuneUnpaidRatio}%`
      },
      { property: 'fortunePeriod', label: '佣金期数', width: '150' },
      { property: 'fortuneTotalPeriod', label: '总期数', width: '150' },
      { property: 'reconciliationOperator', label: '操作人', width: '150' },
      { property: 'updateTime', label: '操作时间', width: '150' }
    ]
  } else if (e === 'setStatus') {
    setPayRecordStatusDialogVisible.value = true
    setPayRecordStatusFormConfig.value = [
      {
        type: 'select',
        prop: 'status',
        label: '出账状态',
        dictType: 'csf_expected_fortune_status',
        defaultValue: selectedRow.value.status || ''
      },
      {
        type: 'textarea',
        prop: 'statusDesc',
        label: '修改理由',
        defaultValue: selectedRow.value.statusDesc || ''
      }
    ]
  } else if (e === 'updateData') {
    updatePayRecordDialogVisible.value = true
    // 2. 使用 nextTick 等待 DOM 更新
    nextTick(() => {
      // 3. 此时 addRecordRef.value 一定存在了
      if (updatePayRecordFormRef.value && selectedRow.value) {
        updatePayRecordFormModel.value = { ...selectedRow.value }
      }
    })
    console.log(addPayRecordFormModel.value)
  }
}

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const pageTotal = ref(0)
const loading = ref(false)
// 表格操作菜单
const dropdownItems = [
  { label: '出账记录', value: 'payRecord' },
  { label: '设置状态', value: 'setStatus' },
  { label: '更新数据', value: 'updateData' }
]

// 表格数据
const tableData = ref([])

// 统计信息
const statisticsData = ref({})

// 按钮事件处理
const handleAdd = () => {
  // ElMessage.info('点击新增按钮')
  addPayRecordDialogVisible.value = true
}

const handleImport = () => {
  ElMessage.info('点击导入按钮')
}

const handleExport = async () => {
  // 获取搜索参数
  const params = searchFormRef.value?.getFormData() || {}
  const response = await exportPayRecord(params)
  // 文件名设置为应收款导出_yyyy-MM-dd hh:mm:ss.xlsx,不需要-，用字符串
  const fileName = `应付款导出_${new Date().toLocaleString().replace(/\//g, '').replace(/:/g, '').replace(/\s/g, '')}.xlsx`
  await safeDownload(response, fileName, 'application/vnd.ms-excel;charset=utf-8')
}

const handleReset = () => {
  // 重置搜索表单
  searchFormRef.value.resetForm()
  searchParams.value = {}
  console.log('表单已重置')
  // 重新加载数据
  loadTableData()
}

const handleQuery = async () => {
  currentPage.value = 1
  loadTableData()
}

// 按钮配置
const operationBtnList = ref([
  {
    key: 'add',
    direction: 'left',
    click: handleAdd
  },
  // {
  //   key: 'import',
  //   direction: 'left',
  //   click: handleImport
  // },
  {
    key: 'export',
    direction: 'right',
    click: handleExport
  },
  {
    key: 'reset',
    direction: 'right',
    click: handleReset
  },
  {
    key: 'query',
    direction: 'right',
    click: handleQuery
  }
])

// 分页事件
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 loadTableData = async () => {
  const searchParams = (await searchFormRef.value.getFormData()) || {}
  loading.value = true
  if (searchParams.payoutDate.length > 0) {
    searchParams.payoutDateStart = `${searchParams.payoutDate[0]}-01`
    searchParams.payoutDateEnd = `${searchParams.payoutDate[1]}-01`
  } else {
    searchParams.payoutDateStart = ''
    searchParams.payoutDateEnd = ''
  }
  try {
    const params = {
      ...searchParams,
      // payoutDateStart: searchParams.payoutDate?.[0] || undefined,
      // payoutDateEnd: searchParams.payoutDate?.[1] || undefined,
      payoutDate: undefined,
      pageNo: currentPage.value,
      pageSize: pageSize.value
    }
    const response = await payableReport(params)
    tableData.value = response.data.page.records
    pageTotal.value = response.data.page.total
    pageSize.value = response.data.page.size

    // 统计信息
    statisticsData.value = {
      totalExpectedAmount: response.data.statisticsVO.totalExpectedAmount,
      totalPaidAmount: response.data.statisticsVO.totalPaidAmount,
      totalUnpaidAmount: response.data.statisticsVO.totalUnpaidAmount,
      paidAmountRatio: response.data.statisticsVO.paidAmountRatio,
      totalPolicyCount: response.data.statisticsVO.totalPolicyCount,
      totalPremiumAmount: response.data.statisticsVO.totalPremiumAmount
    }
  } catch (error) {
    console.error('加载数据失败:', error)
    // ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

// 出账记录查询
const loadPayRecordTableData = async expectedFortuneBizId => {
  loading.value = true
  try {
    const params = {
      expectedFortuneBizId: expectedFortuneBizId
    }
    const response = await payRecordList(params)
    payRecordDialogTableData.value = response.data.records
  } catch (error) {
    console.error('加载数据失败:', error)
    // ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

// 设置出账状态确认
const handleConfirmSetPayRecordStatus = async () => {
  const formData = setPayRecordStatusFormRef.value.getFormData() || {}
  if (!formData.status) {
    ElMessage.error('请选择出账状态')
    return
  }
  if (!formData.statusDesc) {
    ElMessage.error('请输入修改理由')
    return
  }
  try {
    const params = {
      ...formData,
      fortuneBizIdList: [selectedRow.value.expectedFortuneBizId]
    }
    await updataPayrollStatus(params)
    ElMessage.success('设置出账状态成功')
    setPayRecordStatusDialogVisible.value = false
    loadTableData()
  } catch (error) {
    console.error('设置出账状态失败:', error)
    ElMessage.error('设置出账状态失败')
  }
}
// 获取入账状态,字典值转化方法
onMounted(async () => {
  try {
    await loadDicts(['csf_expected_fortune_status'])
    loadTableData()
  } catch (error) {
    console.error('字典加载失败', error)
  } finally {
    loading.value = false
  }
})
// 格式化函数（每次渲染都会调用，所以能拿到最新字典）
const formatStatus = (row, column) => {
  return getDictLabel('csf_expected_fortune_status', row.status) // 实时查缓存
}
const detailRecordStatistics = ref({})
const detailPageInfo = ref({
  pageNo: 1,
  pageSize: 10,
  currentPage: 1,
  total: 0
})
const selectedDetailRecordRow = ref({})
// 应付款管理列表查询
const expectedFortuneListData = async () => {
  loading.value = true
  try {
    const params = {
      policyNo: selectedDetailRecordRow.value.policyNo,
      fortunePeriod: selectedDetailRecordRow.value.fortunePeriod,
      fortuneBizType: selectedDetailRecordRow.value.fortuneBizType,
      payableNo: selectedDetailRecordRow.value.payableNo,
      pageNo: detailPageInfo.value.currentPage,
      pageSize: detailPageInfo.value.pageSize
    }
    const response = await expectedFortuneList(params)
    payableReportTableData.value = response.data.page.records
    detailPageInfo.value.total = response.data.page.total
    detailPageInfo.value.pageSize = response.data.page.size
    // 统计信息
    detailRecordStatistics.value = {
      totalExpectedAmount: response.data.statisticsVO.totalExpectedAmount,
      totalPaidAmount: response.data.statisticsVO.totalPaidAmount,
      totalUnpaidAmount: response.data.statisticsVO.totalUnpaidAmount,
      paidAmountRatio: response.data.statisticsVO.paidAmountRatio,
      totalPolicyCount: response.data.statisticsVO.totalPolicyCount,
      totalPremiumAmount: response.data.statisticsVO.totalPremiumAmount
    }
  } catch (error) {
    console.error('加载数据失败:', error)
    // ElMessage.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

const viewDetail = row => {
  selectedDetailRecordRow.value = row
  detailDialogVisible.value = true
  expectedFortuneListData()
}

// 分页事件
const handleSizeChangeDetailRecord = val => {
  detailPageInfo.value.pageSize = val
  expectedFortuneListData()
}
// 分页事件
const handleCurrentChangeDetailRecord = val => {
  detailPageInfo.value.currentPage = val
  expectedFortuneListData()
}
</script>

<style scoped lang="scss">
.page-search-container {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  margin-bottom: 20px;
}

.search-actions {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
  text-align: right;
}
/* 使用 :deep 穿透 scoped 样式，保证对 el-table__row 生效 */
:deep(.estimated-row) {
  background-color: #f0f9ff; /* 浅蓝色，可根据需要修改 */
}
</style>
