<template>
    <div>
        <CommonPage :operationBtnList="operationBtnList" :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.totalAmount" />
                        </el-col>
                        <el-col :xs="24" :sm="12" :md="4" class="text-center mb-4">
                            <el-statistic title="已入账金额" :value="statisticsData.totalPaidAmount" />
                        </el-col>
                        <el-col :xs="24" :sm="12" :md="4" class="text-center mb-4">
                            <el-statistic title="待入账金额（估）" :value="statisticsData.pendingPaidAmount" />
                        </el-col>
                        <el-col :xs="24" :sm="12" :md="4" class="text-center mb-4">
                            <el-statistic title="已入账比例" :value="statisticsData.paidAmountRatio" />
                        </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 prop="commissionBizType" label="应收单类型" width="130" sortable>
                        <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" fixed="left" sortable />
                    <el-table-column prop="reconciliationCompany" label="对账公司" width="120" sortable />
                    <el-table-column prop="status" label="入账状态" width="120" sortable>
                        <template #default="{ row }">
                            {{ getDictLabel('csf_expected_commission_status', row.status) }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="commissionPeriod" label="入账期数" width="120" sortable />
                    <el-table-column prop="totalPeriod" label="入账总期数" width="120" sortable />
                    <el-table-column prop="commissionName" label="入账项目" width="120" sortable />
                    <el-table-column prop="commissionDate" label="入账日(估)" width="120" sortable />
                    <el-table-column prop="commissionRatio" label="入账比例(估)" width="140" sortable>
                        <template #default="{ row }">
                            {{ (row.commissionRatio || 0) + '%' }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="expectedAmount" label="入账金额(估)" width="140" sortable>
                        <template #default="{ row }">
                            {{ numberWithCommas(row.expectedAmount) }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="paidRatio" label="已入账比例" width="120" sortable>
                        <template #default="{ row }">
                            {{ (row.paidRatio || 0) + '%' }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="paidAmount" label="已入账金额" width="120" sortable>
                        <template #default="{ row }">
                            {{ numberWithCommas(row.paidAmount) }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="pendingRatio" label="待入账比例" width="120" sortable>
                        <template #default="{ row }">
                            {{ (row.pendingRatio || 0) + '%' }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="pendingPaidAmount" label="待入账金额（估）" width="160" sortable>
                        <template #default="{ row }">
                            {{ numberWithCommas(row.pendingPaidAmount) }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="currency" label="入账币种" width="100" />
                    <el-table-column prop="defaultExchangeRate" label="结算汇率（估）" width="120" />
                    <el-table-column prop="insurerBizId" label="保险公司" width="120" sortable />
                    <el-table-column prop="productLaunchBizId" label="产品计划" width="120" sortable />
                    <el-table-column prop="premium" label="期交保费" width="120" sortable>
                        <template #default="{ row }">
                            {{ numberWithCommas(row.premium) }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="statusDesc" label="入账状态修改理由" width="150" />
                    <el-table-column prop="remark" label="备注" width="150" />
                    <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>
            </template>
        </CommonPage>

        <!-- 原有弹窗（不变） -->
        <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" />
                <el-table-column fixed="right" label="操作" min-width="120">
                    <template #default>
                        <el-button link type="primary" size="small" @click="handleClick">
                            查看比对记录
                        </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="新增应收款" dialogWidth="80%" :openDialog="addReceivablesDialogVisible"
            @close="addReceivablesDialogVisible = false" @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 } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { MoreFilled } from '@element-plus/icons-vue'
import { receivedFortuneList, updateCommissionExpected, commissionEntryEditRecords, exportReceivedFortune, commissionExpectedRecord, addReceivedFortune } from '@/api/financial/commission'
import { numberWithCommas } from '@/utils/index'
import SearchForm from '@/components/SearchForm/SearchForm.vue'
import { getDictLabel } from '@/utils/useDict';
import { safeDownload } from '@/utils/safeDownload'
import useUserStore from '@/store/modules/user'

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

// 新增应收款管理
const addReceivablesFormModel = reactive({
    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: 2,
        rules: [
            { required: true, message: '请输入金额', trigger: 'blur' },
            { pattern: /^\d+(\.\d{1,2})?$/, message: '最多两位小数', trigger: 'blur' }
        ]
    }, {
        type: 'select',
        prop: 'currency',
        label: '入账币种',
        dictType: 'bx_currency_type'
    }, {
        type: 'select',
        prop: 'commissionName',
        label: '入账项目',
        dictType: 'csf_commission_type'
    }, {
        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',
        transform: (res) => {
            console.log('对账公司', res)
            return res.data.records || []
        }
    }
]

const handleConfirmAddReceivables = async () => {
    const p = addRecordRef.value.getFormData()
    console.log('新增应收款', p)
    try {
        await addReceivedFortune({
            commissionExpectedAddDtoList: [p]
        })
        ElMessage.success('新增应收款成功')
        addReceivablesDialogVisible.value = false
        handleSearch()
    } catch (error) {
        ElMessage.error(error.message)
    }

}


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: 'abbreviation',
        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' }
]

// 弹窗状态
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
}
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 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 receivedFortuneList(params)
        tableData.value = response.data.page.records || []
        pageTotal.value = response.data.page.total || 0
        pageSize.value = response.data.page.size || 10

        // 统计信息
        statisticsData.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
        }
    } 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' },
            { property: 'currentCommissionRatio', label: '入账比例', width: '150' },
            { property: 'commissionDate', label: '入账日', width: '150' },
            { property: 'status', 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
    }
}


// 查看比对记录
const handleClick = async () => {
    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(selectedRow.value.commissionExpectedBizId)
    actionRecordsDialogTableData.value = records.length ? records : [{
        checkMonth: '2023-08',
        compareStatus: '比对成功',
        entryRatio: '10%',
        shouldEntryRatio: '10%',
        reconciliationCompany: 'XX保险公司',
        createTime: '2023-08-01 10:00:00',
        userName: '张三'
    }]
}

// 新增：设置状态确认事件
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('已取消修改')
    })
}

</script>

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