<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>
                <el-form :model="searchFormData" label-width="120px">
                    <el-row :gutter="20">
                        <!-- 原有搜索项 -->
                        <el-col :xs="24" :sm="12" :md="8" :lg="6">
                            <el-form-item label="保单号" prop="policyNo" label-position="top">
                                <el-input v-model="searchFormData.policyNo" placeholder="请输入保单号" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="12" :md="8" :lg="6">
                            <el-form-item label="入账日（估）" prop="incomeDateRange" label-position="top">
                                <el-date-picker 
                                    v-model="searchFormData.incomeDateRange" 
                                    type="daterange"
                                    value-format="yyyy-MM-dd" 
                                    range-separator="至" 
                                    start-placeholder="开始日期"
                                    end-placeholder="结束日期" 
                                />
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="12" :md="8" :lg="6">
                            <el-form-item label="入账状态" prop="statusList" label-position="top">
                                <el-select v-model="searchFormData.statusList" placeholder="请选择入账状态" clearable multiple>
                                    <el-option label="待入账" value="0" />
                                    <el-option label="完成入账" value="1" />
                                    <el-option label="部分入账" value="2" />
                                    <el-option label="已失效" value="3" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="12" :md="8" :lg="6">
                            <el-form-item label="入账期数" prop="commissionPeriod" label-position="top">
                                <el-input v-model="searchFormData.commissionPeriod" placeholder="请输入入账期数" clearable />
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="12" :md="8" :lg="6">
                            <el-form-item label="入账项目" prop="commissionName" label-position="top">
                                <el-input v-model="searchFormData.commissionName" placeholder="请输入入账项目" clearable />
                            </el-form-item>
                        </el-col>
                        
                        <!-- 新增：保险公司远程搜索下拉 -->
                        <el-col :xs="24" :sm="12" :md="8" :lg="6">
                            <el-form-item label="保险公司" prop="insurerBizId" label-position="top">
                                <el-select 
                                    v-model="searchFormData.insurerBizId" 
                                    placeholder="请选择保险公司" 
                                    clearable
                                    :remote-method="(keyword) => remoteMethod('insurer', keyword)" 
                                    :loading="options.insurer.loading" 
                                    filterable 
                                    remote
                                    reserve-keyword
                                >
                                    <el-option 
                                        v-for="item in options.insurer.options" 
                                        :key="item.value"
                                        :label="item.label" 
                                        :value="item.value" 
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col>

                        <!-- 新增：产品计划远程搜索下拉 -->
                        <!-- <el-col :xs="24" :sm="12" :md="8" :lg="6">
                            <el-form-item label="产品计划" prop="productLaunchBizId" label-position="top">
                                <el-select 
                                    v-model="searchFormData.productLaunchBizId" 
                                    placeholder="请选择产品计划" 
                                    clearable
                                    :remote-method="(keyword) => remoteMethod('product', keyword)" 
                                    :loading="options.product.loading" 
                                    filterable 
                                    remote
                                    reserve-keyword
                                >
                                    <el-option 
                                        v-for="item in options.product.options" 
                                        :key="item.bizId"
                                        :label="item.productName" 
                                        :value="item.bizId" 
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col> -->

                        <el-col :xs="24" :sm="12" :md="8" :lg="6">
                            <el-form-item label="应收单类型" prop="commissionBizType" label-position="top">
                                <el-select v-model="searchFormData.commissionBizType" placeholder="请选择应收单类型" clearable>
                                    <el-option label="关联保单应收单" value="R" />
                                    <el-option label="非关联保单应收单" value="U" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <!-- 新增：出单团队远程搜索下拉 -->
                        <el-col :xs="24" :sm="12" :md="8" :lg="6">
                            <el-form-item label="对账公司" prop="reconciliationCompanyBizId" label-position="top">
                                <el-select 
                                    v-model="searchFormData.reconciliationCompany" 
                                    placeholder="请选择对账公司" 
                                    clearable
                                    :remote-method="(keyword) => remoteMethod('reconciliationCompany', keyword)" 
                                    :loading="options.reconciliationCompany.loading" 
                                    filterable 
                                    remote
                                    reserve-keyword
                                >
                                    <el-option 
                                        v-for="item in options.reconciliationCompany.options" 
                                        :key="item.value"
                                        :label="item.label" 
                                        :value="item.value" 
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col> 
                        <!-- 新增：出单团队远程搜索下拉 -->
                        <!-- <el-col :xs="24" :sm="12" :md="8" :lg="6">
                            <el-form-item label="出单团队" prop="outTeamBizId" label-position="top">
                                <el-select 
                                    v-model="searchFormData.outTeamBizId" 
                                    placeholder="请选择出单团队" 
                                    clearable
                                    :remote-method="(keyword) => remoteMethod('team', keyword)" 
                                    :loading="options.team.loading" 
                                    filterable 
                                    remote
                                    reserve-keyword
                                >
                                    <el-option 
                                        v-for="item in options.team.options" 
                                        :key="item.teamBizId"
                                        :label="item.teamName" 
                                        :value="item.teamBizId" 
                                    />
                                </el-select>
                            </el-form-item>
                        </el-col> -->
                    </el-row>
                </el-form>
            </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="120" sortable />
                    <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 }">
                            <el-tag :type="row.status === '1' ? 'success' : row.status === '0' ? 'warning' : row.status === '2' ? 'info' : 'danger'">
                                {{ row.status === '1' ? '完成入账' : row.status === '0' ? '待入账' : row.status === '2' ? '部分入账' : '已失效' }}
                            </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 }">
                            {{ numberWithCommas(row.expectedAmount) }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="paidRatio" label="已入账比例" width="120" sortable>
                        <template #default="{ row }">
                            {{ (row.ratio || 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="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="setStatusDialogTableVisible = false"
        >
            <el-form :model="form">
                <el-form-item label="入账状态" label-width="120">
                    <el-select v-model="form.status" placeholder="请选择入账状态">
                        <el-option label="待入账" value="0" />
                        <el-option label="完成入账" value="1" />
                        <el-option label="部分入账" value="2" />
                        <el-option label="已失效" value="3" />
                    </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="handleConfirmSetStatus">确认</el-button>
                </div>
            </template>
        </CommonDialog>
    </div>
</template>

<script setup name="Receivables">
import CommonPage from '@/components/commonPage'
import CommonDialog from '@/components/commonDialog'
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { MoreFilled } from '@element-plus/icons-vue'
import { numberWithCommas, debounce } from '@/utils/index'
import { receivedFortuneList, commissionEntryRecord, commissionEntryEditRecords } from '@/api/financial/commission'

// 查询下拉列表数据
import { searchInsurers,searchReconciliationCompanies } from '@/api/search' 

// 分页相关
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([])

// 新增：下拉框选项状态管理（loading + 选项列表）
const options = reactive({
    insurer: { loading: false, options: [] }, // 保险公司
    product: { loading: false, options: [] }, // 产品计划
    reconciliationCompany: { loading: false, options: [] }, // 对账公司
})

// 设置入账状态表单
const form = reactive({
    status: '',
    desc: '',
})

const selectedRow = ref(null)

// 搜索表单数据（新增下拉框绑定字段）
const searchFormData = reactive({
    policyNo: '',
    incomeDateRange: [],
    statusList: [],
    commissionName: '',
    commissionPeriod: '',
    reconciliationCompany: '',
    insurerBizId: '',        // 保险公司ID
    productLaunchBizId: '',  // 产品计划ID
    commissionBizType: '',
    outTeamBizId: ''         // 出单团队ID（替换原outTeam）
})

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

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

// 新增：防抖处理远程搜索（延迟300ms，避免频繁请求）
const debouncedRemoteMethod = debounce(async (type, keyword) => {
    try {
        // 根据类型设置加载状态
        options[type].loading = true
        let res = []
        // 不同类型调用不同接口
        switch (type) {
            case 'insurer':
                res = await searchInsurers({ queryContent: keyword, pageSize: 20 }) // 保险公司搜索
                options.insurer.options = res.data.records.map(item=>{
                    return {
                        label: item.abbreviation,
                        value: item.insuranceCompanyBizId
                    }
                }) || []
                break
            case 'reconciliationCompany':
                res = await searchReconciliationCompanies({ name: keyword, pageSize: 20 }) // 对账公司搜索
                options.reconciliationCompany.options = res.data.records.map(item=>{
                    return {
                        label: item.name,
                        value: item.reconciliationCompanyBizId
                    }
                }) || []
                break
            default:
                break
        }
    } catch (error) {
        console.error(`搜索${type}失败:`, error)
        ElMessage.error(`加载${type === 'insurer' ? '保险公司' : type === 'product' ? '产品计划' : '出单团队'}失败`)
    } finally {
        // 关闭加载状态
        options[type].loading = false
    }
    console.log(options)
}, 300)

// 新增：远程搜索方法（对外暴露）
const remoteMethod = (type, keyword) => {
    // if (!keyword) {
    //     // 关键词为空时清空选项（可选）
    //     options[type].options = []
    //     return
    // }
    debouncedRemoteMethod(type, keyword)
}
// remoteMethod('reconciliationCompany', searchFormData.reconciliationCompany)
// remoteMethod('insurer', searchFormData.insurerBizId)

// 按钮事件处理
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] = ''
        }
    })
    // 重置下拉框选项
    Object.keys(options).forEach(key => {
        options[key].options = []
    })
    ElMessage.success('搜索条件已重置')
    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 () => {
    loading.value = true
    try {
        const params = {
            ...searchFormData,
            commissionDateStart: searchFormData.incomeDateRange[0] || '',
            commissionDateEnd: searchFormData.incomeDateRange[1] || '',
            incomeDateRange: 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 = { commissionBizId: cbd }
        const response = await commissionEntryRecord(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: '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: 'commissionRatio', label: '入账比例', width: '150' },
            { property: 'commissionDate', label: '入账日', width: '150' },
            { property: 'status', label: '入账状态', width: '150' }
        ]
        // 加载真实数据
        const records = await loadEntryRecordData(row.commissionExpectedBizId)
        entryRecordDialogTableData.value = records.length ? records : [{
            commissionPeriod: '2023-08',
            totalPeriod: '10',
            exchangeRate: '1.2345',
            currency: 'CNY',
            amount: '10000.00',
            commissionRatio: '10%',
            commissionDate: '2023-08-01',
            status: '已入账'
        }]
    } else if (e === 'setStatus') {
        // 回显当前行状态
        form.status = row.status
        form.desc = ''
        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 = () => {
    if (!form.status) {
        return ElMessage.warning('请选择入账状态')
    }
    if (!form.desc) {
        return ElMessage.warning('请输入修改理由')
    }
    // 调用接口修改状态（示例）
    ElMessageBox.confirm('确定要修改入账状态吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(async () => {
        // 此处替换为真实接口调用
        ElMessage.success('状态修改成功')
        setStatusDialogTableVisible.value = false
        loadTableData() // 重新加载表格
    }).catch(() => {
        ElMessage.info('已取消修改')
    })
}

// 初始化加载数据
onMounted(() => {
    loadTableData()
})
</script>

<style scoped lang="scss">

</style>