<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>
        <!-- 统计信息卡片 -->
        <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.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.reconciliationCompanyCount" />
            </el-col>
            <el-col :xs="24" :sm="12" :md="4" class="text-center mb-4">
              <el-statistic
                title="比对记录总条数"
                :value="statisticsData.totalCompareCommissionCount"
              />
            </el-col>
            <el-col :xs="24" :sm="12" :md="4" class="text-center mb-4">
              <el-statistic
                title="比对成功数"
                :value="statisticsData.successCompareCommissionCount"
              />
            </el-col>
            <el-col :xs="24" :sm="12" :md="4" class="text-center mb-4">
              <el-statistic
                title="比对失败数"
                :value="statisticsData.failedCompareCommissionCount"
              />
            </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.expectePaidAmount"
                :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-row>
          <el-col :span="6">
            <el-text tag="mark" class="mx-1">实佣率=实际入账金额/结算汇率/每期保费</el-text>
          </el-col>
          <el-col :span="6">
            <el-text tag="mark" class="mx-1"> 达成率缺口= 1 - 本期实佣率/保单本期来佣率 </el-text>
          </el-col>
        </el-row>
        <el-table
          :data="tableData"
          ref="multipleTableRef"
          height="400"
          row-key="id"
          border
          highlight-current-row
          style="width: 100%"
          v-loading="loading"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="40" :selectable="selectableFn" />
          <el-table-column
            prop="commissionStatus"
            label="比对状态"
            width="120"
            sortable
            fixed="left"
          >
            <template #default="{ row }">
              {{ selectDictLabel(csf_commission_status, row.commissionStatus) }}
            </template>
          </el-table-column>
          <el-table-column prop="commissionBizType" label="业务类型" width="120" sortable>
            <template #default="{ row }">
              {{ getCommissionBizTypeLabel(row.commissionBizType) }}
            </template>
          </el-table-column>
          <el-table-column prop="reconciliationYearMonth" label="检核年月" width="120" sortable />
          <el-table-column prop="policyNo" label="保单号" width="120" sortable />
          <el-table-column prop="reconciliationCompany" label="对账公司" width="120" sortable />
          <el-table-column prop="commissionDate" label="入账日" width="120" sortable />
          <el-table-column prop="commissionExpectedStatus" label="入账状态" width="120" sortable>
            <template #default="{ row }">
              {{ selectDictLabel(csf_expected_commission_status, row.commissionExpectedStatus) }}
            </template>
          </el-table-column>
          <el-table-column
            prop="currentCommissionRatio"
            label="本次实佣率"
            width="130"
            sortable
            :formatter="formatRatio"
          />
          <el-table-column
            prop="paidRatio"
            label="累积实佣率"
            width="130"
            sortable
            :formatter="formatRatio"
          />
          <el-table-column
            prop="pendingRatio"
            label="达成率缺口"
            width="120"
            sortable
            :formatter="formatRatio"
          />
          <el-table-column
            prop="amount"
            label="本次入账金额"
            width="130"
            sortable
            :formatter="formatCurrencyUtil"
          />
          <el-table-column prop="currency" label="入账币种" width="120" sortable />
          <el-table-column prop="exchangeRate" label="结算汇率(实)" width="140" sortable />
          <el-table-column prop="commissionPeriod" label="本次入账期数" width="130" sortable />
          <el-table-column prop="totalPeriod" label="总期数" width="120" sortable />
          <el-table-column prop="commissionName" label="入账项目" width="120" sortable />
          <el-table-column
            prop="premium"
            label="期交保费"
            width="120"
            sortable
            :formatter="formatCurrencyUtil"
          />
          <el-table-column prop="policyCurrency" label="保单币种" width="120" sortable />
          <el-table-column prop="productName" label="产品名称" width="120" />
          <el-table-column prop="commissionRatio" label="保单本期来佣率" width="120" />
          <el-table-column prop="policyHolder" label="投保人" width="120" />
          <el-table-column prop="policyHolderEn" label="投保人(英文)" width="120" />
          <el-table-column prop="broker" label="转介人" width="120" />
          <el-table-column prop="insuranceCompany" label="保险公司" width="120" />
          <el-table-column prop="remark" label="备注" width="120" sortable />
          <el-table-column prop="isDeleted" label="记录状态" width="120" sortable>
            <template #default="{ row }">
              {{ row.isDeleted === 1 ? '无效' : '有效' }}
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" min-width="120">
            <template #default="{ row }">
              <el-popover placement="right" :width="200" trigger="click">
                <template #reference>
                  <el-icon>
                    <MoreFilled />
                  </el-icon>
                </template>
                <el-menu @select="handleSelect($event, row)" popper-class="custom-menu">
                  <el-menu-item :index="item.value" v-for="item in dropdownItems" :key="item.value">
                    <el-text class="mx-1" v-if="!item.confirm">{{ item.label }}</el-text>
                    <el-popconfirm
                      v-if="item.confirm"
                      confirm-button-text="Yes"
                      cancel-button-text="No"
                      :icon="InfoFilled"
                      icon-color="#626AEF"
                      :title="item.confirm"
                      @confirm="handleMenuConfirm(item.value, row)"
                      width="300"
                      placement="left-end"
                    >
                      <template #reference>
                        <el-text class="mx-1">{{ item.label }}</el-text>
                      </template>
                    </el-popconfirm>
                  </el-menu-item>
                </el-menu>
              </el-popover>
            </template>
          </el-table-column>
        </el-table>
        <!-- 表格操作菜单 -->
        <div class="tableOptionContainer">
          <el-row justify="space-between">
            <el-col :span="12">
              <el-text type="danger">*非关联保单应收单以及比对失败的不可生成可出账记录</el-text>
            </el-col>
            <el-col :span="4">
              <el-button
                type="primary"
                :icon="Select"
                :disabled="updatePayRollStatusDisable"
                @click="generateCommissionRecordapi"
                >{{ multipleSelection.length }} 条数据，生成可出账记录</el-button
              >
            </el-col>
          </el-row>
        </div>
      </template>
    </CommonPage>
    <!-- 开始检核弹窗-->
    <CommonDialog
      dialogTitle="开始检核"
      dialogWidth="80%"
      :openDialog="dialogFlag"
      :showAction="false"
      :showClose="true"
      @close="closthDialog()"
    >
      <el-row>
        <el-col :xs="24" :sm="24" :md="24" :lg="24">
          <SearchForm ref="checkFormRef" :config="checkConfig" v-model="checkFormData" />
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :xs="24" :sm="12" :md="3" :lg="3">
          <el-button
            type="primary"
            :icon="Plus"
            :disabled="!checkFormData?.reconciliationYearMonth"
            @click="handleAddCheckList()"
            >新增</el-button
          >
        </el-col>
        <el-col :xs="24" :sm="24" :md="3" :lg="3">
          <el-button
            type="primary"
            :icon="Upload"
            :disabled="!checkFormData?.reconciliationYearMonth"
            @click="fileUploadDialogFlag = true"
            >导入</el-button
          >
        </el-col>
        <el-col :xs="24" :sm="24" :md="3" :lg="3">
          <el-button type="primary" link @click="downloadTemplate">下载模板</el-button>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :xs="24" :sm="24" :md="24" :lg="24">
          <el-table :data="checkRecordTableData" style="width: 100%" height="400">
            <el-table-column prop="commissionBizType" label="应收款类型" width="120">
              <template #default="{ row }">
                {{ getCommissionBizTypeLabel(row.commissionBizType) }}
              </template>
            </el-table-column>
            <!-- <el-table-column prop="receivableNo" label="应收款编号" width="120" /> -->
            <el-table-column prop="policyNo" label="关联保单号" width="120" />
            <el-table-column prop="commissionStatus" label="比对状态" width="120" fixed="left">
              <template #default="{ row }">
                {{ selectDictLabel(csf_commission_status, row.commissionStatus) }}
              </template>
            </el-table-column>
            <el-table-column prop="commissionPeriod" label="佣金期数" width="120" />
            <el-table-column prop="totalPeriod" label="总期数" width="120" />
            <el-table-column prop="commissionDate" label="入账日（实）" width="120" />
            <el-table-column prop="amount" label="入账金额" width="120" />
            <el-table-column prop="currency" label="入账币种" width="120" />
            <el-table-column prop="exchangeRate" label="结算汇率" width="120" />
            <el-table-column prop="commissionName" label="入账项目" width="120" />
            <el-table-column prop="reconciliationCompany" label="对账公司" width="120" />
            <!-- <el-table-column prop="zip" label="入账状态" width="120" /> -->
            <el-table-column fixed="right" label="操作" min-width="240">
              <template #default="{ row }">
                <el-button type="primary" text size="small" @click="compareCommissionEntryapi(row)">
                  重新比对
                </el-button>
                <el-button type="primary" text size="small" @click="checkRecordEdit(row)">
                  修改
                </el-button>
                <el-popconfirm
                  confirm-button-text="Yes"
                  cancel-button-text="No"
                  :icon="InfoFilled"
                  icon-color="#626AEF"
                  title="确认要删除吗？"
                  @confirm="deletePolicyCommissionApi(row)"
                >
                  <template #reference>
                    <el-button text type="danger" size="small">删除</el-button>
                  </template>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :xs="24" :sm="24" :md="24" :lg="24">
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="checkRecordPageInfo.currentPage"
              v-model:page-size="checkRecordPageInfo.pageSize"
              :page-sizes="[50, 100, 200, 300]"
              :total="checkRecordPageInfo.total"
              @size-change="checkRecordPageHandleSizeChange"
              @current-change="checkRecordPageHandleCurrentChange"
              layout="total, sizes, prev, pager, next, jumper"
            />
          </div>
        </el-col>
      </el-row>
    </CommonDialog>
    <!-- 新增检核记录弹窗 -->
    <CommonDialog
      :dialogTitle="editStatus.value == 'add' ? '新增检核记录' : '修改检核记录'"
      dialogWidth="80%"
      :openDialog="addCheckRecordDialogFlag"
      :showAction="true"
      :showClose="true"
      @close="closeDialog()"
      @confirm="handleAddCheckRecord()"
    >
      <el-row>
        <el-col :xs="24" :sm="24" :md="24" :lg="24">
          <SearchForm
            ref="addCheckRecordFormRef"
            :config="addCheckRecordConfig"
            v-model="addReceivablesFormModel"
          />
        </el-col>
      </el-row>
    </CommonDialog>

    <CommonDialog
      dialogTitle="文件导入"
      dialogWidth="80%"
      :openDialog="fileUploadDialogFlag"
      :showAction="true"
      :showClose="true"
      @close="((fileUploadDialogFlag = false), (files = ''))"
      @confirm="((fileUploadDialogFlag = false), (files = ''))"
    >
      <FileUpload
        v-model="files"
        :data="{ reconciliationYearMonth: checkFormData.reconciliationYearMonth }"
        :file-type="['xlsx', 'xls']"
        :action="'/csf/api/commission/upload/excel'"
        :limit="1"
        :fileSize="15"
        @uploadEnd="handleUploadEnd"
      />
    </CommonDialog>

    <!-- 设置比对状态 -->
    <CommonDialog
      dialogTitle="设置比对状态"
      dialogWidth="80%"
      :openDialog="setCompareStatusDialogFlag"
      :showAction="true"
      :showClose="true"
      @close="setCompareStatusDialogFlag = false"
      @confirm="setCompareStatusapi"
    >
      <SearchForm
        ref="setCompareStatusFormRef"
        :config="setCompareStatusConfig"
        v-model="setCompareStatusFormModel"
      />
    </CommonDialog>

    <!-- 更新数据 -->

    <CommonDialog
      dialogTitle="更新数据"
      dialogWidth="80%"
      :openDialog="updateDataDialogFlag"
      :showAction="true"
      :showClose="true"
      @close="updateDataDialogFlag = false"
      @confirm="updateDataapi"
    >
      <SearchForm
        ref="updateDataFormRef"
        :config="updateDataConfig"
        v-model="updateDataFormModel"
      />
    </CommonDialog>

    <!-- 查看记录 -->
    <CommonDialog
      dialogTitle="查看记录"
      dialogWidth="80%"
      :openDialog="viewRecordDialogFlag"
      :showAction="true"
      :showClose="true"
      @close="viewRecordDialogFlag = false"
    >
    </CommonDialog>
    <!-- 修改检核 -->

    <CommonDialog
      dialogTitle="修改检核"
      dialogWidth="80%"
      :openDialog="recordCheckDialogFlag"
      :showAction="true"
      :showClose="true"
      @close="recordCheckDialogFlag = false"
      @confirm="confirmRecordCheck"
    >
      <SearchForm
        ref="updateDataFormRef"
        :config="updateDataConfig"
        v-model="updateDataFormModel"
      />
    </CommonDialog>
    <!-- 修改入账状态 -->

    <CommonDialog
      dialogTitle="修改入账状态"
      dialogWidth="80%"
      :openDialog="accountedStatusFlag"
      :showAction="true"
      :showClose="true"
      @close="accountedStatusFlag = false"
      @confirm="confirmAccountedStatus"
    >
      <SearchForm
        ref="accountedStatusFormRef"
        :config="accountedStatusConfig"
        v-model="accountedStatusFormModel"
      />
    </CommonDialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import CommonPage from '@/components/commonPage'
import CommonDialog from '@/components/commonDialog'
import SearchForm from '@/components/SearchForm/SearchForm.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { formatCurrency } from '@/utils/number'
// 接口
import {
  getPolicyCommissionList,
  generateCommissionRecord,
  addPayrollCheckRecord,
  commissionExpectedRecord,
  updateCompareStatus,
  updateCommissionRecord,
  deletePolicyCommission,
  syncExpectedCommission,
  compareCommissionEntry,
  editStatusApi
} from '@/api/financial/commission'

import { InfoFilled, Select, Upload, Plus } from '@element-plus/icons-vue'
import FileUpload from '@/components/FileUpload/index.vue'
import { loadDicts, getDictLabel } from '@/utils/useDict'

const accountedStatusFormModel = ref({})
const accountedStatusFlag = ref(false)
const accountedStatusFormRef = ref(null)

const { proxy } = getCurrentInstance()
const { csf_expected_commission_status } = proxy.useDict('csf_expected_commission_status')
const { csf_commission_status } = proxy.useDict('csf_commission_status')
const downloadTemplateUrl =
  'https://yd-ali-oss.oss-cn-shanghai-finance-1-pub.aliyuncs.com/xlsx/2026/01/26/33f0637762144d58a256f5d8d3c2d2b6.xlsx'
const recordCheckDialogFlag = ref(false)
const accountedStatusConfig = ref([
  {
    type: 'select',
    prop: 'status',
    label: '入账状态',
    dictType: 'csf_expected_commission_status',
    rules: [{ required: true, message: '请选择入账状态', trigger: 'blur' }]
    // defaultValue: selectedRow.value.status || ''
  },
  {
    type: 'textarea',
    prop: 'statusDesc',
    label: '修改理由',
    rules: [{ required: true, message: '请填写修改理由', trigger: 'blur' }]
    // defaultValue: selectedRow.value.statusDesc || ''
  }
])
const downloadTemplate = () => {
  const link = document.createElement('a')
  link.href = downloadTemplateUrl // 注意：以 / 开头，指向 public 下的文件
  link.download = '入账检核导入模板.xlsx' // 设置下载文件名
  link.click() // 自动触发点击，无需 append 到 DOM（现代浏览器支持）
}

const formatRatio = (row, column, cellValue, index) => {
  if (cellValue == null || (cellValue == '' && cellValue !== 0)) {
    return '-'
  }
  return cellValue + '%'
}

const formatCurrencyUtil = (row, column, cellValue, index) => {
  if (cellValue == null || cellValue == '' || cellValue == 0) {
    return '-'
  }
  return formatCurrency(cellValue)
}
const files = ref('')
// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const pageTotal = ref(0)
// 弹窗页面检核记录分页
const checkRecordPageInfo = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})
const checkRecordPageHandleSizeChange = val => {
  checkRecordPageInfo.pageSize = val
  checkRecordQuery()
}
const checkRecordPageHandleCurrentChange = val => {
  checkRecordPageInfo.currentPage = val
  checkRecordQuery()
}
const loading = ref(false)
const searchFormRef = ref(null)
const searchConfig = ref([
  {
    type: 'input',
    prop: 'policyNo',
    label: '保单号'
  },
  {
    type: 'select',
    prop: 'statusList',
    label: '比对状态',
    multiple: true,
    dictType: 'csf_commission_status'
  },
  {
    type: 'select',
    prop: 'reconciliationCompanyBizIdList',
    label: '对账公司',
    api: '/insurance/base/api/insuranceReconciliationCompany/page',
    keywordField: 'name',
    requestParams: { pageNo: 1, pageSize: 20 },
    placeholder: '输入对账公司名称搜索',
    debounceWait: 500, // 自定义防抖时间
    multiple: true,
    valueKey: 'reconciliationCompanyBizId',
    labelKey: 'name',
    transform: res => {
      console.log(res)
      return res?.data.records || []
    }
  },
  {
    type: 'date',
    prop: 'expectedDate',
    label: '入账日（估）',
    placeholder: '请选择'
  },
  {
    type: 'daterange',
    prop: 'commissionDate',
    label: '入账日（实）',
    startPlaceholder: '开始时间',
    endPlaceholder: '结束时间'
  },
  {
    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: 'month',
    prop: 'reconciliationYearMonth',
    label: '检核年月',
    placeholder: '检核年月'
  }
])
const selectedRow = ref(null)
// 设置比对状态弹窗
const setCompareStatusDialogFlag = ref(false)
const setCompareStatusFormRef = ref(null)
const setCompareStatusConfig = [
  {
    type: 'select',
    prop: 'status',
    label: '比对状态',
    dictType: 'csf_commission_status'
  }
]
const setCompareStatusFormModel = reactive({
  status: ''
})
// 当比对状态为成功时可以选择
const selectableFn = row => row.commissionStatus == '1' && row.commissionBizType == 'R'
// 设置编辑状态，是新增还是修改
const editStatus = ref('add')
// 更新数据
const updateDataDialogFlag = ref(false)
// 查看记录
const viewRecordDialogFlag = ref(false)

const fileUploadDialogFlag = ref(false)
const checkRecordTableData = ref([])

const selectedRowCheck = ref(null)
const checkFormRef = ref(null)
const checkConfig = ref([
  {
    type: 'month',
    prop: 'reconciliationYearMonth',
    label: '检核年月',
    placeholder: '检核年月',
    rules: [{ required: true, message: '请选择检核年月', trigger: 'blur' }]
  },
  {
    type: 'input',
    prop: 'policyNo',
    label: '保单号',
    placeholder: '保单号'
  }
])
const checkRecordEdit = row => {
  console.log('查看记录', row)
  selectedRowCheck.value = { ...row }
  editStatus.value = 'edit'
  addReceivablesFormModel.value = { ...row }
  addCheckRecordDialogFlag.value = true
  console.log('父组件赋值', addReceivablesFormModel.value)
}

const checkFormData = ref({
  reconciliationYearMonth: ''
})

// 监听 checkFormData 变化，自动重新查询
watch(
  () => ({ ...checkFormData.value }), // 深度监听对象内容
  newVal => {
    // console.log('搜索条件变化:', newVal)
    // ✅ 在这里调用查询接口 或 触发列表刷新

    if (newVal.reconciliationYearMonth) {
      checkRecordQuery()
    }
  },
  { immediate: true } // 首次加载也执行（可选）
)
// 确认修改检核
const confirmRecordCheck = async () => {
  //等待后端接口
  try {
    // ✅ 统一从子组件获取完整表单数据（含 extra 字段）
    // await nextTick() // 确保子组件已同步
    const formData = updateDataFormRef.value.getFormData()
    console.log('===========', formData)
    let params
    params = {
      ...formData, // ←←← 使用 formData，不是 addReceivablesFormModel.value
      commissionBizId: selectedRow.value.commissionBizId
    }
    await updateCommissionRecord(params)

    ElMessage.success('修改检核记录成功')
    recordCheckDialogFlag.value = false
    updateDataFormRef.value.resetForm()

    loadTableData()
  } catch (error) {
    console.error('操作失败', error)
    ElMessage.error('操作失败')
  }
}
// 删除检核记录
const deletePolicyCommissionApi = async row => {
  console.log(row)
  try {
    const res = await deletePolicyCommission({ commissionBizId: row.commissionBizId })
    if (res.code === 200) {
      ElMessage.success('删除成功')
      checkRecordQuery()
      return true
    } else {
      ElMessage.error(res.msg || '删除失败')
      return false
    }
  } catch (error) {
    ElMessage.error('删除失败')
    return false
  }
}

// 生成可出账记录按钮
const updatePayRollStatusDisable = ref(true)

onMounted(async () => {})

// 应收单类型
const commissionBizTypeOptions = [
  { value: 'R', label: '关联保单应收单' },
  { value: 'U', label: '非关联保单应收单' }
]
// 应收单类型通过value转成label
const getCommissionBizTypeLabel = value => {
  const item = commissionBizTypeOptions.find(item => item.value === value)
  return item?.label || ''
}
// 新增应收款管理
const addReceivablesFormModel = ref({})
// 新增检核记录表单
const addCheckRecordFormRef = ref(null)
const addCheckRecordConfig = ref([
  {
    type: 'select',
    prop: 'commissionBizType',
    label: '应收单类型',
    placeholder: '应收单类型',
    options: commissionBizTypeOptions,
    rules: [{ required: true, message: '请选择应收单类型', trigger: 'blur' }]
  },
  {
    type: 'input',
    prop: 'policyNo',
    label: '保单号',
    visible: formData => formData.commissionBizType == 'R',
    rules: [{ required: true, message: '请输入保单号', trigger: 'blur' }]
  },
  {
    type: 'input',
    prop: 'commissionPeriod',
    label: '佣金期数',
    inputType: 'decimal',
    visible: formData => formData.commissionBizType == 'R',
    rules: [
      { required: true, message: '请输入佣金期数', trigger: 'blur' },
      { pattern: /^\d+$/, message: '只能输入正整数', trigger: 'blur' }
    ]
  },
  {
    type: 'input',
    prop: 'totalPeriod',
    label: '总期数',
    inputType: 'decimal',
    visible: formData => formData.commissionBizType == 'R',
    rules: [{ pattern: /^\d+$/, message: '只能输入正整数', trigger: 'blur' }]
  },
  {
    type: 'date',
    prop: 'commissionDate',
    label: '入账日（实）',
    placeholder: '请选择',
    maxDate: 'today',
    rules: [{ required: true, message: '请选择入账日（实）', trigger: 'blur' }]
  },
  {
    type: 'input',
    prop: 'amount',
    label: '入账金额',
    inputType: 'decimalNumber',
    decimalDigits: 4,
    rules: [
      { required: true, message: '请输入金额', trigger: 'blur' },
      { pattern: /^-?\d+(\.\d+)?$/, message: '请输入有效的数字', trigger: 'blur' }
    ]
  },
  {
    type: 'select',
    prop: 'currency',
    label: '入账币种',
    dictType: 'bx_currency_type',
    rules: [{ required: true, message: '请选择入账币种', trigger: 'blur' }]
  },
  {
    type: 'select',
    prop: 'commissionType',
    label: '入账项目',
    dictType: 'csf_commission_type',
    rules: [{ required: true, message: '请选择入账项目', trigger: 'blur' }],
    onChangeExtraFields: {
      commissionName: 'itemLabel'
    }
  },
  {
    type: 'select',
    prop: 'reconciliationCompanyBizId',
    label: '对账公司',
    api: '/insurance/base/api/insuranceReconciliationCompany/page',
    keywordField: 'name',
    requestParams: { pageNo: 1, pageSize: 20 },
    placeholder: '输入对账公司名称搜索',
    debounceWait: 500, // 自定义防抖时间
    onChangeExtraFields: {
      reconciliationCompany: 'name', // 自动同步 raw.name 到 reconciliationCompany
      reconciliationCompanyCode: 'code'
    },
    valueKey: 'reconciliationCompanyBizId',
    labelKey: 'name',
    transform: res => {
      console.log(res)
      return res?.data.records || []
    },
    rules: [{ required: true, message: '请选择对账公司', trigger: 'blur' }]
  },
  {
    type: 'input',
    prop: 'exchangeRate',
    label: '结算汇率（实)',
    inputType: 'decimal',
    decimalDigits: 4,
    rules: [
      { required: true, message: '请输入金额', trigger: 'blur' },
      { pattern: /^\d+(\.\d{1,4})?$/, message: '最多四位小数', trigger: 'blur' }
    ]
  },
  {
    type: 'input',
    prop: 'remark',
    label: '备注'
  }
])
const addCheckRecordDialogFlag = ref(false)
const handleAddCheckRecord = async () => {
  try {
    // ✅ 统一从子组件获取完整表单数据（含 extra 字段）
    await nextTick() // 确保子组件已同步
    const formData = addCheckRecordFormRef.value.getFormData()
    console.log('===========', formData)
    let params
    if (editStatus.value === 'edit') {
      params = {
        ...formData, // ←←← 使用 formData，不是 addReceivablesFormModel.value
        commissionBizId: selectedRowCheck.value.commissionBizId
      }
      await updateCommissionRecord(params)
    } else {
      params = {
        ...formData,
        reconciliationYearMonth: checkFormData.value.reconciliationYearMonth
      }
      await addPayrollCheckRecord([params])
    }
    ElMessage.success(editStatus.value === 'edit' ? '更新成功' : '新增成功')
    addCheckRecordDialogFlag.value = false
    addCheckRecordFormRef.value.resetForm()

    checkRecordQuery()
  } catch (error) {
    console.error('操作失败', error)
    ElMessage.error('操作失败')
  }
}
const clearForm = type => {
  if (type === 'addReceivablesFormModel')
    if (addCheckRecordFormRef.value) {
      addReceivablesFormModel.value = {}
      addCheckRecordFormRef.value.resetForm()
    }
}

const closeDialog = () => {
  addCheckRecordDialogFlag.value = false
  editStatus.value = 'add'
  handleQuery()
}
// 生成可出账记录
const generateCommissionRecordapi = async () => {
  try {
    const res = await generateCommissionRecord({
      commissionBizIdList: multipleSelection.value.map(item => item.commissionBizId)
    })
    if (res.code === 200) {
      ElMessage.success('生成可出账记录成功')
    } else {
      ElMessage.error(res.msg || '生成可出账记录失败')
    }
  } catch (error) {
    console.error('生成可出账记录失败', error)
    ElMessage.error('生成可出账记录失败')
  }
}
// 表格操作菜单
const dropdownItems = [
  { label: '设置比对状态', value: 'setStatus', confirm: '' },
  { label: '同步到应收款管理', value: 'syncToReceivable', confirm: '确认要同步到应收款管理吗？' },
  { label: '修改检核记录', value: 'editCheckRecord' },
  { label: '修改入账状态', value: 'setAccountedStatus' }
]
const handleMenuConfirm = async (action, row) => {
  console.log('点击了操作菜单', action, row)
  if (action === 'syncToReceivable') {
    try {
      // if (row.commissionStatus !== '3') {
      //   ElMessage.error('应收款管理已有这条记录，无需同步')
      //   return
      // }
      const res = await syncExpectedCommission({
        commissionBizId: row.commissionBizId
      })
      if (res.code === 200) {
        ElMessage.success('同步到应收款管理成功')
      } else {
        ElMessage.error(res.msg || '同步到应收款管理失败')
      }
    } catch (error) {
      console.error('同步到应收款管理失败', error)
      ElMessage.error('同步到应收款管理失败')
    }
  }
}

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

// 按钮事件处理
const handleAdd = () => {
  // 开始检核
  dialogFlag.value = true
}

const handleExport = () => {
  ElMessage.info('点击导出按钮')
}
const handleReset = () => {
  // 重置搜索表单
  searchFormRef.value.resetForm()
  checkFormData.value = {}
  console.log('表单已重置')
}
const handleQuery = async () => {
  const params = searchFormRef.value.getFormData()
  console.log('父组件发起查询:', params)
  loadTableData(params)
}

// 查询检核记录
const checkRecordQuery = async () => {
  try {
    const params = {
      reconciliationYearMonth: checkFormData.value.reconciliationYearMonth,
      policyNo: checkFormData.value.policyNo,
      pageNo: checkRecordPageInfo.currentPage,
      pageSize: checkRecordPageInfo.pageSize
    }
    const res = await commissionExpectedRecord(params)
    checkRecordTableData.value = res.data.records || []
    checkRecordPageInfo.total = res.data.total || 0
    checkRecordPageInfo.currentPage = res.data.current || 0
    checkRecordPageInfo.pageSizes = res.data.size || 0
  } catch (error) {
    console.error('查询检核记录失败', error)
    ElMessage.error('查询检核记录失败')
  }
}

const multipleSelection = ref([])
const handleSelectionChange = val => {
  multipleSelection.value = val
  console.log('全选:', val)
  // 生成可出账记录按钮是否禁用
  updatePayRollStatusDisable.value = val.length === 0
}
const visibleDefaultButtons = ref(['add', 'reset', 'query'])
// 按钮配置
const operationBtnList = ref([
  {
    key: 'add',
    direction: 'left',
    label: '开始检核',
    click: handleAdd
  },
  // {
  //   key: 'export',
  //   direction: 'right',
  //   click: handleExport
  // },
  {
    key: 'reset',
    direction: 'right',
    click: handleReset
  },
  {
    key: 'query',
    direction: 'right',
    click: handleQuery
  }
])

// 加载表格数据
const loadTableData = async (searchParams = {}) => {
  loading.value = true
  try {
    const params = {
      pageNo: currentPage.value,
      pageSize: pageSize.value,
      ...searchParams,
      commissionDateStart: searchParams.commissionDate?.[0] || undefined,
      commissionDateEnd: searchParams.commissionDate?.[1] || undefined,
      commissionDate: undefined
    }
    const res = await getPolicyCommissionList(params)
    tableData.value = res.data.page.records || []
    pageTotal.value = res.data.page.total || 0
    pageSize.value = res.data.page.size || 0
    // 统计信息
    statisticsData.value = res.data.commissionStatisticsVO || {}
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error(error.message || '加载数据失败')
  } finally {
    loading.value = false
  }
}
loadTableData()
// 分页事件
const handleSizeChange = val => {
  pageSize.value = val
  loadTableData()
}
const handleCurrentChange = val => {
  currentPage.value = val
  loadTableData()
}
// 表格数据
const tableData = ref([])

const handleSelect = (e, row) => {
  selectedRow.value = row
  console.log('选中行:', e, row)
  if (e === 'setStatus') {
    setCompareStatusDialogFlag.value = true
    return
  } else if (e === 'editRecord') {
    // updateDataDialogFlag.value = true
    return
  } else if (e === 'viewRecord') {
    viewRecordDialogFlag.value = true
    return
  } else if (e === 'syncToReceivable') {
    return
  } else if (e === 'editCheckRecord') {
    updateDataFormModel.value = { ...selectedRow.value }
    recordCheckDialogFlag.value = true
    return
  } else if (e === 'setAccountedStatus') {
    accountedStatusFormModel.value = {
      statusDesc: selectedRow.value.statusDesc,
      status: selectedRow.value.commissionExpectedStatus
    }
    accountedStatusFlag.value = true
    return
  }
}
const handleAddCheckList = () => {
  editStatus.value = 'add'
  addReceivablesFormModel.value = { ...selectedRow.value }
  addCheckRecordDialogFlag.value = true
  clearForm('addReceivablesFormModel')
}

// 设置比对状态api

const setCompareStatusapi = async () => {
  try {
    const res = await updateCompareStatus({
      ...setCompareStatusFormRef.value.getFormData(),
      commissionBizId: selectedRow.value.commissionBizId
    })
    if (res.code === 200) {
      ElMessage.success('设置比对状态成功')
      setCompareStatusDialogFlag.value = false
      setCompareStatusFormRef.value.resetForm()
      loadTableData()
    } else {
      ElMessage.error(res.msg || '设置比对状态失败')
    }
  } catch (error) {
    console.error('设置比对状态失败', error)
    ElMessage.error('设置比对状态失败')
  }
}

// 更新数据api
const updateDataFormRef = ref(null)
const updateDataFormModel = ref({
  commissionAmount: '',
  commissionStatus: ''
})
const updateDataConfig = addCheckRecordConfig
const updateDataapi = async () => {
  try {
    const res = await updateCommissionRecord({
      ...updateDataFormRef.value.getFormData(),
      commissionBizId: selectedRow.value.commissionBizId
    })
    if (res.code === 200) {
      ElMessage.success('更新数据成功')
      updateDataDialogFlag.value = false
      updateDataFormRef.value.resetForm()
      loadTableData()
    } else {
      ElMessage.error(res.msg || '更新数据失败')
    }
  } catch (error) {
    console.error('更新数据失败', error)
    ElMessage.error('更新数据失败')
  }
}
const handleUploadEnd = code => {
  if (code === 200) {
    ElMessage.success('上传文件成功')
    fileUploadDialogFlag.value = false
    files.value = ''
    checkRecordQuery()
  } else {
    ElMessage.error('上传文件失败')
  }
}

// 关闭弹窗后的操作
const closthDialog = () => {
  dialogFlag.value = false
  checkFormRef.value.resetForm()
  checkFormData.value = {}
  checkRecordTableData.value = []
}

// 重新比对
const compareCommissionEntryapi = async row => {
  try {
    const res = await compareCommissionEntry(row.commissionBizId)
    if (res.code === 200) {
      ElMessage.success('重新比对成功')
      checkRecordQuery()
    } else {
      ElMessage.error(res.msg || '重新比对失败')
    }
  } catch (error) {
    console.error('重新比对失败', error)
    ElMessage.error('重新比对失败')
  }
}
const confirmAccountedStatus = () => {
  const formData = accountedStatusFormRef.value.getFormData()
  console.log('====================================')
  console.log('formData', formData)
  console.log('====================================')
  if (!formData.status) {
    return ElMessage.warning('请选择入账状态')
  }
  if (!formData.statusDesc) {
    return ElMessage.warning('请输入修改理由')
  }
  ElMessageBox.confirm('确定要修改入账状态吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        const res = await editStatusApi({
          commissionExpectedBizId: selectedRow.value.commissionExpectedBizId,
          statusDesc: formData.statusDesc,
          status: formData.status
        })
        if (res.code === 200) {
          ElMessage.success('状态修改成功')
          accountedStatusFlag.value = false
          loadTableData() // 重新加载表格
        } else {
          ElMessage.error(res.msg || '状态修改失败')
        }
      } catch (error) {
        console.error('修改状态失败:', error)
        ElMessage.error('修改状态失败')
      }
    })
    .catch(() => {
      ElMessage.info('已取消修改')
    })
}
</script>

<style scoped>
.tableOptionContainer {
  margin-top: 10px;
}

.el-row,
.el-col {
  margin-bottom: 5px;
}
</style>
