<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 :value="statisticsData.totalAmount" :formatter="value=>formatCurrency(value)">
                                <template #title>
                                <div style="display: inline-flex; align-items: center">
                                    应收款总金额
                                </div>
                                </template>
                            </el-statistic>
                        </el-col>
                        <el-col :xs="24" :sm="12" :md="4" class="text-center mb-4">
                         <el-statistic :value="statisticsData.totalPaidAmount" :formatter="value=>formatCurrency(value)">
                                <template #title>
                                <div style="display: inline-flex; align-items: center">
                                    已入账金额
                                </div>
                                </template>
                            </el-statistic>
                        </el-col>
                        <el-col :xs="24" :sm="12" :md="4" class="text-center mb-4">
                        <el-statistic :value="statisticsData.pendingPaidAmount" :formatter="value=>formatCurrency(value)">
                                <template #title>
                                <div style="display: inline-flex; align-items: center">
                                    待入账金额（估）
                                </div>
                                </template>
                            </el-statistic>
                        </el-col>
                        <el-col :xs="24" :sm="12" :md="4" class="text-center mb-4">
                             <el-statistic :value="statisticsData.paidAmountRatio" :formatter="value=>formatCurrency(value,'',2)+'%'">
                                <template #title>
                                <div style="display: inline-flex; align-items: center">
                                    已入账比例
                                </div>
                                </template>
                            </el-statistic>
                        </el-col>
                        <el-col :xs="24" :sm="12" :md="4" class="text-center mb-4">
                            <el-statistic title="总保单数" :value="statisticsData.totalPolicyCount" />
                        </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 receivableReportTableColumns" :key="index" :fixed="column.fixed"
                        :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="false"
            :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" class="text-center mb-4">
                             <el-statistic :value="detailRecordStatistics.totalAmount" :formatter="value=>formatCurrency(value)">
                                <template #title>
                                <div style="display: inline-flex; align-items: center">
                                    应入账总金额
                                </div>
                                </template>
                            </el-statistic>
                     </el-col>
                     <el-col :xs="24" :sm="12" :md="4" class="text-center mb-4">
                             <el-statistic :value="detailRecordStatistics.totalPaidAmount" :formatter="value=>formatCurrency(value)">
                                <template #title>
                                <div style="display: inline-flex; align-items: center">
                                    已入账金额
                                </div>
                                </template>
                            </el-statistic>
                     </el-col>
                    <el-col :xs="24" :sm="12" :md="4" class="text-center mb-4">
                             <el-statistic :value="detailRecordStatistics.totalUnpaidAmount" :formatter="value=>formatCurrency(value)">
                                <template #title>
                                <div style="display: inline-flex; align-items: center">
                                    待入账金额
                                </div>
                                </template>
                            </el-statistic>
                     </el-col>
                      <el-col :xs="24" :sm="12" :md="4" class="text-center mb-4">
                             <el-statistic :value="detailRecordStatistics.paidAmountRatio" :formatter="value=>formatCurrency(value,'',2)+'%'">
                                <template #title>
                                <div style="display: inline-flex; align-items: center">
                                    已入账比例
                                </div>
                                </template>
                            </el-statistic>
                     </el-col>
                      <el-col :xs="24" :sm="12" :md="4" class="text-center mb-4">
                             <el-statistic :value="detailRecordStatistics.totalPolicyCount" >
                                <template #title>
                                <div style="display: inline-flex; align-items: center">
                                    总保单数
                                </div>
                                </template>
                            </el-statistic>
                     </el-col>
                      <el-col :xs="24" :sm="12" :md="4" class="text-center mb-4">
                             <el-statistic :value="detailRecordStatistics.totalPremium" :formatter="value=>formatCurrency(value)">
                                <template #title>
                                <div style="display: inline-flex; align-items: center">
                                    总保费
                                </div>
                                </template>
                            </el-statistic>
                     </el-col>
                </el-row>
            </div>
            <el-table :data="receivableReportTableData" border style="width: 100%;margin-bottom: 10px;min-height: 300px;">
                <el-table-column v-for="item in receivableReportItemTableColumns" :key="item.property" :prop="item.prop"
                    :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="entryRecordDialogTableVisible"
            :showAction="false" :showClose="true" @close="entryRecordDialogTableVisible = false">
            <el-table :data="entryRecordDialogTableData" border style="width: 100%">
                <el-table-column v-for="item in entryRecordDialogTableColumns" :key="item.property"
                    :prop="item.property" :label="item.label" :width="item.width" :formatter="item.formatter" />
                <el-table-column fixed="right" label="操作" min-width="120">
                    <template #default="scope">
                        <el-button link type="primary" size="small" @click="handleClick(scope.row)">
                            查看比对记录
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </CommonDialog>

        <CommonDialog dialogTitle="操作记录" dialogWidth="80%" :openDialog="actionRecordsDialogVisible" :showAction="false"
            :showClose="true" @close="actionRecordsDialogVisible = false">
            <el-table :data="actionRecordsDialogTableData" border style="width: 100%">
                <el-table-column v-for="item in actionRecordsDialogTableColumns" :key="item.property"
                    :prop="item.property" :label="item.label" :width="item.width"/>
            </el-table>
        </CommonDialog>

        <CommonDialog dialogTitle="设置入账状态" dialogWidth="80%" :openDialog="setStatusDialogTableVisible"
            @close="setStatusDialogTableVisible = false" @confirm="handleConfirmSetStatus">
            <SearchForm ref="setCommissionRecordStatusFormRef" :config="setCommissionRecordStatusFormConfig" />
        </CommonDialog>

        <!-- 新增应收款管理 -->
        <CommonDialog :dialogTitle="editStatus === 'add' ? '新增应收款' : '更新应收款'" dialogWidth="80%"
            :openDialog="addReceivablesDialogVisible"
            @close="addReceivablesDialogVisible = false; resetAddReceivablesForm()"
            @confirm="handleConfirmAddReceivables">
            <SearchForm ref="addRecordRef" :config="addReceivablesFormConfig" v-model="addReceivablesFormModel" />
        </CommonDialog>
    </div>
</template>

<script setup name="Receivables">
import CommonPage from '@/components/commonPage'
import CommonDialog from '@/components/commonDialog'
import { ref, reactive, onMounted, computed,nextTick  } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { MoreFilled } from '@element-plus/icons-vue'
import {
    receivedFortuneList, updateCommissionExpected, commissionEntryEditRecords,
    exportReceivedFortune, commissionExpectedRecord, addReceivedFortune, receivableReport
} from '@/api/financial/commission'
import { numberWithCommas } from '@/utils/index'
import SearchForm from '@/components/SearchForm/SearchForm.vue'
import { loadDicts, getDictLabel } from '@/utils/useDict'
import { safeDownload } from '@/utils/safeDownload'
import useUserStore from '@/store/modules/user'
import { formatCurrency } from '@/utils/number'

const userStore = useUserStore()
// 应收单类型
const commissionBizTypeOptions = [
    { value: 'R', label: '关联保单应收单' },
    { value: 'U', label: '非关联保单应收单' }
]
const editStatus = ref('add')

// 新增应收款管理
const addReceivablesFormModel = ref({
    commissionBizType: 'U',
})
const addReceivablesDialogVisible = ref(false)
const addRecordRef = ref(null)
const addReceivablesFormConfig = [
    {
        type: 'select',
        prop: 'commissionBizType',
        label: '应收单类型',
        placeholder: '应收单类型',
        options: commissionBizTypeOptions
    },
    {
        type: 'input',
        prop: 'policyNo',
        label: '保单号',
        visible: (formData) => formData.commissionBizType == 'R'
    }, {
        type: 'input',
        prop: 'commissionPeriod',
        label: '佣金期数',
        inputType: 'decimal',
        visible: (formData) => formData.commissionBizType === 'R',
        rules: [
            { 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: '请选择'
    },
    //  {
    //     type: 'date',
    //     prop: 'actualCommissionDate',
    //     label: '入账日（实）',
    //     placeholder: '请选择',
    //     maxDate: 'today'
    // }, 
    {
        type: 'input',
        prop: 'amount',
        label: '入账金额',
        inputType: 'decimal',
        decimalDigits: 4,
        visible: (formData) => formData.commissionBizType === 'U',
        rules: [
            { required: true, message: '请输入金额', trigger: 'blur' },
            { pattern: /^\d+(\.\d{1,4})?$/, message: '最多四位小数', trigger: 'blur' }
        ]
    }, {
        type: 'input',
        prop: 'commissionRatio',
        label: '入账比例（%）',
        inputType: 'decimal',
        decimalDigits: 4,
        visible: (formData) => formData.commissionBizType === 'R',
        rules: [
            { required: true, message: '请输入入账比例', trigger: 'blur' },
            { pattern: /^\d+(\.\d{1,4})?$/, message: '最多四位小数', trigger: 'blur' }
        ]
    }, {
        type: 'select',
        prop: 'currency',
        label: '入账币种',
        dictType: 'bx_currency_type'
    }, {
        type: 'select',
        prop: 'commissionType',
        label: '入账项目',
        dictType: 'csf_commission_type',
        onChangeExtraFields: {
            commissionName: 'itemLabel',
        },
    }, {
        type: 'select',
        prop: 'reconciliationCompanyBizId',
        label: '对账公司',
        api: '/insurance/base/api/insuranceReconciliationCompany/page',
        keywordField: 'name',
        requestParams: { pageNo: 1, pageSize: 20 },
        placeholder: '输入对账公司名称搜索',
        debounceWait: 500, // 自定义防抖时间
        valueKey: 'reconciliationCompanyBizId',
        labelKey: 'name',
        onChangeExtraFields: {
            reconciliationCompany: 'name',// 自动同步 raw.name 到 reconciliationCompany
            reconciliationCompanyCode: 'code'
        },
        transform: (res) => {
            console.log('对账公司', res)
            return res.data.records || []
        }
    }
]
// 弹窗表单重置
const resetAddReceivablesForm = () => {
    addRecordRef.value.resetForm()
    editStatus.value = 'add'
}



const handleConfirmAddReceivables = async () => {
    if (editStatus.value === 'add') {
        const p = addRecordRef.value.getFormData()
        try {
            await addReceivedFortune({
                commissionExpectedAddDtoList: [p]
            })
            ElMessage.success('新增应收款成功')
            addReceivablesDialogVisible.value = false
            resetAddReceivablesForm()
            handleQuery()
        } catch (error) {
            ElMessage.error(error.message)
        }
    } else {
        try {
            const res = await updateCommissionExpected({
                commissionExpectedBizId: selectedRow.value.commissionExpectedBizId,
                ...addReceivablesFormModel.value
            })
            if (res.code === 200) {
                ElMessage.success('应收款修改成功')
                addReceivablesDialogVisible.value = false
                resetAddReceivablesForm()
                loadTableData() // 重新加载表格
            } else {
                ElMessage.error(res.msg || '应收款修改失败')
            }
        } catch (error) {
            console.error('修改应收款失败:', error)
            ElMessage.error('修改应收款失败')
        }
    }


}


const searchFormRef = ref(null)
const searchParams = ref({})
const searchConfig = ref([
    {
        type: 'input',
        prop: 'policyNo',
        label: '保单号'
    },
    {
        type: 'daterange',
        prop: 'entryDate',
        label: '入账日（估）',
        startPlaceholder: '开始时间',
        endPlaceholder: '结束时间'
    },
    {
        type: 'select',
        prop: 'statusList',
        label: '入账状态',
        multiple: true,
        dictType: 'csf_expected_commission_status'
    },
    {
        type: 'input',
        prop: 'commissionPeriod',
        label: '入账期数',
        inputType: 'decimal',
        rules: [
            { pattern: /^\d+$/, message: '只能输入正整数', trigger: 'blur' }
        ]
    },
    {
        type: 'select',
        prop: 'fortuneName',
        label: '入账项目',
        dictType: 'csf_commission_type'
    },
    {
        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: 'select',
        prop: 'insurerCompanyBizIdList',
        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) => {
            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: 'commissionBizType',
        label: '应收单类型',
        options: commissionBizTypeOptions,
    }, {
        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 currentPage = ref(1)
const pageSize = ref(10)
const pageTotal = ref(0)
const loading = ref(false)


// 应收单类型通过value转成label
const getCommissionBizTypeLabel = (value) => {
    const item = commissionBizTypeOptions.find(item => item.value === value)
    return item?.label || ''
}

// 表格操作菜单
const dropdownItems = [
    { label: '入账记录', value: 'entryRecord' },
    { label: '设置状态', value: 'setStatus' },
    { label: '更新数据', value: 'updateData' },
]

// 弹窗状态
const entryRecordDialogTableVisible = ref(false)
const setStatusDialogTableVisible = ref(false)
const actionRecordsDialogVisible = ref(false)

// 弹窗表格数据
const actionRecordsDialogTableData = ref([])
const entryRecordDialogTableData = ref([])
const entryRecordDialogTableColumns = ref([])
const actionRecordsDialogTableColumns = ref([])

// 设置入账状态表单
const setCommissionRecordStatusFormRef = ref(null)
const setCommissionRecordStatusFormConfig = ref([])
const selectedRow = ref(null)

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

// 统计信息
const statisticsData = ref({
    totalAmount: 0,
    totalPaidAmount: 0,
    pendingPaidAmount: 0,
    paidAmountRatio: 0,
    totalPolicyCount: 0
})

// 按钮事件处理
const handleAdd = () => {
    addReceivablesDialogVisible.value = true
    if (addRecordRef.value) {
        addRecordRef.value.resetForm()
    }
    addReceivablesFormModel.value = {}
}

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

const handleExport = async () => {
    // 获取搜索参数
    const params = searchFormRef.value?.getFormData() || {}
    const response = await exportReceivedFortune(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 = () => {
    loadTableData()
}
const visibleDefaultButtons = ref([
    'add', 'export', 'reset', 'query'
])
// 按钮配置
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,
            commissionDateStart: searchParams?.entryDate?.[0] || undefined,
            commissionDateEnd: searchParams?.entryDate?.[1] || undefined,
            entryDate: undefined,
            pageNo: currentPage.value,
            pageSize: pageSize.value
        }
        const response = await receivableReport(params)
        tableData.value = response.data.page.records || []
        pageTotal.value = response.data.page.total || 0
        pageSize.value = response.data.page.size || 50

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

// 入账记录查询
const loadEntryRecordData = async (cbd) => {
    loading.value = true
    try {
        const params = { commissionExpectedBizId: cbd }
        const response = await commissionExpectedRecord(params)
        return response.data.records || []
    } catch (error) {
        console.error('加载入账记录失败:', error)
        ElMessage.error('加载入账记录失败')
        return []
    } finally {
        loading.value = false
    }
}

// 入账操作记录查询
const loadEntryEditRecordData = async (cbd) => {
    loading.value = true
    try {
        const params = { commissionBizId: cbd }
        const response = await commissionEntryEditRecords(params)
        return response.data.records || []
    } catch (error) {
        console.error('加载操作记录失败:', error)
        ElMessage.error('加载操作记录失败')
        return []
    } finally {
        loading.value = false
    }
}

// 操作菜单选择事件
const handleSelect = async (e, row) => {
    selectedRow.value = { ...row }
    if (e === 'entryRecord') {
        entryRecordDialogTableVisible.value = true
        entryRecordDialogTableColumns.value = [
            { property: 'reconciliationYearMonth', label: '检核年月', width: '100' },
            { property: 'commissionPeriod', label: '佣金期数', width: '100' },
            { property: 'totalPeriod', label: '总期数', width: '150' },
            { property: 'exchangeRate', label: '结算汇率（实）', width: '150' },
            { property: 'currency', label: '入账币种', width: '150' },
            { property: 'amount', label: '入账金额', width: '150',formatter:(row)=> formatCurrency(row.amount || 0) },
            { property: 'currentCommissionRatio', label: '入账比例', width: '150', formatter: (row) => `${row.currentCommissionRatio || ''}%` },
            { property: 'commissionDate', label: '入账日', width: '150' },
            { property: 'commissionStatusName', label: '入账状态', width: '150' }
        ]
        // 加载真实数据
        const records = await loadEntryRecordData(row.commissionExpectedBizId)
        entryRecordDialogTableData.value = records.length ? records : []
    } else if (e === 'setStatus') {
        console.log(selectedRow.value.status)
        setCommissionRecordStatusFormConfig.value = [
            {
                type: 'select',
                prop: 'status',
                label: '入账状态',
                dictType: 'csf_expected_commission_status',
                defaultValue: selectedRow.value.status || ''
            }, {
                type: 'textarea',
                prop: 'statusDesc',
                label: '修改理由',
                defaultValue: selectedRow.value.statusDesc || ''
            },
        ]
        setStatusDialogTableVisible.value = true
    } else if (e === 'updateData') {
        editStatus.value = 'update'
        addReceivablesDialogVisible.value = true
          // 2. 使用 nextTick 等待 DOM 更新
        nextTick(() => {
            // 3. 此时 addRecordRef.value 一定存在了
            if (addRecordRef.value && selectedRow.value) {
                addReceivablesFormModel.value = { ...selectedRow.value };
                console.log('赋值成功:', addReceivablesFormModel.value);
            }
        });
        console.log('更新数据', selectedRow.value)
    }
}


// 查看比对记录
const handleClick = async (row) => {
    actionRecordsDialogVisible.value = true
    actionRecordsDialogTableColumns.value = [
        { property: 'checkMonth', label: '检核年月', width: '100' },
        { property: 'compareStatus', label: '比对状态', width: '150' },
        { property: 'entryRatio', label: '入账比例', width: '150' },
        { property: 'shouldEntryRatio', label: '应入账比例', width: '150' },
        { property: 'reconciliationCompany', label: '对账公司', width: '150' },
        { property: 'createTime', label: '比对时间', width: '150' },
        { property: 'userName', label: '比对人', width: '150' }
    ]
    // 加载真实数据
    const records = await loadEntryEditRecordData(row.commissionBizId)
    actionRecordsDialogTableData.value = records.length ? records : []
}

// 新增：设置状态确认事件
const handleConfirmSetStatus = () => {
    const formData = setCommissionRecordStatusFormRef.value.getFormData()
    if (!formData.status) {
        return ElMessage.warning('请选择入账状态')
    }
    if (!formData.statusDesc) {
        return ElMessage.warning('请输入修改理由')
    }
    // 调用接口修改状态（示例）
    ElMessageBox.confirm('确定要修改入账状态吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        try {
            const res = await updateCommissionExpected({
                commissionExpectedBizId: selectedRow.value.commissionExpectedBizId,
                ...formData
            })
            if (res.code === 200) {
                ElMessage.success('状态修改成功')
                setStatusDialogTableVisible.value = false
                loadTableData() // 重新加载表格
            } else {
                ElMessage.error(res.msg || '状态修改失败')
            }
        } catch (error) {
            console.error('修改状态失败:', error)
            ElMessage.error('修改状态失败')
        }
    }).catch(() => {
        ElMessage.info('已取消修改')
    })
}
// 获取入账状态,字典值转化方法
onMounted(async () => {
    try {
        await loadDicts(['csf_expected_commission_status'])
        loadTableData()
    } catch (error) {
        console.error('字典加载失败', error)
    } finally {
        loading.value = false
    }
})
// 格式化函数（每次渲染都会调用，所以能拿到最新字典）
const formatStatus = (row,column) => {
    return getDictLabel('csf_expected_commission_status', row.status) // 实时查缓存
}
const detailDialogVisible = ref(false)
const receivableReportTableData = ref([])
const receivableReportTableColumns = ref([
    { prop: 'policyNo', label: '保单号', sortable: true, width: '150',fixed:'left', formatter: (row) => row.policyNo || '-' },
    { prop: 'reconciliationCompany', label: '对账公司', sortable: true, width: '150', formatter: (row) => row.reconciliationCompany || '-' },
    { prop: 'commissionPeriod', label: '入账期数', sortable: true, width: '100', formatter: (row) => row.commissionPeriod || '-' },
    { prop: 'totalPeriod', label: '入账总期数', sortable: true, width: '100', formatter: (row) => row.totalPeriod || '-' },
    { prop: 'commissionDate', label: '入账日（估）', sortable: true, width: '130', },
    { 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: 'paidRatio', label: '已入账比例', sortable: true, width: '120', formatter: (row) => (row.paidRatio || 0) + '%' || '-' },
    { prop: 'paidAmount', label: '已入账金额HKD', 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: '待入账金额HKD', sortable: true, width: '120', formatter: (row) => formatCurrency(row.unpaidAmount || 0) },
    { prop: 'exchangeRate', label: '结算汇率（估）', sortable: true, width: '120'},
    { prop: 'insuranceCompany', label: '保险公司', sortable: true, width: '120', formatter: (row) => row.insuranceCompany || '-' },
    { prop: 'productName', label: '产品计划', sortable: true, width: '120', formatter: (row) => row.productName || '-' },
    { prop: 'premium', label: '期交保费', sortable: true, width: '120', formatter: (row) => formatCurrency(row.premium || 0) },
    { prop: 'policyCurrency', label: '保单币种', sortable: true, width: '120', formatter: (row) => row.policyCurrency || '-' },
])
// 应收明细
const receivableReportItemTableColumns = ref([
    { prop: 'commissionBizType', label: '应收单类型', sortable: true, width: '150', formatter: (row) => getCommissionBizTypeLabel(row.commissionBizType) || '-' },
    { prop: 'receivableNo', label: '应收款编号', sortable: true, width: '150', formatter: (row) => row.receivableNo || '-' },
    { prop: 'policyNo', label: '保单号', sortable: true, width: '150', formatter: (row) => row.policyNo || '-' },
    { prop: 'reconciliationCompany', label: '对账公司', sortable: true, width: '150', formatter: (row) => row.reconciliationCompany || '-' },
    { prop: 'status', label: '入账状态', sortable: true, width: '120', formatter: (row) => formatStatus(row) || '-' },
    { prop: 'commissionPeriod', label: '入账期数', sortable: true, width: '120', formatter: (row) => row.commissionPeriod || '-' },
    { prop: 'totalPeriod', label: '入账总期数', sortable: true, width: '120', formatter: (row) => row.totalPeriod || '-' },
    { prop: 'commissionName', label: '入账项目', sortable: true, width: '130', formatter: (row) => row.commissionName || '-' },
    { prop: 'commissionDate', label: '入账日（估）', sortable: true, width: '130', formatter: (row) => row.commissionDate || '-' },
    { prop: 'commissionRatio', label: '产品对应来佣率', sortable: true, width: '120', formatter: (row) => (row.commissionRatio || 0) + '%' || '-' },
    { prop: 'expectedAmount', label: '预估入账金额', sortable: true, width: '120', formatter: (row) => formatCurrency(row.expectedAmount || 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: 'pendingRatio', label: '实佣率缺口', sortable: true, width: '120', formatter: (row) => (row.pendingRatio || 0) + '%' || '-' },
    { prop: 'pendingAmount', label: '待入账金额', sortable: true, width: '120', formatter: (row) => formatCurrency(row.pendingAmount || 0) },
    { prop: 'defaultExchangeRate', label: '结算汇率（估）', sortable: true, width: '120'},
    { prop: 'insuranceCompany', label: '保险公司', sortable: true, width: '120', formatter: (row) => row.insuranceCompany || '-' },
    { prop: 'productName', label: '产品计划', sortable: true, width: '120', formatter: (row) => row.productName || '-' },
    { prop: 'premium', label: '期交保费', sortable: true, width: '120', formatter: (row) => formatCurrency(row.premium || 0) },
    { prop: 'policyCurrency', label: '保单币种', sortable: true, width: '120', formatter: (row) => row.policyCurrency || '-' },
    { prop: 'currency', label: '入账币种', sortable: true, width: '120', formatter: (row) => row.currency || '-' },
    { prop: 'statusDesc', label: '入账状态修改理由', sortable: true, width: '120', formatter: (row) => row.statusDesc || '-' },
    { prop: 'remark', label: '备注', sortable: true, width: '120', formatter: (row) => row.remark || '-' },
])

const detailRecordStatistics = ref({})
const detailPageInfo = ref({
    pageNo: 1,
    pageSize: 10,
    currentPage: 1,
    total: 0
})

// 获取入账报告
const receivedFortuneListData = async () => {
    loading.value = true
    try {
        const params = {
            policyNo: selectedDetailRecordRow.value.policyNo,
            commissionPeriod: selectedDetailRecordRow.value.commissionPeriod,
            receivableNo: selectedDetailRecordRow.value.receivableNo,
            pageNo: detailPageInfo.value.currentPage,
            pageSize: detailPageInfo.value.pageSize
        }
        const response = await receivedFortuneList(params)
        receivableReportTableData.value = response.data.page.records || []
        detailPageInfo.value.total = response.data.page.total || 0
        detailPageInfo.value.pageSize = response.data.page.size || 50
        // 统计信息
        detailRecordStatistics.value = {
            totalAmount: response.data.expectedStatisticsVO.totalAmount,
            totalPaidAmount: response.data.expectedStatisticsVO.totalPaidAmount,
            pendingPaidAmount: response.data.expectedStatisticsVO.pendingPaidAmount,
            paidAmountRatio: response.data.expectedStatisticsVO.paidAmountRatio,
            totalPolicyCount: response.data.expectedStatisticsVO.totalPolicyCount,
            totalPremium: response.data.expectedStatisticsVO.totalPremium
        }
    } catch (error) {
        console.error('加载数据失败:', error)
        ElMessage.error('加载数据失败')
    } finally {
        loading.value = false
    }
}
const selectedDetailRecordRow = ref({})
const viewDetail = (row) => {
    selectedDetailRecordRow.value = row
    detailDialogVisible.value = true
    receivedFortuneListData()
}
// 分页事件
const handleSizeChangeDetailRecord = (val) => {
    detailPageInfo.value.pageSize = val
    receivedFortuneListData()
}
// 分页事件
const handleCurrentChangeDetailRecord = (val) => {
    detailPageInfo.value.currentPage = val
    receivedFortuneListData()
}
</script>

<style scoped lang="scss"></style>