<template>
    <el-card style="width: 100%;" shadow="hover">
        <el-form :form="formData" :disabled="localMode != 'add'">
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="核算名称" required>
                        <el-input v-model="formData.name" placeholder="请输入核算名称"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="核算类型" required>
                        <el-select v-model="formData.type" placeholder="请选择核算类型" style="width: 100%;">
                            <el-option
                                v-for="item in typeOptions"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            ></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-form-item label="详细描述" required>
                <el-input
                    type="textarea"
                    :rows="2"
                    v-model="formData.description"
                    placeholder="请输入描述"
                ></el-input>
            </el-form-item>
        </el-form>
        <div style="text-align: right;">
            <el-button type="primary" v-if="localMode=='add'" @click="handleSave">保存</el-button>
        </div>
    </el-card>
    <el-row style="margin-top: 12px" v-if="formData.id">
        <el-button type="primary" @click="changeCal('dq')">贷前计算</el-button>
        <el-button type="primary" @click="changeCal('dh')" style="margin-left: 12px;" >贷后计算</el-button>
    </el-row>
    <el-row style="margin-top: 12px" v-if="formData.id" :gutter="10">
        <el-col :span="10"  v-if="currentCal==='dq'">
            <el-card shadow="hover" width="100%">
                <template #header>
                    <div style="display: flex; justify-content: space-between; align-items: center;border-bottom: 1px solid #ebeef5; padding-bottom: 4px;">
                    <span>贷前计算器</span>
                    <span><el-button type="primary" @click="handleDqCal" :disabled="calDisabled" :loading="calLoading">开始计算</el-button></span>
                    </div>
                </template>
                <el-form :form="formData" label-width="270px" :disabled="calDisabled">
                    <el-form-item label="企业技术说明及改造方案">
                        <sc-upload-filed
                            v-model="formData.dq_file6"
                            :file_ = "formData.dq_file6_"
                            :multiple="false"
                            :limit="1"
                            accept=".txt,.doc,.docx"
                            />
                    </el-form-item>
                    <el-form-item label="企业低碳转型战略与总体规划">
                        <sc-upload-filed
                            v-model="formData.dq_file1"
                            :file_ = "formData.dq_file1_"
                            :multiple="false"
                            :limit="1"
                            accept=".txt,.doc,.docx"
                            />
                    </el-form-item>
                    <el-form-item label="碳排放数据监测、核查与信息披露报告">
                        <sc-upload-filed
                            v-model="formData.dq_file2"
                            :file_ = "formData.dq_file2_"
                            :multiple="false"
                            :limit="1"
                            accept=".txt,.doc,.docx"
                            />
                    </el-form-item>
                    <el-form-item label="数字化与智能控制系统技术方案">
                        <sc-upload-filed
                            v-model="formData.dq_file5"
                            :file_ = "formData.dq_file5_"
                            :multiple="false"
                            :limit="1"
                            accept=".txt,.doc,.docx"
                            />
                    </el-form-item>
                    <el-form-item label="环境、社会与治理（ESG）尽职调查报告">
                        <sc-upload-filed
                            v-model="formData.dq_file3"
                            :file_ = "formData.dq_file3_"
                            :multiple="false"
                            :limit="1"
                            accept=".txt,.doc,.docx"
                            />
                    </el-form-item>
                    <el-form-item label="项目融资与可行性研究方案">
                        <sc-upload-filed
                            v-model="formData.dq_file4"
                            :file_ = "formData.dq_file4_"
                            :multiple="false"
                            :limit="1"
                            accept=".txt,.doc,.docx"
                            />
                    </el-form-item>
                </el-form>
            </el-card>
        </el-col>
        <el-col :span="10"  v-if="currentCal==='dh'">
            <el-card shadow="hover" width="100%">
                <template #header>
                    <div style="display: flex; justify-content: space-between; align-items: center;border-bottom: 1px solid #ebeef5; padding-bottom: 4px;">
                    <span>贷后计算器</span>
                    <span><el-button type="primary" @click="handleDhCal" :disabled="calDisabled" :loading="calLoading">开始计算</el-button></span>
                    </div>
                </template>
                <el-form :form="formData" label-width="270px" :disabled="calDisabled">
                    <el-form-item label="企业技术说明及改造方案">
                        <sc-upload-filed
                            v-model="formData.dh_file6"
                            :file_ = "formData.dh_file6_"
                            :multiple="false"
                            :limit="1"
                            accept=".txt,.doc,.docx"
                            />
                    </el-form-item>
                    <el-form-item label="数字化与智能控制系统技术方案">
                        <sc-upload-filed
                            v-model="formData.dh_file5"
                            :file_ = "formData.dh_file5_"
                            :multiple="false"
                            :limit="1"
                            accept=".txt,.doc,.docx"
                            />
                    </el-form-item>
                    <el-form-item label="企业低碳转型战略与总体规划">
                        <sc-upload-filed
                            v-model="formData.dh_file1"
                            :file_ = "formData.dh_file1_"
                            :multiple="false"
                            :limit="1"
                            accept=".txt,.doc,.docx"
                            />
                    </el-form-item>
                    <el-form-item label="碳排放数据监测、核查与信息披露报告">
                        <sc-upload-filed
                            v-model="formData.dh_file2"
                            :file_ = "formData.dh_file2_"
                            :multiple="false"
                            :limit="1"
                            accept=".txt,.doc,.docx"
                            />
                    </el-form-item>
                    <el-form-item label="环境、社会与治理（ESG）尽职调查报告">
                        <sc-upload-filed
                            v-model="formData.dh_file3"
                            :file_ = "formData.dh_file3_"
                            :multiple="false"
                            :limit="1"
                            accept=".txt,.doc,.docx"
                            />
                    </el-form-item>
                    <el-form-item label="项目融资与可行性研究方案">
                        <sc-upload-filed
                            v-model="formData.dh_file4"
                            :file_ = "formData.dh_file4_"
                            :multiple="false"
                            :limit="1"
                            accept=".txt,.doc,.docx"
                            />
                    </el-form-item>
                </el-form>
            </el-card>
        </el-col>
        <el-col :span="14">
            <el-card style="width: 100%;">
                <template #header>
                    <span v-if="score === null">暂无评分数据，请上传相关文件后计算</span>
                    <span v-else>
                        贵企业的转型金融{{currentCal==='dq'?'贷前':'贷后'}}评估得分为
                        <span class="score-display">{{ score }}</span> 分;
                        等级: <span class="level-display" :style="levelStyle">
                            {{ level }}
                        </span>
                    </span>
                </template>
                <!-- 动画容器 -->
                <div class="animation-container" v-show="showAnimation">
                    <div class="particles-container">
                        <div class="particle" v-for="n in 30" :key="n" :style="particleStyle(n)"></div>
                    </div>
                    <div class="loading-circle">
                        <div class="circle"></div>
                        <div class="circle"></div>
                        <div class="circle"></div>
                    </div>
                    <div class="loading-text" :style="{color: loadingTextColor}">{{ loadingText }}</div>
                </div>
                
                <!-- 结果展示 -->
                <div class="result-container" v-show="showResult">
                    <div class="score-circle" :style="scoreCircleStyle">
                        <div class="score-value">{{ score }}</div>
                        <!-- <div class="score-label">总分</div> -->
                    </div>
                    <!-- <div class="level-badge" :style="levelStyle">
                        {{ level }}
                    </div> -->
                    <div class="result-description">
                        <p>根据您提交的资料，我们已完成双碳贷前评估。</p>
                        <p>您的企业评级为 <strong :style="{color: levelColor,fontSize: '24px'}">{{ level }}</strong> 级。</p>
                    </div>
                </div>
            </el-card>
        </el-col>
    </el-row>
</template>
<script setup>
import {nextTick, onMounted, ref, watch, computed} from 'vue';
import TOOL from "@/utils/tool.js";
import API from '@/api'
import { ElMessage } from 'element-plus'
const props = defineProps({
    mode: {
        type: String,
        default: 'show'
    },
    t_id: {
        type: String,
        default: null
    }
});
const localMode = ref("show");
const formData = ref({});
const typeOptions = ref([
    {label: '企业', value: '企业'},
    {label: '项目', value: '项目'}
]);
const handleSave = () => {
    if (localMode.value == 'add') {
        API.carbon.work.create.req(formData.value).then(res => {
            formData.value = res;
            localMode.value = 'show';
        });
    }
}
onMounted(() => {
    if (props.t_id) {
        API.carbon.work.item.req(props.t_id).then(res => {
            formData.value = res;
            if (res.score_dq && currentCal.value==='dq') {
                score.value = res.score_dq;
                showResult.value = true
            }
            if (res.create_by == TOOL.data.get("USER_INFO").id) {
                calDisabled.value = false;
            }
        });
    } else {
        localMode.value = 'add';
        formData.value = {}
    }
});

const currentCal = ref("dq");

const calDisabled = ref(true);
const changeCal = (type) => {
    currentCal.value = type;
    showResult.value = false;
    if (type==='dq' && formData.value.score_dq) {
        score.value = formData.value.score_dq;
        showResult.value = true
    } else if (type==='dh' && formData.value.score_dh) {
        score.value = formData.value.score_dh;
        showResult.value = true
    } else {
        score.value = null;
    }
};
const calLoading = ref(false);
const score = ref(null);
const level = ref("较差");
const levelColor = ref('#000');
const showAnimation = ref(false);
const showResult = ref(false);
const loadingText = ref("正在计算评分...");
const loadingTextColor = ref("#ee2416");

// 计算等级样式
const levelStyle = computed(() => {
    return {
        color: levelColor.value,
        background: `${levelColor.value}15`,
        border: `1px solid ${levelColor.value}30`
    };
});

// // 计算得分圆环样式
const scoreCircleStyle = computed(() => {
    const percentage = score.value ? (score.value / 100) * 360 : 0;
    return {
        background: `conic-gradient(${levelColor.value} ${percentage}deg, #f0f0f0 ${percentage}deg 360deg)`
    };
});

// 粒子样式
const particleStyle = (n) => {
    const size = Math.random() * 8 + 4;
    const left = Math.random() * 100;
    const animationDelay = Math.random() * 2;
    const animationDuration = Math.random() * 3 + 2;
    
    return {
        width: `${size}px`,
        height: `${size}px`,
        left: `${left}%`,
        animationDelay: `${animationDelay}s`,
        animationDuration: `${animationDuration}s`,
        background: '#ee2416'
    };
};

watch(score, (newScore) => {
    if (newScore >= 80) {
        level.value = '领先'
        levelColor.value = '#4caf50'
    } else if (newScore >= 60) {
        level.value = '良好'
        levelColor.value = '#2196f3'
    } else if (newScore >= 30) {
        level.value = '一般'
        levelColor.value = '#ff9800'
    } else {
        level.value = '较差'
        levelColor.value = '#f44336'
    }
}, { immediate: true });

const handleDqCal = () => {
    // 验证是否已上传文件
    if (formData.value.dq_file1 || formData.value.dq_file2 || formData.value.dq_file3 ||
        formData.value.dq_file4 || formData.value.dq_file5 || formData.value.dq_file6) {
    } else {
        ElMessage.info('请至少上传一个文件后再进行计算');
        return
    }
    calLoading.value = true;
    showAnimation.value = true;
    showResult.value = false;
    
    // 动态变化的加载文本
    const loadingTexts = [
        "正在分析企业低碳转型战略...",
        "正在评估碳排放数据...",
        "正在审核ESG尽职调查报告...",
        "正在研究项目融资方案...",
        "正在分析数字化技术方案...",
        "正在评估企业技术说明...",
        "正在生成最终评分..."
    ];
    
    let textIndex = 0;
    const minLoadingTime = 5000; // 最小加载时间 5秒
    const startTime = Date.now(); // 记录开始时间

    const textInterval = setInterval(() => {
        loadingText.value = loadingTexts[textIndex];
        textIndex = (textIndex + 1) % loadingTexts.length;
    }, 800);

    API.carbon.work.cal_dq.req(formData.value.id, formData.value).then(res => {
        const elapsedTime = Date.now() - startTime; // 已过去的时间
        const remainingTime = Math.max(0, minLoadingTime - elapsedTime); // 还需要等待的时间
        
        setTimeout(() => {
            clearInterval(textInterval);
            calLoading.value = false;
            score.value = res.total_score;
            
            // 动画完成后显示结果
            setTimeout(() => {
                showAnimation.value = false;
                showResult.value = true;
            }, 500);
        }, remainingTime);
        
    }).catch(e => {
        const elapsedTime = Date.now() - startTime;
        const remainingTime = Math.max(0, minLoadingTime - elapsedTime);
        
        setTimeout(() => {
            clearInterval(textInterval);
            calLoading.value = false;
            showAnimation.value = false;
        }, remainingTime);
    });
}

const handleDhCal = () => {
    // 验证是否已上传文件
    if (formData.value.dh_file1 || formData.value.dh_file2 || formData.value.dh_file3 ||
        formData.value.dh_file4 || formData.value.dh_file5 || formData.value.dh_file6) {
    } else {
        ElMessage.info('请至少上传一个文件后再进行计算');
        return
    }
    calLoading.value = true;
    showAnimation.value = true;
    showResult.value = false;
    
    // 动态变化的加载文本
    const loadingTexts = [
        "正在分析企业低碳转型战略...",
        "正在评估碳排放数据...",
        "正在审核ESG尽职调查报告...",
        "正在研究项目融资方案...",
        "正在分析数字化技术方案...",
        "正在评估企业技术说明...",
        "正在生成最终评分..."
    ];
    
    let textIndex = 0;
    const minLoadingTime = 5000; // 最小加载时间 5秒
    const startTime = Date.now(); // 记录开始时间

    const textInterval = setInterval(() => {
        loadingText.value = loadingTexts[textIndex];
        textIndex = (textIndex + 1) % loadingTexts.length;
    }, 800);

    API.carbon.work.cal_dh.req(formData.value.id, formData.value).then(res => {
        const elapsedTime = Date.now() - startTime; // 已过去的时间
        const remainingTime = Math.max(0, minLoadingTime - elapsedTime); // 还需要等待的时间
        
        setTimeout(() => {
            clearInterval(textInterval);
            calLoading.value = false;
            score.value = res.total_score;
            
            // 动画完成后显示结果
            setTimeout(() => {
                showAnimation.value = false;
                showResult.value = true;
            }, 500);
        }, remainingTime);
        
    }).catch(e => {
        const elapsedTime = Date.now() - startTime;
        const remainingTime = Math.max(0, minLoadingTime - elapsedTime);
        
        setTimeout(() => {
            clearInterval(textInterval);
            calLoading.value = false;
            showAnimation.value = false;
        }, remainingTime);
    });
}
</script>
<style scoped>
.animation-container {
    margin-top: 80px;
    position: relative;
    height: 300px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}

.particles-container {
    position: absolute;
    width: 100%;
    height: 100%;
    overflow: hidden;
}

.particle {
    position: absolute;
    border-radius: 50%;
    opacity: 0.7;
    animation: floatUp linear infinite;
}

@keyframes floatUp {
    0% {
        transform: translateY(100px) scale(0);
        opacity: 0;
    }
    10% {
        opacity: 0.7;
    }
    90% {
        opacity: 0.7;
    }
    100% {
        transform: translateY(-100px) scale(1);
        opacity: 0;
    }
}

.loading-circle {
    display: flex;
    gap: 10px;
    margin-bottom: 20px;
}

.circle {
    width: 15px;
    height: 15px;
    border-radius: 50%;
    background: var(--td-brand-color);
    animation: pulse 1.5s ease-in-out infinite;
}

.circle:nth-child(2) {
    animation-delay: 0.2s;
}

.circle:nth-child(3) {
    animation-delay: 0.4s;
}

@keyframes pulse {
    0%, 100% {
        transform: scale(0.8);
        opacity: 0.5;
    }
    50% {
        transform: scale(1.2);
        opacity: 1;
    }
}

.loading-text {
    font-size: 18px;
    font-weight: 500;
    transition: all 0.3s ease;
}

.result-container {
    margin-top: 80px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 400px;
    gap: 20px;
}

.score-circle {
    width: 200px;
    height: 200px;
    border-radius: 50%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    position: relative;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.score-circle::before {
    content: '';
    position: absolute;
    width: 170px;
    height: 170px;
    border-radius: 50%;
    background: white;
}

.score-value {
    font-size: 40px;
    font-weight: bold;
    z-index: 1;
    color: #333;
}

.score-label {
    font-size: 14px;
    color: #666;
    z-index: 1;
}

.level-badge {
    padding: 8px 20px;
    border-radius: 20px;
    font-size: 18px;
    font-weight: bold;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.result-description {
    text-align: center;
    max-width: 80%;
    line-height: 1.6;
    font-size: 18px;
}

.score-display {
    font-weight: bold;
    font-size: 32px;
    color: #2d8cf0;
}

.level-display {
    font-weight: bold;
    font-size: 32px;
    padding: 4px 12px;
    border-radius: 8px;
}
</style>