<template>
    <div>
        <div class="detail-wrap">
            <div class="sticky-wrap">
                <div class="header-wrap">
                    <div class="left-wrap">
                        <svg-icon iconClass="document" class="header-icon"></svg-icon>
                        <div class="header-content">
                            <div class="title">利率测算报告</div>
                            <div class="date">创建时间:2025-12-13</div>
                        </div>
                    </div>
                    <div class="btn-wrap">
                        <div class="customer-id-wrap">
                            <span class="customer-id-label">客户ID:</span>
                            <el-input class="customer-id-input" @blur="changeID" v-model="baseInfo.applicationId"></el-input>
                        </div>
                        <el-button type="primary" @click="SubmitForm">查询</el-button>
                        <el-button type="primary" @click="onSaveOrSubmit">提交</el-button>
                        <el-button type="text" @click="historyDialogVisible = true">历史记录</el-button>
                    </div>
                </div>
            </div>
            
            <div class="card-wrap" style="margin-top: 0px">
                <div class="title-bar">
                    <div class="content">客户基本信息</div>
                </div>
                <el-divider></el-divider>
                <el-descriptions :column="2" :labelStyle="{ width: '25%', }" :contentStyle="{ width: '25%' }" border>
                    <el-descriptions-item label="客户内码">{{ this.baseInfo.custIsn }}</el-descriptions-item>
                    <el-descriptions-item label="客户类型">{{ this.baseInfo.custType }}</el-descriptions-item>
                    <el-descriptions-item label="担保方式">{{ this.baseInfo.guarType }}</el-descriptions-item>
                    <el-descriptions-item label="担保方式_省行">{{ this.baseInfo.loanType }}</el-descriptions-item>
                    <el-descriptions-item label="客户名称">{{ this.baseInfo.custName }}</el-descriptions-item>
                    <el-descriptions-item label="证件类型">{{ this.baseInfo.idType }}</el-descriptions-item>
                    <el-descriptions-item label="贷款利率">{{ this.baseInfo.loanRate }}</el-descriptions-item>
                    <el-descriptions-item label="贷款利率_省行">{{ this.baseInfo.loanRate }}</el-descriptions-item>
                    <el-descriptions-item label="客户年龄">{{ this.baseInfo.bpAge }}</el-descriptions-item>
                    <el-descriptions-item label="申请金额">{{ this.baseInfo.applyAmt }}</el-descriptions-item>
                    <el-descriptions-item label="贷款用途">{{ this.baseInfo.loanPurpose }}</el-descriptions-item>
                    <el-descriptions-item label="是否有经营佐证">{{ this.baseInfo.bizProof }}</el-descriptions-item>
                    <el-descriptions-item label="抵质押类型">{{ this.baseInfo.collType }}</el-descriptions-item>
                    <el-descriptions-item label="抵质押物是否三方所有">{{ this.baseInfo.collThirdParty }}</el-descriptions-item>
                </el-descriptions>
            </div>
            <div class="card-wrap">
                <div class="title-bar">
                    <div class="content">利率测算</div>
                </div>
                <el-divider></el-divider>

                <el-descriptions :column="4" :labelStyle="{ width: '60px' }" :contentStyle="{ width: '60px' }" border>
                    <el-descriptions-item label="基础利率(%)">3.00</el-descriptions-item>
                    <el-descriptions-item label="浮动利率(%)">{{ floatRate }} </el-descriptions-item>
                    <el-descriptions-item label="测算利率(%)"> {{ calcRate }}</el-descriptions-item>
                    <el-descriptions-item labelClassName="summary-item" label="执行利率(%)">
                        <el-input v-model="baseInfo.finalRate" class="no-border" placeholder="请输入" />
                    </el-descriptions-item>
                    <el-descriptions-item v-if="showCalc" labelClassName="summary-item" label="超利分成">{{
                        chartInfo.profitAmt
                    }}</el-descriptions-item>
                    <el-descriptions-item v-if="showCalc" labelClassName="summary-approval-label"
                        contentClassName="summary-approval-content" label="审批状态">{{ approvalStatus | approvalStatusFilter
                        }}</el-descriptions-item>
                    <el-descriptions-item v-if="showCalc" labelClassName="summary-approval-label"
                        contentClassName="summary-approval-content" label="审批层级">{{ approvalLevel | approvalFilter
                        }}</el-descriptions-item>
                </el-descriptions>

                <div class="btn-wrap">
                    <el-button type="primary" @click="onCalc">利率测算</el-button>
                </div>
            </div>

            <div v-if="showCalc" class="card-wrap">
                <div class="title-bar">
                    <div class="content">议价池</div>
                </div>
                <el-divider></el-divider>
                <div class="chart-table-wrap">
                    <div ref="chartRef" class="chart-wrap"></div>
                    <div class="table-wrap">
                        <table class="calc-table">
                            <tr>
                                <th>议价池类型</th>
                                <th>使用额度(元)</th>
                                <th>现有额度(元)</th>
                                <th>使用率</th>
                            </tr>
                            <tr v-for="(item, index) in poolList" :key="index">
                                <td>{{ item.label }}</td>
                                <td>￥{{ item.usedAmt | amtFilter }}</td>
                                <td>￥{{ item.aviableAmt | amtFilter }}</td>
                                <td>{{ getUsedRate(item) }}%</td>
                            </tr>
                        </table>
                    </div>
                </div>
            </div>
            <div class="card-wrap">
                <div class="title-bar">
                    <div class="content">测算因数</div>
                </div>
                <el-divider></el-divider>
                <table class="custom-table custom-table-border">
                    <tr>
                        <th>因素名称</th>
                        <th>因素取值</th>
                    </tr>
                    <tr v-for="(item, index) in calcFactors" :key="index">
                        <td class="td-25-per">{{ item.label }}</td>
                        <td class="td-25-per">{{ item.val }}</td>
                    </tr>
                </table>
            </div>

        </div>
        <!-- 历史记录弹窗 -->
        <el-dialog title="历史记录" :visible.sync="historyDialogVisible" width="800px">
            <el-table :data="historyList" style="width: 100%">
                <el-table-column prop="name" label="申请ID"></el-table-column>
                <el-table-column prop="index" label="序号"></el-table-column>
            </el-table>
        </el-dialog>
    </div>
</template>
<script>
import { execRateCalc, submitCalcFlow } from '@/api/rate-calc/index'
import { add, divide, minus, multiply } from '@/utils/math'
import * as echarts from 'echarts'
import { cloneDeep, isEmpty } from 'lodash'
import { BaseProps, InitBaseForm, PoolTypes, ApprovalType, calcFactors, amtFilter } from './constants-info'
import { mapGetters } from 'vuex';
import {applicationSubmit} from '@/api/gridSearch/publicPool/index';
export default {
    name: 'RateDetailView',
    data() {
        return {
            BaseProps,
            calcFactors,
            cusName: '',
            cusIdNo: '',
            pageType: 'detail',
            loading: false,
            baseInfo: cloneDeep(InitBaseForm),
            url:process.env.VUE_APP_NEW_URL,
            chartInfo: {},
            approvalLevel: '',
            approvalStatus:'',
            chartInstance: null,
            chartOptions: {
                tooltip: {
                    trigger: 'item'
                },
                series: [
                    {
                        name: '测算结果',
                        type: 'pie',
                        radius: ['40%', '70%'],
                        percentPrecision: 8,
                        avoidOverlap: false,
                        itemStyle: { borderRadius: 6, borderColor: '#fff' },
                        label: {
                            show: false
                        },
                        labelLine: {
                            show: false
                        },
                        tooltip: {
                            formatter: params => `${params.name}: ${amtFilter(params.value)}元`
                        }
                    }
                ]
            },
            poolList: [],
            historyList:[],
            historyDialogVisible: false,
            showCalc: false
        }
    },
    computed: {
        ...mapGetters(['ratedetail']),
        floatRate() {
            const tot = this.calcFactors.reduce((acc, curr) => acc + curr.val, 0)
            return divide(tot, 100, 2)
        },
        calcRate() {
            return add(3, this.floatRate, 2)
        },
    },
    created() {
        this.historyList = JSON.parse(localStorage.getItem('rateCalcHistory') || '[]')
    },
    mounted() {
        this.getDetailInfo()
        this.changeID()

    },
    filters: {
        amtFilter,
        approvalFilter(val) {
            const fItem = ApprovalType.find(item => item.value === val)
            return fItem?.label ?? '-'
        },
        approvalStatusFilter(val) {
            const fItem = val === '1'?'需要审批':'无需审批' 
            return val ?fItem :'-'
        },
    },
    methods: {
        getMarks(item) {
            return {
                [item.min]: item.min.toString(),
                [item.max]: item.max.toString()
            }
        },
        changeID() {
            try {
                let history = JSON.parse(localStorage.getItem('rateCalcHistory') || '[]');
                if (!Array.isArray(history)) {
                    history = [];
                }
                if (this.baseInfo.applicationId) {
                    const exists = history.some(item => item.name === this.baseInfo.applicationId);
                    if (!exists) {
                        history.push({
                            name: this.baseInfo.applicationId,
                            index: history.length
                        });
                    }
                }
                const uniqueHistory = history.reduce((acc, current) => {
                    const exists = acc.find(item => item.name === current.name);
                    if (!exists) {
                        acc.push(current);
                    }
                    return acc;
                }, []);
                localStorage.setItem('rateCalcHistory', JSON.stringify(uniqueHistory));
                this.historyList =  uniqueHistory;
            } catch (error) {
                console.error('处理历史记录时出错:', error);
                return [];
            }
        },
        SubmitForm() {
            applicationSubmit({applicationId:this.baseInfo.applicationId},this.url).then(res => {
                if (res.data.code === 200) {
                    this.baseInfo = res.data.data
                    this.getDetailInfo()
                    this.$message.success('操作成功')
                } else {
                    this.$message.error(res.message)
                }
            })
        },
        getParams() {
            let params = {
                applicationId: this.baseInfo.applicationId,
                approvalLevel: this.approvalLevel,
                approvalStatus: this.approvalStatus,
                branchUsage:this.chartInfo.branchUsage,
                finalRate: this.baseInfo.finalRate,
                managerUsage: this.chartInfo.managerUsage,
                outletUsage: this.chartInfo.outletUsage,
                profitAmt: this.chartInfo.profitAmt
            }
            if (isEmpty(this.chartInfo)) {
                params = {
                    applicationId: this.baseInfo.applicationId,
                    approvalLevel: '',
                    approvalStatus: '',
                    branchUsage:'',
                    finalRate: '',
                    managerUsage: '',
                    outletUsage: '',
                    profitAmt: ''
                }
            }
            return params
        },
        async getDetailInfo() {
            try {
                this.loading = true
                this.baseInfo = {
                    ...this.baseInfo,
                    ...this.ratedetail,
                    finalRate: this.ratedetail?.finalRate ? this.ratedetail.finalRate * 100 : 0
                }

                this.calcFactors.forEach((factor, index) => {
                    if (this.ratedetail && this.ratedetail.hasOwnProperty(factor.prop)) {
                        const val = this.ratedetail[factor.prop];
                        const numVal = val !== null && val !== undefined && val !== '' ? Number(val) : 0;
                        factor.val = numVal;
                    } 
                })
                this.baseInfo.finalRate = this.calcRate
            } catch (error) {
                console.error('getDetailInfo error', error)
                this.$message.error('数据加载失败: ' + error.message)
            } finally {
                this.loading = false
            }
        },
        async onSaveOrSubmit() {
            try {
                const params = this.getParams()
                const data = await submitCalcFlow(params,this.url)
                if (data.data.code === 200) {
                    this.$message.success(data?.data.msg ?? '提交成功')
                }else {
                    this.$message.error(data.data.msg)
                }
            } catch (error) {
                console.error('saveCalcFlow error:', error)
            }
        },
        getChartData(resData) {
            const cData = []
            this.poolList = []
            for (const item of PoolTypes) {
                const citem = { value: 0, name: item.label }
                let titem = {
                    label: item.label,
                    usedAmt: 0,
                    aviableAmt: 0
                }
                
                // 根据label类型设置不同的使用额度和现有额度
                switch (item.label) {
                    case '私域池':
                        titem.usedAmt = resData?.managerUsage ?? 0
                        titem.aviableAmt = resData?.managerBalance ?? 0
                        break
                    case '网点公域池':
                        titem.usedAmt = resData?.branchUsage ?? 0
                        titem.aviableAmt = resData?.branchBalance ?? 0
                        break
                    case '支行公域池':
                        titem.usedAmt = resData?.outletUsage ?? 0
                        titem.aviableAmt = resData?.outletBalance ?? 0
                        break
                    default:
                        titem.usedAmt = resData?.[item.propName] ?? 0
                        titem.aviableAmt = resData?.[item.propName] ?? 0
                }
                
                this.poolList.push(titem)
                citem.value = titem.usedAmt
                cData.push(citem)
            }
            return cData
        },
        async onCalc() {
            try {
                const params = {
                    applicationId: this.baseInfo.applicationId,
                    finalRate: Number(this.baseInfo.finalRate)
                }
                const  data  = await execRateCalc(params,this.url)
                if (data.data.code === 200) {
                    this.$message.success(data.data?.message ?? '测算成功')
                    this.chartInfo = data.data.data ?? {}
                    this.approvalLevel = this.chartInfo?.approvalLevel ?? '0'
                    this.approvalStatus = this.chartInfo.approvalStatus ?? '0'
                    this.chartOptions.series[0].data = this.getChartData(data.data.data)
                    this.showCalc = true
                    this.$nextTick(() => {
                        this.chartInstance = echarts.init(this.$refs.chartRef)
                        this.chartInstance.setOption(this.chartOptions)
                    })
                } else {
                    this.$message.error(data.data.data?.message ?? '测算失败')
                }
            } catch (error) {
                console.error('on rate calc error:', error)
            }
        },
        getUsedRate(item) {
            return multiply(divide(item.usedAmt, item.aviableAmt, 4), 100, 2)
        }
    }
}
</script>
<style lang="scss" scoped>
.detail-wrap {
    width: 100%;
    padding-bottom: 20px;
}

.detail-wrap .sticky-wrap {
    position: sticky;
    padding-bottom: 20px;
}

.detail-wrap .header-wrap {
    padding: 20px;
    border-radius: 8px;
    display: flex;
    justify-content: space-between;
}

.detail-wrap .header-wrap .left-wrap {
    display: flex;
    align-items: center;
}

.detail-wrap .header-wrap .left-wrap .header-icon {
    width: 36px;
    height: 36px;
    fill: #4682ff;
    margin-right: 10px;
}

.detail-wrap .header-wrap .left-wrap .header-content .title {
    color: #010101;
    font-size: 20px;
    font-weight: 600;
    display: flex;
    flex-direction: row;
}

.detail-wrap .header-wrap .left-wrap .header-content .date {
    margin-top: 5px;
    color: #595959;
    font-size: 14px;
}

.btn-wrap {
    margin-top: 10px;
    display: flex;
    justify-content: center;
    align-items: center;
}

.customer-id-wrap {
    display: flex;
    align-items: center;
    margin-right: 20px;
}

.customer-id-label {
    white-space: nowrap;
    margin-right: 10px;
}

.customer-id-input {
    width: 200px;
}

.custom-table {
    width: 100%;
    color: #909399;
    font-size: 14px;
    line-height: 1.5;
    border-collapse: collapse;
    border: 1px solid #e5e6f7;

    th,
    td {
        padding: 10px;
        text-align: left;
        border: 1px solid #e5e6f7;
    }

    th {
        background-color: #f0f2f5;
    }

    th {
        width: 50%;
    }

    th:nth-child(2) {
        width: 50%;
    }
}

.card-wrap {
    .title-bar {
        width: 100%;
        position: relative;
        margin-top: 10px;
        display: flex;
        align-items: center;
        justify-content: space-between;

        .content {
            padding: 0;
            position: relative;
            padding-left: 15px;
            color: #010101;
            font-size: 18px;
            font-weight: 600;
            line-height: 20px;

            &::before {
                content: "";
                position: absolute;
                left: 0;
                top: 0;
                bottom: 0;
                width: 4px;
                background-color: #1890ff;
            }

            .tip {
                color: #a6a6b2;
                font-size: 14px;
                font-weight: 400;
                line-height: 20px;
            }
        }
    }

    ::v-deep .summary-item {
        color: #010101;
        font-weight: 600;
    }

    ::v-deep .summary-approval-label {
        color: #e6a23c;
        font-weight: 600;
    }

    ::v-deep .summary-approval-content {
        color: #e6a23c;
        font-weight: 600;
    }

    ::v-deep .custom-form {
        width: 100%;
        border-radius: 4px;
        padding: 20px;

        .el-form-item {
            width: 100%;
            display: inline-block;
            border: 1px solid #e6ebf5;
            margin-bottom: 0;

            .el-form-item__label {
                background-color: #fafafa;
                padding: 10px;
                text-align: center;
            }

            .el-form-item__content {
                padding-top: 10px;
                text-align: center;

                .el-input__inner {
                    border: none;
                }
            }
        }
    }

    .btn-wrap {
        margin-top: 10px;
        display: flex;
        justify-content: center;
    }

    .approval-type {
        display: flex;
    }

    .chart-table-wrap {
        display: flex;

        .chart-wrap {
            width: 400px;
            height: 400px;
            margin-right: 10px;
        }

        .table-wrap {
            width: 700px;

            .calc-table {
                width: 100%;
                font-size: 14px;
                border-collapse: collapse;

                th {
                    width: 25%;
                }

                th,
                td {
                    text-align: center;
                    border: 1px solid #e6e8ee;
                    font-size: 14px;
                    color: rgba(0, 0, 0, 0.9);
                    line-height: 22px;
                    padding: 12px 25px;
                    word-break: break-all;
                }
            }
        }
    }
}
</style>
