<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" :lg="4">
              <el-card shadow="hover" class="statistics-card">
                <div class="card-content">
                  <div class="card-label">应出账总金额</div>
                  <div class="card-value">{{ formatCurrency(statisticsData.totalExpectedAmount) }}</div>
                </div>
              </el-card>
            </el-col>
            <el-col :xs="24" :sm="12" :md="4" :lg="4">
              <el-card shadow="hover" class="statistics-card">
                <div class="card-content">
                  <div class="card-label">已出账金额</div>
                  <div class="card-value">{{ formatCurrency(statisticsData.totalPaidAmount) }}</div>
                </div>
              </el-card>
            </el-col>
            <el-col :xs="24" :sm="12" :md="4" :lg="4">
              <el-card shadow="hover" class="statistics-card">
                <div class="card-content">
                  <div class="card-label">待出账金额</div>
                  <div class="card-value">{{ formatCurrency(statisticsData.totalUnpaidAmount) }}</div>
                </div>
              </el-card>
            </el-col>
            <el-col :xs="24" :sm="12" :md="4" :lg="4">
              <el-card shadow="hover" class="statistics-card">
                <div class="card-content">
                  <div class="card-label">已出账比例</div>
                  <div class="card-value">{{ statisticsData.paidAmountRatio }}%</div>
                </div>
              </el-card>
            </el-col>
            <el-col :xs="24" :sm="12" :md="4" :lg="4">
              <el-card shadow="hover" class="statistics-card">
                <div class="card-content">
                  <div class="card-label">总保单数</div>
                  <div class="card-value">{{ statisticsData.totalPolicyCount }}</div>
                </div>
              </el-card>
            </el-col>
            <el-col :xs="24" :sm="12" :md="4" :lg="4">
              <el-card shadow="hover" class="statistics-card">
                <div class="card-content">
                  <div class="card-label">总保费</div>
                  <div class="card-value">{{ formatCurrency(statisticsData.totalPremiumAmount) }}</div>
                </div>
              </el-card>
            </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">
      <div class="statistics-container" v-if="detailRecordStatistics.totalPolicyCount > 0">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :md="4" :lg="4">
            <el-card shadow="hover" class="statistics-card">
              <div class="card-content">
                <div class="card-label">应出账总金额</div>
                <div class="card-value">{{ formatCurrency(detailRecordStatistics.totalExpectedAmount) }}</div>
              </div>
            </el-card>
          </el-col>
          <el-col :xs="24" :sm="12" :md="4" :lg="4">
            <el-card shadow="hover" class="statistics-card">
              <div class="card-content">
                <div class="card-label">已出账金额</div>
                <div class="card-value">{{ formatCurrency(detailRecordStatistics.totalPaidAmount) }}</div>
              </div>
            </el-card>
          </el-col>
          <el-col :xs="24" :sm="12" :md="4" :lg="4">
            <el-card shadow="hover" class="statistics-card">
              <div class="card-content">
                <div class="card-label">待出账金额</div>
                <div class="card-value">{{ formatCurrency(detailRecordStatistics.totalUnpaidAmount) }}</div>
              </div>
            </el-card>
          </el-col>
          <el-col :xs="24" :sm="12" :md="4" :lg="4">
            <el-card shadow="hover" class="statistics-card">
              <div class="card-content">
                <div class="card-label">已出账比例</div>
                <div class="card-value">{{ detailRecordStatistics.paidAmountRatio }}%</div>
              </div>
            </el-card>
          </el-col>
          <el-col :xs="24" :sm="12" :md="4" :lg="4">
            <el-card shadow="hover" class="statistics-card">
              <div class="card-content">
                <div class="card-label">总保单数</div>
                <div class="card-value">{{ detailRecordStatistics.totalPolicyCount }}</div>
              </div>
            </el-card>
          </el-col>
          <el-col :xs="24" :sm="12" :md="4" :lg="4">
            <el-card shadow="hover" class="statistics-card">
              <div class="card-content">
                <div class="card-label">总保费</div>
                <div class="card-value">{{ formatCurrency(detailRecordStatistics.totalPremiumAmount) }}</div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>
      <el-table :data="payableReportTableData" border style="width: 100%;margin-bottom: 10px;">
        <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">
              <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">
      <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" />
    </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 } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { formatCurrency } from '@/utils/number'
import { expectedFortuneList, payRecordList, addPayRecord, updatePayRecord, exportPayRecord } 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 payableReportTableData = ref([])
const payableReportTableColumns = ref([
  { prop: 'policyNo', label: '保单号', sortable: true, width: '150', formatter: (row) => row.policyNo || '-' },
  { prop: 'broker', label: '转介人(主)', sortable: true, width: '150', formatter: (row) => row.broker || '-' },
  { 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: 'amount', label: '应出账金额', sortable: true, width: '120', formatter: (row) => formatCurrency(row.amount || 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: 'policyNo', label: '保单号', sortable: true, width: '120', formatter: (row) => row.policyNo || '-' },
  { prop: 'broker', label: '转介人', sortable: true, width: '120', formatter: (row) => row.broker || '-' },
  { prop: 'status', label: '出账状态', sortable: true, width: '120', formatter: (row) => getDictLabel('csf_expected_fortune_status', row.status) || '-' },
  { prop: 'currency', label: '出账币种', sortable: true, width: '120', formatter: (row) => row.currency || '-' },
  { 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: '120', formatter: (row) => row.payoutDate || '-' },
  { prop: 'actualPayoutDate', label: '出账日（实）', sortable: true, width: '120', formatter: (row) => row.actualPayoutDate || '-' },
  { prop: 'commissionRatio', label: '出账比例', sortable: true, width: '120', formatter: (row) => (row.commissionRatio || 0) + '%' || '-' },
  { prop: 'amount', label: '应出账金额（估）', sortable: true, width: '120', formatter: (row) => formatCurrency(row.amount || 0) },
  { prop: 'paidRatio', label: '已出账比例', sortable: true, width: '120', formatter: (row) => (row.paidRatio || 0) + '%' || '-' },
  { prop: 'paidAmount', label: '已出账金额', sortable: true, width: '120', formatter: (row) => formatCurrency(row.paidAmount || 0) },
  { prop: 'unpaidRatio', label: '待出账比例', sortable: true, width: '120', formatter: (row) => (row.unpaidRatio || 0) + '%' || '-' },
  { prop: 'unpaidAmount', label: '待出账金额(估)', sortable: true, width: '120', formatter: (row) => formatCurrency(row.unpaidAmount || 0) },
  { prop: 'brokerRatio', label: '持有比例', sortable: true, width: '120', 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: 'statusDesc', label: '修改理由', sortable: true, width: '120', formatter: (row) => row.statusDesc || '-' },
  { prop: 'remark', label: '备注', sortable: true, width: '120', formatter: (row) => row.remark || '-' },
])




// 设置出账状态
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: 'daterange',
    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: 'fortuneName',
    label: '出账项目',
    dictType: 'csf_fortune_type'
  },
  {
    type: 'select',
    prop: 'insurerBizId',
    label: '保险公司',
    api: '/insurance/base/api/insuranceCompany/page',
    keywordField: 'queryContent',
    requestParams: { pageNo: 1, pageSize: 20 },
    placeholder: '输入保险公司名称搜索',
    debounceWait: 500, // 自定义防抖时间
    valueKey: 'insuranceCompanyBizId',
    labelKey: 'abbreviation',
    transform: (res) => {
      console.log(res)
      return res?.data.records || []
    }
  }, {
    type: 'select',
    prop: 'productLaunchBizId',
    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',
    transform: (res) => {
      return res?.data.records || []
    }
  }, {
    type: 'select',
    prop: 'fortuneBizType',
    label: '应付单类型',
    options: [
      { value: 'R', label: '关联保单应付单' },
      { value: 'U', label: '非关联保单应付单' }
    ]
  }, {
    type: 'select',
    prop: 'teamBizId',
    label: '出单团队',
    api: '/csf/api/team/page',
    keywordField: 'teamName',
    requestParams: { pageNo: 1, pageSize: 20 },
    placeholder: '输入出单团队名称搜索',
    debounceWait: 500, // 自定义防抖时间
    valueKey: 'teamBizId',
    labelKey: 'teamName',
    transform: (res) => {
      return res?.data.records || []
    }
  },
])


const payRecordDialogTableVisible = ref(false)
// 新增出账记录
const addPayRecordFormModel = ref({
  fortuneBizType: 'U',
})
const addPayRecordDialogVisible = ref(false)
const addPayRecordFormRef = ref()
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: 'amount',
    label: '出账金额',
    inputType: 'decimal',
    rules: [
      { pattern: /^\d+$/, message: '只能输入正整数', trigger: 'blur' }
    ]
  }, {
    type: 'select',
    prop: 'currency',
    label: '出账币种',
    dictType: 'bx_currency_type'
  }, {
    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: 20 },
    placeholder: '输入转介人名称搜索',
    debounceWait: 500, // 自定义防抖时间
    valueKey: 'userSaleBizId',
    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'
  }
]
const handleConfirmAddPayRecord = async () => {
  if (editStatus.value === 'add') {
    const handleConfirmAddPayRecordparams = addPayRecordFormRef.value.getFormData()
    try {
      await addPayRecord([handleConfirmAddPayRecordparams])
      ElMessage.success('新增出账记录成功')
      addPayRecordDialogVisible.value = false
      addPayRecordFormRef.value.resetForm()

    } 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('更新出账记录成功')
      addPayRecordDialogVisible.value = false
      addPayRecordFormRef.value.resetForm()
      editStatus.value = 'add'
    } catch (error) {
      ElMessage.error(error.message)
    }
  }

}
// 弹窗表单重置
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: 'currentPaymentAmount', label: '出账金额', width: '150' },
      { 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') {
    editStatus.value = 'edit'
    addPayRecordDialogVisible.value = true
    if (addPayRecordFormRef.value) {
      addPayRecordFormModel.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 () => {
  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
  loadTableData()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  loadTableData()
}

// 加载表格数据
const loadTableData = async () => {
  const searchParams = searchFormRef.value.getFormData() || {}
  loading.value = true
  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'])
  } 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;
}

</style>