<template>
    <div class="page-container row-container">
        <section class="list-part-container" style="flex: 2">
            <!-- 搜索区 -->
            <el-form class="list-search-container" :model="queryParams" ref="queryRef" :inline="true">
                <el-form-item label="年份：" prop="year">
                    <el-date-picker v-model="queryParams.year" type="year" value-format="YYYY" :editable="false"
                        :clearable="false" placeholder="请选择时间" @change="handleYearChange" style="width: 130px" />
                </el-form-item>
                <el-form-item label="工艺图纸电子化基数：" v-hasPermi="['business:conversion:query']" prop="number">
                    <span v-if="!disabled">{{ number }}</span>
                    <el-input v-if="disabled" v-model.trim="number" style="width: 220px; margin-left: 0px" />
                </el-form-item>
                <el-form-item>
                    <el-button v-if="!disabled" type="primary" v-hasPermi="['business:conversion:add']"
                        @click="handleEdit">编辑</el-button>
                    <el-button v-if="disabled" type="success" @click="handleSave">保存</el-button>
                    <el-button v-if="disabled" type="info" @click="handleCancel">取消</el-button>
                </el-form-item>
            </el-form>
            <!-- 列表区 -->
            <div ref="echartDom" style="width: 100%; height: 100%;"></div>

            <!-- 表单 -->

        </section>
    </div>
</template>

<script setup name="Conversion">
import { listConversion, addConversion } from '@/api/business/conversion'
import { ref, onMounted, reactive, computed } from 'vue'
import * as echarts from 'echarts'
import { getProcuctDrawing } from '@/api/business/drawing'
import { markRaw } from "vue"
const { proxy } = getCurrentInstance();
const disabled = ref(false)
const echartInstance = ref(null)
const itemNum = ref(0)
const echartDom = ref(null)
const procuctDrawing = ref(0)
const number = ref(0)
const rawData = ref([])
const months = ref(['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'])
const currentMonthIndex = computed(() => new Date().getMonth())
/** 字典 */
const { conversion_mes } = proxy.useDict("conversion_mes");
const data = reactive({
    queryParams: {
        year: new Date().getFullYear().toString()
    }
})

const { queryParams } = toRefs(data)

// function processChartData(rawData, selectedYear) {
//     const monthlyData = new Array(12).fill(0); // 初始化每月数据为0
//     console.log(rawData,542)
//     rawData.forEach(record => {
//         const recordDate = new Date(record.date);
//         const recordYear = recordDate.getFullYear();
//         const monthIndex = recordDate.getMonth();

//         // 根据年份和月份设置itemNum的值
//         if (recordYear === selectedYear) {
//             // 这里可以根据实际情况调整逻辑
//             itemNum.value = record.quantity; // 使用quantity作为分子
//         }
//     });

//     // 计算每个月的电子化率
//     for (let i = 0; i < 12; i++) {
//         // 假设每个月的基数（分母）存储在procuctDrawing中
//         // 这里需要根据实际情况调整逻辑来获取每个月的基数
//         const denominator = (selectedYear === 2024 && i >= 2) ? procuctDrawing.value : 0; // 示例逻辑
//         if (denominator > 0) {
//             monthlyData[i] = (itemNum.value / denominator * 100).toFixed(2);
//         }
//     }

//     return monthlyData;
// }

function processChartData(rawData, selectedYear) {
    const monthlyData = new Array(12).fill(null);
    const currentYear = new Date().getFullYear();
    const currentMonthIndex = new Date().getMonth();
    // console.log(rawData)
    rawData.forEach(record => {
        const recordDate = new Date(record.date);
        const recordYear = recordDate.getFullYear();
        const monthIndex = recordDate.getMonth();
        if (!record.quantity) {
            itemNum.value = 0
        }
        else {
            itemNum.value = record.quantity
        }
        // else {
        //     itemNum.value = procuctDrawing.value;
        // }

        if (recordYear === selectedYear) {
            // console.log(recordDate, recordYear, monthIndex)

            monthlyData[monthIndex] = (itemNum.value / parseInt(record.number) * 100).toFixed(2);
            // console.log(monthlyData[monthIndex], record.number)
        }
    });

    // 设置默认值逻辑
    for (let i = 0; i < 12; i++) {
        if (monthlyData[i] === null) {
            // 如果选择的年份是2024年，且月份是3月或之后，或者年份晚于2024年，则使用默认值100
            monthlyData[i] = 0
            //  (selectedYear >= 2024 && (i >= 2 || selectedYear > 2024)) ? itemNum.value : 0;
        }
        // 转换为百分比形式
        monthlyData[i] = parseInt(monthlyData[i]);
    }
    return monthlyData;
}

function handleEdit() {
    disabled.value = !disabled.value;
}

function handleCancel() {
    disabled.value = !disabled.value;
    getList();
}

function handleSave() {
    addConversion({ number: number.value }).then(res => {
        if (res.code == 200) {
            proxy.$modal.msgSuccess("操作成功");
            disabled.value = !disabled.value;
            getList();
        }
    });
}
function sortDataByDateAsc(rawData) {
    return rawData.slice().sort((a, b) => new Date(a.date) - new Date(b.date));
}
function updateChart(monthlyData, displayMonths, selectedYear, currentYear) {

    echartInstance.value.setOption({
        title: { text: '工艺图纸上线率' },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            },
            formatter: function (params) {
                const param = params[0];
                const monthIndex = param.dataIndex;
                const month = displayMonths[monthIndex];
                const currentYear = new Date().getFullYear();
                const currentMonthIndex = new Date().getMonth();
                const rawDataAsc = sortDataByDateAsc(rawData.value);

                // 初始化值
                let rawDataItem, requiredDocumentsThisMonth = 0;
                let uploadedProducts = 0;
                let rate = 0;

                // 遍历 rawDataAsc 来找到当前月份的数据项
                rawDataAsc.forEach(item => {
                    const itemDate = new Date(item.date); // 确保 item.date 是一个日期字符串或 Date 对象
                    if (itemDate.getFullYear() === currentYear && itemDate.getMonth() === monthIndex) {
                        rawDataItem = item;
                    }
                });

                if (rawDataItem) {
                    requiredDocumentsThisMonth = rawDataItem.number;
                    uploadedProducts = rawDataItem.quantity;
                } else if (selectedYear === currentYear && monthIndex === currentMonthIndex) {
                    // 如果当前月份，使用 procuctDrawing.value
                    uploadedProducts = procuctDrawing.value;
                }

                // 计算上线率
                if (requiredDocumentsThisMonth > 0) {
                    rate = (uploadedProducts / requiredDocumentsThisMonth * 100).toFixed(2);
                }

                // 根据业务逻辑设置 conversion_mes
                const mes1 = conversion_mes.value[0].label;
                const mes2 = conversion_mes.value[1].label;

                return `
        ${month}:<br/>
        ${mes2}${uploadedProducts}，<br/>
        上线率：${rate}%
    `;
            }
        },
        xAxis: {
            type: 'category',
            data: displayMonths
        },
        yAxis: {
            type: 'value'
        },
        series: [{
            name: '电子化率',
            type: 'line',
            data: monthlyData
        }]
    });
}
function initChart() {
    echartInstance.value = markRaw(echarts.init(echartDom.value));
    updateChart([], months.value); // 使用空数据初始化图表
}

function handleQuery() {
    getList();
}

function handleYearChange(year) {
    const currentYear = new Date().getFullYear();
    if (parseInt(year) > currentYear) {
        queryParams.value.year = currentYear.toString();
    } else {
        queryParams.value.year = year;
    }
    getList();
}

function resetQuery() {
    queryParams.value.year = new Date().getFullYear().toString();
    getList();
}
function sortDataByDateDesc(rawData) {
    return rawData.slice().sort((a, b) => new Date(b.date) - new Date(a.date));
}
function getList() {
    // 解构 queryParams 和 currentMonthIndex 为局部变量
    const { queryParams } = toRefs(data);
    const currentMonthIndex = computed(() => new Date().getMonth());

    // 获取当前选择的年份和当前年份
    const selectedYear = parseInt(queryParams.value.year);
    const currentYear = new Date().getFullYear();

    listConversion(selectedYear).then(res => {

        rawData.value = sortDataByDateDesc(res.data);
        number.value = rawData.value[0].number;
        getProcuctDrawing().then(res => {
            procuctDrawing.value = res.data;
            // 处理图表数据
            const monthlyData = processChartData(rawData.value, selectedYear);
            const displayMonths = selectedYear === currentYear ?
                months.value.slice(0, currentMonthIndex.value + 1) :
                months.value;

            // 将selectedYear和currentYear传递给updateChart
            updateChart(monthlyData, displayMonths, selectedYear, currentYear);
        });
    });
}


onMounted(() => {
    initChart();
    getList();
});
</script>