<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" v-model="searchFormData" :fields="searchFields" label-position="top"
                    :label-width="null" :inline="false" :gutter="20" class="custom-search-form" />
                    {{ searchFormData }}
            </template>
            <!-- 列表区域 -->
            <template #table>
                <!-- 统计信息卡片 -->
                <div class="statistics-cards" 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="120" fixed="left" sortable />
                    <el-table-column prop="receivableNo" label="应收款编号" width="120" />
                    <el-table-column prop="policyNo" label="保单号" width="120" />
                    <el-table-column prop="reconciliationCompany" label="对账公司" width="120" sortable />
                    <el-table-column prop="status" label="入账状态" width="120" sortable>
                        <template #default="{ row }">
                            <el-tag :type="row.status === '1' ? 'success' : 'warning'">
                                {{ row.status === '1' ? '已入账' : '待入账' }}
                            </el-tag>
                        </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="commissionType" 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 }">
                            {{ formatCurrency(row.expectedAmount) }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="paidAmountRatio" label="已入账比例" width="120" sortable>
                        <template #default="{ row }">
                            {{ (row.paidAmountRatio || 0) + '%' }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="paidAmount" label="已入账金额" width="120" sortable>
                        <template #default="{ row }">
                            {{ formatCurrency(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 }">
                            {{ formatCurrency(row.pendingPaidAmount) }}
                        </template>
                    </el-table-column>
                    <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 }">
                            {{ formatCurrency(row.premium) }}
                        </template>
                    </el-table-column>
                    <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"
                    :property="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"
                    :property="item.property" :label="item.label" :width="item.width" />
            </el-table>
        </CommonDialog>

        <!-- 设置状态 弹窗-->
        <CommonDialog dialogTitle="设置入账状态" dialogWidth="80%" :openDialog="setStatusDialogTableVisible"
            @close="setStatusDialogTableVisible = false" @confirm="setStatusDialogTableVisible = false">
            <el-form :model="form">
                <el-form-item label="入账状态" label-width="120">
                    <el-select v-model="form.status" placeholder="请选择入账状态">
                        <el-option label="Zone No.1" value="shanghai" />
                        <el-option label="Zone No.2" value="beijing" />
                    </el-select>
                </el-form-item>
                <el-form-item label="修改理由" :label-width="120">
                    <el-input v-model="form.desc" type="textarea" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="setStatusDialogTableVisible = false">取消</el-button>
                    <el-button type="primary" @click="setStatusDialogTableVisible = false">
                        确认
                    </el-button>
                </div>
            </template>
        </CommonDialog>
    </div>


</template>

<script setup name="Receivables">
import CommonPage from '@/components/commonPage'
import CommonDialog from '@/components/commonDialog'
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { formatCurrency } from '@/utils/number'
import { receivedFortuneList, commissionEntryRecord, commissionEntryEditRecords } from '@/api/financial/commission'
import SearchForm from '@/components/SearchForm/index.vue'
// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const pageTotal = ref(0)
const loading = ref(false)
// 表格操作菜单
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 form = reactive({
    status: '',
    desc: '',
})

const selectedRow = ref(null)
const handleSelect = (e, row) => {
    selectedRow.value = row
    if (e === 'entryRecord') {
        // 入账记录
        entryRecordDialogTableVisible.value = true
        entryRecordDialogTableColumns.value = [
            { 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: 'commissionPeriod', label: '入账比例', width: '150' },
            { property: 'commissionPeriod', label: '入账日', width: '150' },
            { property: 'status', label: '入账状态', width: '150' }
        ]
        // 加载入账记录-假数据等待接口修改
        loadEntryRecordData(selectedRow.value.commissionExpectedBizId).then(records => {
            console.log(records)
            entryRecordDialogTableData.value = records =
                [{
                    commissionPeriod: '2023-08-01',
                    totalPeriod: '2023-08-31',
                    exchangeRate: '1.2345',
                    currency: '假数据，等接口改CNY',
                    amount: '10000.00',
                    commissionPeriod: '10%',
                    commissionPeriod: '2023-08-01',
                    status: '已入账'
                }]
        })
    } else if (e === 'setStatus') {
        setStatusDialogTableVisible.value = true
    }
}
const handleClick = () => {
    actionRecordsDialogVisible.value = true
    actionRecordsDialogTableColumns.value = [
        { 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: 'createTime', label: '比对时间', width: '150' },
        { property: 'userName', label: '比对人', width: '150' }
    ]
    // 加载入账操作记录-假数据等待接口修改
    loadEntryEditRecordData(selectedRow.value.commissionExpectedBizId).then(records => {
        actionRecordsDialogTableData.value = records =
            [{
                commissionPeriod: '2023-08-01',
                totalPeriod: '2023-08-31',
                exchangeRate: '1.2345',
                currency: '假数据，等接口改CNY',
                amount: '10000.00',
                commissionPeriod: '10%',
                commissionPeriod: '2023-08-01',
                status: '已入账'
            }]
    })
}

// 搜索表单数据 - 修正字段名
const searchFormData = reactive({
    policyNo: '',
    incomeDateRange: [], // 改为数组格式
    statusList: [],
    commissionNameList: [], // 修改字段名
    commissionPeriod: '',
    reconciliationCompanyList: [], // 修改字段名
    insurerBizId: [],
    productLaunchBizId: [],
    commissionBizType: '',
    teamBizId: '',
})

const searchFields = ref([
    {
        type: 'input',
        field: 'policyNo',
        label: '保单号',
        placeholder: '请输入保单号',
        colSpan: 6,
        clearable: true,
        rules: [
            { max: 50, message: '保单号长度不能超过50个字符', trigger: 'blur' }
        ]
    },
    {
        type: 'daterange',
        field: 'incomeDateRange',
        label: '入账日期',
        startPlaceholder: '开始日期',
        endPlaceholder: '结束日期',
        colSpan: 6,
        dateFormat: 'YYYY-MM-DD',
        props: {
            valueFormat: 'YYYY-MM-DD',
            style: 'width: 100%'
        }
    },
    {
        type: 'multi-select',
        field: 'statusList',
        label: '入账状态',
        placeholder: '请选择入账状态',
        colSpan: 6,
        options: [
            { label: '已入账', value: '1' },
            { label: '待入账', value: '0' },
            { label: '部分入账', value: '2' }
        ]
    },
    {
        type: 'input',
        field: 'commissionNameList',
        label: '入账项目',
        placeholder: '请输入关键词搜索',
        colSpan: 6,
    },
    {
        type: 'remote-multi-select',
        field: 'reconciliationCompanyList',
        label: '对账公司',
        placeholder: '请输入关键词搜索',
        colSpan: 6,
        remoteConfig: {
            type: 'company',
            defaultOptions: []
        }
    },
    {
        type: 'input',
        field: 'commissionPeriod',
        label: '入账期数',
        placeholder: '请输入期数',
        colSpan: 6,
    },
    {
        type: 'input',
        field: 'insurerBizId',
        label: '保险公司',
        placeholder: '请输入关键词搜索保险公司',
        colSpan: 6,
    },
    {
        type: 'input',
        field: 'productLaunchBizId',
        label: '产品计划',
        placeholder: '请输入关键词搜索产品计划',
        colSpan: 6,
    },
    {
        type: 'select',
        field: 'commissionBizType',
        label: '应收款类型',
        placeholder: '请选择应收款类型',
        colSpan: 6,
        options: [
            { label: '关联保单应收单', value: '1' },
            { label: '非关联保单应收单', value: '2' }
        ]
    },
    {
        type: 'input',
        field: 'teamBizId',
        label: '出单团队',
        placeholder: '请输入关键词搜索出单团队',
        colSpan: 6,
    }
])

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

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

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

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

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

const handleReset = () => {
    // 重置搜索表单
    Object.keys(searchFormData).forEach(key => {
        if (Array.isArray(searchFormData[key])) {
            searchFormData[key] = []
        } else {
            searchFormData[key] = ''
        }
    })
    ElMessage.success('搜索条件已重置')
    // 重新加载数据
    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 () => {
    console.log(searchFormData)
    loading.value = true
    try {
        const params = {
            ...searchFormData,
            currentPage: 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,
            paidAmountRatio: response.data.expectedStatisticsVO.paidAmountRatio
        }

    } catch (error) {
        console.error('加载数据失败:', error)
        // ElMessage.error('加载数据失败')
    } finally {
        loading.value = false
    }
}

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



// 初始化加载数据
loadTableData()
</script>

<style scoped lang="scss">
.statistics-cards {
    margin-bottom: 5px;
    background: RGBA(0, 82, 217, 0.03);
    border-radius: 8px;
    padding: 10px 20px;
}

.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;
}

.el-menu {
    border: none;
}
</style>