<template>
    <div class="bit-design-recommendation" v-loading="loading">
        <!-- 控制栏 -->
        <div class="control-bar">
            <div class="control-item">
                <label>开次:</label>
                <span class="control-value">{{ displayOpeningTimes }}</span>
            </div>
            <div class="control-item">
                <label>钻头尺寸mm:</label>
                <span class="control-value">{{ displayBitSize }}</span>
            </div>
            <div class="control-item">
                <label>开始深度:</label>
                <span class="control-value">{{ controlForm.depthRange[0] }} m</span>
            </div>
            <div class="control-item">
                <label>结束深度:</label>
                <span class="control-value">{{ controlForm.depthRange[1] }} m</span>
            </div>
            <!-- <el-button type="primary" @click="handleQuery">查询</el-button> -->
        </div>
        <!-- 主要内容区域 -->
        <div class="main-content">
            <!-- 上方推荐方案 -->
            <div class="recommendation-section">
                <div class="recommendation-panel">
                    <h3>钻头设计参数推荐</h3>
                    <el-table :data="[recommendationData]" border style="width: 100%">
                        <el-table-column prop="bladeCount" label="刀翼数个" min-width="120px" align="center" />
                        <el-table-column prop="density" label="布齿密度" min-width="120px" align="center" />
                        <el-table-column prop="toothSize" label="切削齿尺寸mm" min-width="120px" align="center" />
                        <el-table-column prop="negativeAngle" label="切削齿后倾角°" min-width="120px" align="center" />
                        <el-table-column prop="crownProfile" label="冠状轮廓" min-width="120px" align="center" />
                        <el-table-column label="操作" align="center" fixed="right" width="250px"
                            class-name="small-padding fixed-width">
                            <template slot-scope="scope">
                                <!-- <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                                    v-hasPermi="['jtzj:jtzjJzzg:edit']">修改</el-button>
                                <el-button size="mini" type="text" icon="el-icon-delete"
                                    @click="handleDelete(scope.row)"
                                    v-hasPermi="['jtzj:jtzjJzzg:remove']">删除</el-button> -->
                                <el-button size="mini" type="text" icon="el-icon-view"
                                    @click="handleUpdate(scope.row)">查看</el-button>
                                <el-button size="mini" type="text" icon="el-icon-connection"
                                    @click="handleMatchBit">匹配钻头</el-button>
                                <el-button size="mini" type="text" icon="el-icon-back"
                                    @click="handleBack">返回</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <!-- <div class="action-buttons">
                        <el-button type="primary" @click="handleMatchBit">匹配钻头</el-button>
                        <el-button @click="handleBack">返回</el-button>
                    </div> -->
                </div>
            </div>
            <!-- 下方图表区域 -->
            <div class="charts-section">
                <div class="charts-grid">
                    <!-- 刀翼总数 -->
                    <div class="chart-item">
                        <div ref="bladeChart1" class="chart" style="width: 100%; height:calc((100vh - 260px) / 2);">
                        </div>
                        <div class="chart-title">刀翼总数</div>
                    </div>
                    <!-- 布齿密度 -->
                    <div class="chart-item">
                        <div ref="bladeChart2" class="chart" style="width: 100%; height:calc((100vh - 260px) / 2);">
                        </div>
                        <div class="chart-title">布齿密度</div>
                    </div>
                    <!-- 切削齿尺寸 -->
                    <div class="chart-item">
                        <div ref="bladeChart3" class="chart" style="width: 100%; height: calc((100vh - 260px) / 2);">
                        </div>
                        <div class="chart-title">切削齿尺寸</div>
                    </div>
                    <!-- 切削齿后倾角 -->
                    <div class="chart-item">
                        <div ref="bladeChart4" class="chart" style="width: 100%; height: calc((100vh - 260px) / 2);">
                        </div>
                        <div class="chart-title">切削齿后倾角°</div>
                    </div>
                    <!-- 冠部轮廓 -->
                    <div class="chart-item">
                        <div ref="cuttingTeethChart1" class="chart"
                            style="width: 100%; height: calc((100vh - 260px) / 2);"></div>
                        <div class="chart-title">冠部轮廓</div>
                    </div>
                    <!-- 保径图表 -->
                    <!-- <div class="chart-item">
                        <div ref="gaugeChart" class="chart" style="width: 100%; height: calc((100vh - 260px) / 2);">
                        </div>
                        <div class="chart-title">
                            <div class="chart-title">保径</div>
                        </div>
                    </div> -->
                </div>
            </div>

        </div>
        <!-- 查看钻头信息弹窗 -->
        <el-dialog title="查看钻头信息" :visible.sync="viewDialogVisible" width="90%" append-to-body
            @close="handleViewDialogClose" class="view-dialog">
            <div v-if="viewDialogVisible" class="view-dialog-content">
                <BitSelectionInfo :bitData="selectedBitData" :hideHeader="true" :showValues="true"
                    @close="handleViewDialogClose" />
            </div>
        </el-dialog>
    </div>
</template>
<script>
import * as echarts from 'echarts'
import { getCjqxDataztyx, ztTj, ppZtxxx } from "@/api/system/cjsjLas";
import BitSelectionInfo from './BitSelectionInfo.vue';
export default {
    name: 'BitDesignRecommendation',
    components: {
        BitSelectionInfo
    },
    data() {
        return {
            controlForm: {
                openingTimes: '',
                depthRange: [],
                bitSize: ''
            },
            charts: {},
            currentOpeningInfo: '', // 当前开次信息
            debugInfo: '', // 调试信息
            displayOpeningTimes: '', // 显示的开次名称
            displayBitSize: '', // 显示的钻头尺寸
            // 接口返回的数据
            apiData: null,
            recommendationData: {
                bladeCount: '',
                toothSize: '',
                density: '',
                crownProfile: '',
                negativeAngle: ''
            },
            viewDialogVisible: false, // 查看弹窗显示状态
            selectedBitData: {}, // 选中的钻头数据
            loading: false // 加载状态
        }
    },
    mounted() {
        this.initFromQuery()
        this.$nextTick(() => {
            this.initCharts()
        })
    },
    beforeDestroy() {
        Object.values(this.charts).forEach(chart => {
            if (chart) {
                chart.dispose()
            }
        })
    },
    methods: {
        // 初始化页面参数
        initFromQuery() {
            console.log('initFromQuery 方法被调用了！');
            const query = this.$route.query;
            // 设置开次显示值
            if (query.openingTimes) {
                this.displayOpeningTimes = query.openingTimes;
                // 同时设置内部值用于其他逻辑
                const openingTimesMap = {
                    '一开': 'first',
                    '二开': 'second',
                    '三开': 'third',
                    '第三开次': 'third',
                    '第四开次': 'fourth',
                    '第五开次': 'fifth'
                };
                const mappedValue = openingTimesMap[query.openingTimes] || 'first';
                this.controlForm.openingTimes = mappedValue;
                console.log(`开次显示: ${query.openingTimes}`);
            }

            // 设置钻头尺寸显示值
            if (query.ztccValues) {
                try {
                    const ztccValues = JSON.parse(query.ztccValues);
                    if (ztccValues && ztccValues.length > 0) {
                        // 取第一个ztcc值作为显示的钻头尺寸
                        const firstZtcc = ztccValues[0].toString();
                        this.displayBitSize = `${firstZtcc}mm`;
                        this.controlForm.bitSize = firstZtcc;
                        console.log(`钻头尺寸显示: ${firstZtcc}mm`);
                    }
                } catch (e) {
                    console.warn('解析ztcc值失败:', e);
                }
            }

            if (query.startDepth && query.endDepth) {
                // 设置深度范围
                const startDepth = parseInt(query.startDepth);
                const endDepth = parseInt(query.endDepth);
                this.controlForm.depthRange = [startDepth, endDepth];

                console.log(`深度范围设置: ${startDepth} - ${endDepth}m`);
            }

            // 设置当前开次信息显示
            if (query.openingTimes && query.startDepth && query.endDepth) {
                this.currentOpeningInfo = `${query.openingTimes} (${query.startDepth}-${query.endDepth}m)`;
                console.log('当前开次信息:', this.currentOpeningInfo);

                // 显示成功消息
                this.$nextTick(() => {
                    this.$message.success(`已选择${query.openingTimes}: ${query.startDepth}-${query.endDepth}m`);
                });
            }

            // 打印最终的控制表单状态
            console.log('最终控制表单状态:', this.controlForm);

            // 设置调试信息显示
            if (query.jh || query.openingTimes) {
                this.debugInfo = `井号:${query.jh || '未知'} | 开次:${query.openingTimes || '未知'} | 数据点:${query.pointCount || '0'}`;
            }

            // 调用接口获取推荐数据
            this.fetchRecommendationData();
        },

        // 获取推荐数据
        fetchRecommendationData() {
            const query = this.$route.query;
            if (!query.jh || !query.startDepth || !query.endDepth) {
                let missingParams = [];
                if (!query.jh) missingParams.push('井号(jh)');
                if (!query.startDepth) missingParams.push('起始深度(startDepth)');
                if (!query.endDepth) missingParams.push('结束深度(endDepth)');

                const errorMsg = `缺少必要参数，无法调用推荐接口: ${missingParams.join(', ')}`;
                console.warn(errorMsg);
                this.$message.warning(`参数不完整: ${missingParams.join(', ')}`);
                return;
            }

            // 开始加载
            this.loading = true;

            // 解析 ztcc 值
            let ztcc = null;
            if (query.ztccValues) {
                try {
                    const ztccValues = JSON.parse(query.ztccValues);
                    if (Array.isArray(ztccValues) && ztccValues.length > 0) {
                        ztcc = ztccValues[0]; // 取第一个值
                    }
                } catch (e) {
                    console.warn('解析ztcc值失败:', e);
                }
            }

            const params = {
                jh: query.jh,
                ksjs: parseFloat(query.startDepth), // 开始井深
                jsjs: parseFloat(query.endDepth),   // 结束井深
                ztcc: ztcc,                         // 钻头尺寸
                kc: query.openingTimes              // 开次
            };

            console.log('调用ztTj接口，参数:', params);

            ztTj(params).then(response => {
                console.log('ztTj接口返回数据:', response);
                this.apiData = response;

                // 更新推荐方案表格
                this.updateRecommendationData(response);

                // 更新图表数据
                this.updateChartsWithApiData(response);

            }).catch(error => {
                console.error('调用ztTj接口失败:', error);
                this.$message.error('获取推荐数据失败，请重试');
            }).finally(() => {
                // 结束加载
                this.loading = false;
            });
        },

        // 更新推荐方案数据
        updateRecommendationData(data) {
            if (!data || !data.zttjfa) {
                console.warn('推荐方案数据格式错误');
                return;
            }

            const zttjfa = data.zttjfa;
            console.log('zttjfa推荐数据:', zttjfa);

            // 根据新的字段结构使用zttjfa中的推荐值
            // t01: 刀翼数, t02: 布齿密度, t03: 切削齿尺寸, t04: 切削齿后倾角, t05: 冠部轮廓, t06: 保径
            this.recommendationData = {
                bladeCount: zttjfa.t01 || '',
                toothSize: zttjfa.t03 || '',
                density: zttjfa.t02 || '',
                crownProfile: zttjfa.t05 || '',
                negativeAngle: zttjfa.t04 || ''
            };

            console.log('推荐方案数据已更新:', this.recommendationData);
        },

        // 使用接口数据更新图表
        updateChartsWithApiData(data) {
            if (!data) {
                console.warn('没有数据，无法更新图表');
                return;
            }

            console.log('开始更新图表，接收到的数据:', data);

            // 更新刀翼数图表 (blade1 对应 dys)
            if (data.dys && this.charts.blade1) {
                console.log('更新刀翼数图表:', data.dys);
                this.updateBladeChart(data.dys);
            }

            // 更新布齿密度图表 (blade2 对应 bcmd)
            if (data.bcmd && this.charts.blade2) {
                console.log('更新布齿密度图表:', data.bcmd);
                this.updateDensityChart(data.bcmd);
            }

            // 更新切削齿尺寸图表 (blade3 对应 qxccc)
            if (data.qxccc && this.charts.blade3) {
                console.log('更新切削齿尺寸图表:', data.qxccc);
                this.updateCuttingTeethSizeChart(data.qxccc);
            }

            // 更新切削齿后倾角图表 (blade4 对应 qxcfqj)
            if (data.qxcfqj && this.charts.blade4) {
                console.log('更新切削齿后倾角图表:', data.qxcfqj);
                this.updateCuttingTeethAngleChart(data.qxcfqj);
            }

            // 更新冠部轮廓图表 (cuttingTeeth1 对应 gblk)
            if (data.gblk && this.charts.cuttingTeeth1) {
                console.log('更新冠部轮廓图表:', data.gblk);
                this.updateCrownProfileChart(data.gblk);
            }

            // 更新保径图表 (gauge 对应 bjdata)
            if (data.bjdata && this.charts.gauge) {
                console.log('更新保径图表:', data.bjdata);
                this.updateGaugeChart(data.bjdata);
            }
        },

        // 更新刀翼数图表
        updateBladeChart(dysData) {
            if (!dysData || !dysData.X || !dysData.Y) {
                console.warn('刀翼数图表数据无效:', dysData);
                return;
            }

            console.log('更新刀翼数图表 - X轴:', dysData.X, 'Y轴:', dysData.Y);

            // 直接使用后台返回的数据
            let displayData = [...dysData.Y]; // 复制原始数据

            this.charts.blade1.setOption({
                title: { text: '刀翼数', left: 'center', top: 10, textStyle: { fontSize: 12 } },
                tooltip: {
                    trigger: 'axis',
                    formatter: '{b}: {c}'
                },
                grid: { top: 40, left: 40, right: 20, bottom: 30 },
                xAxis: {
                    type: 'category',
                    data: dysData.X,
                    axisLabel: {
                        rotate: 45,
                        fontSize: 10
                    }
                },
                yAxis: {
                    type: 'value',
                    name: '次数',
                    // max: 100
                },
                series: [
                    {
                        name: '刀翼数',
                        type: 'bar',
                        barWidth: 50,
                        data: displayData,
                        itemStyle: {
                            color: '#5087ec'
                        },
                        label: {
                            show: true,
                            position: 'top',
                            formatter: '{c}'
                        }
                    }
                ]
            });
        },

        // 更新布齿密度图表
        updateDensityChart(bcmdData) {
            if (!bcmdData || !bcmdData.X || !bcmdData.Y) {
                console.warn('布齿密度图表数据无效:', bcmdData);
                return;
            }

            console.log('更新布齿密度图表 - X轴:', bcmdData.X, 'Y轴:', bcmdData.Y);

            // 直接使用后台返回的数据
            let displayData = [...bcmdData.Y]; // 复制原始数据

            this.charts.blade2.setOption({
                title: { text: '布齿密度', left: 'center', top: 10, textStyle: { fontSize: 12 } },
                tooltip: {
                    trigger: 'axis',
                    formatter: '{b}: {c}'
                },
                grid: { top: 40, left: 40, right: 20, bottom: 30 },
                xAxis: {
                    type: 'category',
                    data: bcmdData.X
                },
                yAxis: {
                    type: 'value',
                    name: '次数',
                    // max: 100
                },
                series: [
                    {
                        name: '布齿密度',
                        type: 'bar',
                        barWidth: 50,
                        data: displayData,
                        itemStyle: {
                            color: '#5087ec'
                        },
                        label: {
                            show: true,
                            position: 'top',
                            formatter: '{c}'
                        }
                    }
                ]
            });
        },

        // 更新切削齿尺寸图表
        updateCuttingTeethSizeChart(qxcccData) {
            if (!qxcccData || !qxcccData.X || !qxcccData.Y) {
                console.warn('切削齿尺寸图表数据无效:', qxcccData);
                return;
            }

            console.log('更新切削齿尺寸图表 - X轴:', qxcccData.X, 'Y轴:', qxcccData.Y);

            // 直接使用后台返回的数据
            let displayData = [...qxcccData.Y]; // 复制原始数据

            this.charts.blade3.setOption({
                title: { text: '切削齿尺寸', left: 'center', top: 10, textStyle: { fontSize: 12 } },
                tooltip: {
                    trigger: 'axis',
                    formatter: '{b}mm: {c}'
                },
                grid: { top: 40, left: 40, right: 20, bottom: 30 },
                xAxis: {
                    type: 'category',
                    data: qxcccData.X
                },
                yAxis: {
                    type: 'value',
                    name: '次数',
                    // max: 100
                },
                series: [
                    {
                        name: '切削齿尺寸',
                        type: 'bar',
                        barWidth: 50,
                        data: displayData,
                        itemStyle: {
                            color: '#5087ec'
                        },
                        label: {
                            show: true,
                            position: 'top',
                            formatter: '{c}'
                        }
                    }
                ]
            });
        },

        // 更新切削齿后倾角图表
        updateCuttingTeethAngleChart(qxcfqjData) {
            if (!qxcfqjData || !qxcfqjData.X || !qxcfqjData.Y) {
                console.warn('切削齿后倾角图表数据无效:', qxcfqjData);
                return;
            }

            console.log('更新切削齿后倾角图表 - X轴:', qxcfqjData.X, 'Y轴:', qxcfqjData.Y);

            // 直接使用后台返回的数据
            let displayData = [...qxcfqjData.Y]; // 复制原始数据

            this.charts.blade4.setOption({
                title: { text: '切削齿后倾角°', left: 'center', top: 10, textStyle: { fontSize: 12 } },
                tooltip: {
                    trigger: 'axis',
                    formatter: '{b}°: {c}'
                },
                grid: { top: 40, left: 40, right: 20, bottom: 30 },
                xAxis: {
                    type: 'category',
                    data: qxcfqjData.X
                },
                yAxis: {
                    type: 'value',
                    name: '次数',
                    // max: 100
                },
                series: [
                    {
                        name: '切削齿后倾角°',
                        type: 'bar',
                        barWidth: 50,
                        data: displayData,
                        itemStyle: {
                            color: '#5087ec'
                        },
                        label: {
                            show: true,
                            position: 'top',
                            formatter: '{c}'
                        }
                    }
                ]
            });
        },

        // 更新冠部轮廓图表
        updateCrownProfileChart(gblkData) {
            if (!gblkData || !gblkData.X || !gblkData.Y) {
                console.warn('冠部轮廓图表数据无效:', gblkData);
                return;
            }

            console.log('更新冠部轮廓图表 - X轴:', gblkData.X, 'Y轴:', gblkData.Y);

            // 直接使用后台返回的数据
            let displayData = [...gblkData.Y]; // 复制原始数据

            this.charts.cuttingTeeth1.setOption({
                title: { text: '冠部轮廓', left: 'center', top: 10, textStyle: { fontSize: 12 } },
                tooltip: {
                    trigger: 'axis',
                    formatter: '{b}: {c}'
                },
                grid: { top: 40, left: 40, right: 20, bottom: 30 },
                xAxis: {
                    type: 'category',
                    data: gblkData.X,
                    axisLabel: {
                        rotate: 30,
                        fontSize: 10
                    }
                },
                yAxis: {
                    type: 'value',
                    name: '次数',
                    // max: 100
                },
                series: [
                    {
                        name: '冠部轮廓',
                        type: 'bar',
                        barWidth: 50,
                        data: displayData,
                        itemStyle: {
                            color: '#5087ec'
                        },
                        label: {
                            show: true,
                            position: 'top',
                            formatter: '{c}'
                        }
                    }
                ]
            });
        },

        // 更新保径图表
        updateGaugeChart(bjdataArray) {
            if (!Array.isArray(bjdataArray)) {
                console.warn('保径图表数据无效:', bjdataArray);
                return;
            }

            console.log('更新保径图表:', bjdataArray);

            // 直接使用后台返回的数据
            let pieData = bjdataArray.map(item => ({
                name: item.name,
                value: item.value
            }));

            this.charts.gauge.setOption({
                title: { text: '保径', left: 'center', top: 10, textStyle: { fontSize: 12 } },
                tooltip: {
                    trigger: 'item',
                    formatter: '{b}: {c}%'
                },
                series: [
                    {
                        type: 'pie',
                        radius: '60%',
                        center: ['50%', '60%'],
                        data: pieData,
                        itemStyle: {
                            color: function (params) {
                                return params.name === '常规' ? '#5087ec' : '#67c23a';
                            }
                        },
                        label: {
                            formatter: '{b}: {c}%'
                        },
                        emphasis: {
                            itemStyle: {
                                shadowBlur: 10,
                                shadowOffsetX: 0,
                                shadowColor: 'rgba(0, 0, 0, 0.5)'
                            }
                        }
                    }
                ]
            });
        },

        initCharts() {
            this.initBladeCharts()
            this.initCuttingTeethCharts()
            this.initGaugeChart()
        },

        initBladeCharts() {
            // 刀翼图表1 - 刀翼数
            if (this.$refs.bladeChart1) {
                this.charts.blade1 = echarts.init(this.$refs.bladeChart1)
                this.charts.blade1.setOption({
                    title: { text: '刀翼数', left: 'center', top: 10, textStyle: { fontSize: 12 } },
                    tooltip: { trigger: 'axis' },
                    grid: { top: 40, left: 40, right: 20, bottom: 30 },
                    xAxis: { type: 'category', data: ['低', '中', '高'] },
                    yAxis: { type: 'value', name: '百分' },
                    series: [
                        { name: '刀翼数', type: 'bar', barWidth: 30, data: [] }
                    ]
                })
            }

            // 刀翼图表2 - 布齿密度
            if (this.$refs.bladeChart2) {
                this.charts.blade2 = echarts.init(this.$refs.bladeChart2)
                this.charts.blade2.setOption({
                    title: { text: '布齿密度', left: 'center', top: 10, textStyle: { fontSize: 12 } },
                    tooltip: { trigger: 'axis' },
                    grid: { top: 40, left: 40, right: 20, bottom: 30 },
                    xAxis: { type: 'category', data: ['低', '中', '高'] },
                    yAxis: { type: 'value', name: '百分' },
                    series: [
                        { type: 'bar', barWidth: 30, data: [] }
                    ]
                })
            }

            // 刀翼图表3 - 切削齿尺寸
            if (this.$refs.bladeChart3) {
                this.charts.blade3 = echarts.init(this.$refs.bladeChart3)
                this.charts.blade3.setOption({
                    title: { text: '切削齿尺寸', left: 'center', top: 10, textStyle: { fontSize: 12 } },
                    tooltip: { trigger: 'axis' },
                    grid: { top: 40, left: 40, right: 20, bottom: 30 },
                    xAxis: { type: 'category', data: [4, 5, 6, 7, 8] },
                    yAxis: { type: 'value', name: '百分' },
                    series: [
                        { name: '切削齿尺寸', type: 'bar', barWidth: 30, data: [] }
                    ]
                })
            }

            // 刀翼图表4 - 切削齿后倾角
            if (this.$refs.bladeChart4) {
                this.charts.blade4 = echarts.init(this.$refs.bladeChart4)
                this.charts.blade4.setOption({
                    title: { text: '切削齿后倾角°', left: 'center', top: 10, textStyle: { fontSize: 12 } },
                    tooltip: { trigger: 'axis' },
                    grid: { top: 40, left: 40, right: 20, bottom: 30 },
                    xAxis: { type: 'category', data: [4, 5, 6, 7, 8] },
                    yAxis: { type: 'value', name: '百分' },
                    series: [
                        { name: '切削齿后倾角°', type: 'bar', barWidth: 30, data: [] }
                    ]
                })
            }
        },

        initCuttingTeethCharts() {
            // 切削齿图表1 - 冠部轮廓
            if (this.$refs.cuttingTeethChart1) {
                this.charts.cuttingTeeth1 = echarts.init(this.$refs.cuttingTeethChart1)
                this.charts.cuttingTeeth1.setOption({
                    title: { text: '冠部轮廓', left: 'center', top: 10, textStyle: { fontSize: 12 } },
                    tooltip: { trigger: 'axis' },
                    grid: { top: 40, left: 40, right: 20, bottom: 30 },
                    xAxis: { type: 'category', data: ['长剖面', '中剖面', '短剖面', '平剖面'] },
                    yAxis: { type: 'value', name: '百分' },
                    series: [
                        { name: '冠部轮廓', type: 'bar', barWidth: 30, data: [] }
                    ]
                })
            }
        },

        initGaugeChart() {
            // 保径图表 - 饼图
            if (this.$refs.gaugeChart) {
                this.charts.gauge = echarts.init(this.$refs.gaugeChart)
                this.charts.gauge.setOption({
                    title: { text: '保径', left: 'center', top: 10, textStyle: { fontSize: 12 } },
                    tooltip: { trigger: 'item' },
                    series: [
                        {
                            type: 'pie',
                            radius: '60%',
                            center: ['50%', '60%'],
                            data: [
                                { value: 85, name: '常规', itemStyle: { color: '#409EFF' } },
                                { value: 15, name: '增强', itemStyle: { color: '#67C23A' } }
                            ],
                            label: {
                                formatter: '{b}: {c}%'
                            }
                        }
                    ]
                })
            }
        },

        handleQuery() {
            console.log('查询条件:', this.controlForm)
            // 这里可以调用API获取数据并更新图表
        },

        handleMatchBit() {
            console.log('匹配钻头')

            // 获取ztcc值
            let ztcc = null;
            if (this.$route.query.ztccValues) {
                try {
                    const ztccValues = JSON.parse(this.$route.query.ztccValues);
                    if (Array.isArray(ztccValues) && ztccValues.length > 0) {
                        ztcc = ztccValues[0];
                    }
                } catch (e) {
                    console.warn('解析ztcc值失败:', e);
                }
            }

            // 构建查询参数
            const queryParams = {
                from: 'recommendation',
                jh: this.$route.query.jh,
                qk: this.$route.query.qk,
                ztcc: ztcc
            };

            // 如果有推荐数据，添加t01-t06参数
            if (this.apiData && this.apiData.zttjfa) {
                const zttjfa = this.apiData.zttjfa;
                queryParams.t01 = zttjfa.t01; // 刀翼数
                queryParams.t02 = zttjfa.t02; // 布齿密度
                queryParams.t03 = zttjfa.t03; // 切削齿尺寸
                queryParams.t04 = zttjfa.t04; // 切削齿后倾角
                queryParams.t05 = zttjfa.t05; // 冠部轮廓
                // queryParams.t06 = zttjfa.t06; // 保径
            }

            console.log('跳转参数:', queryParams);

            // 跳转到钻头匹配页面
            this.$router.push({
                name: 'BitMatching',
                query: queryParams
            })
        },

        // 添加返回按钮处理方法
        handleBack() {
            console.log('返回上一页')
            // 根据来源页面决定返回路径
            const from = this.$route.query.from || 'main'
            if (from === 'main') {
                // 返回BitDesign页面时，需要传递必要的参数
                const queryParams = {
                    jh: this.$route.query.jh,  // 井号
                    qk: this.$route.query.qk   // 区块
                };
                console.log('返回BitDesign页面，传递参数:', queryParams);
                this.$router.push({
                    name: 'BitDesign',
                    query: queryParams
                })
            } else {
                this.$router.go(-1)
            }
        },

        // 处理查看按钮点击
        handleUpdate(row) {
            console.log('查看钻头信息', row);

            // 先构建基础数据
            const zttjfa = (this.apiData && this.apiData.zttjfa) || {};
            const recData = this.recommendationData;

            // 构建基础钻头数据
            this.selectedBitData = {
                ztxh: zttjfa.ztxh || '',
                ztcc: this.controlForm.bitSize || this.displayBitSize.replace('mm', '') || '',
                ztlb: zttjfa.ztlb || '',
                ztbh: zttjfa.ztbh || '',
                // 参数值 - 使用推荐方案表格中显示的值
                tzdm01: recData.bladeCount || zttjfa.t01 || '',
                tzdm02: recData.density || zttjfa.t02 || '',
                tzdm03: recData.toothSize || zttjfa.t03 || '',
                tzdm04: recData.negativeAngle || zttjfa.t04 || '',
                tzdm05: recData.crownProfile || zttjfa.t05 || '',
                tzdm06: zttjfa.t06 || '',
                // 图片（如果有的话）
                slt01: zttjfa.slt01 || '',
                slt02: zttjfa.slt02 || '',
                slt03: zttjfa.slt03 || '',
                slt04: zttjfa.slt04 || '',
                slt05: zttjfa.slt05 || '',
                slt06: zttjfa.slt06 || '',
                // 匹配状态（推荐方案中显示为"推荐"）
                t01match: recData.bladeCount ? '推荐' : '',
                t02match: recData.density ? '推荐' : '',
                t03match: recData.toothSize ? '推荐' : '',
                t04match: recData.negativeAngle ? '推荐' : '',
                t05match: recData.crownProfile ? '推荐' : '',
                t06match: zttjfa.t06 ? '推荐' : ''
            };

            // 调用 ppZtxxx 接口并更新数据
            this.callPpZtxxx().then(() => {
                console.log('构建的钻头数据:', this.selectedBitData);
                this.viewDialogVisible = true;
            }).catch(() => {
                // 即使接口失败也打开弹窗，使用基础数据
                console.log('接口调用失败，使用基础数据:', this.selectedBitData);
                this.viewDialogVisible = true;
            });
        },

        // 调用 ppZtxxx 接口
        callPpZtxxx() {
            const query = this.$route.query;
            const zttjfa = (this.apiData && this.apiData.zttjfa) || {};

            // 获取 ztcc 值
            let ztcc = null;
            if (query.ztccValues) {
                try {
                    const ztccValues = JSON.parse(query.ztccValues);
                    if (Array.isArray(ztccValues) && ztccValues.length > 0) {
                        ztcc = ztccValues[0];
                    }
                } catch (e) {
                    console.warn('解析ztcc值失败:', e);
                }
            }

            // 构建接口参数
            const params = {
                jh: query.jh || '',
                qk: query.qk || '',
                ztcc: ztcc || '',
                t01: zttjfa.t01 || '',
                t02: zttjfa.t02 || '',
                t03: zttjfa.t03 || '',
                t04: zttjfa.t04 || '',
                t05: zttjfa.t05 || '',
                t06: zttjfa.t06 || ''
            };

            console.log('调用 ppZtxxx 接口，参数:', params);

            return ppZtxxx(params).then(response => {
                console.log('ppZtxxx 接口返回数据:', response);

                // 根据返回的数据更新 selectedBitData
                if (response && response.data) {
                    const data = response.data;

                    // 辅助函数：处理数组数据，保存所有有图片的项
                    const processItems = (items, prefix) => {
                        if (!items || !Array.isArray(items) || items.length === 0) {
                            return;
                        }

                        // 过滤出有图片的项
                        const itemsWithImage = items.filter(item => item.slt && item.slt.trim() !== '');

                        // 如果有有图片的项，使用它们；否则使用所有项
                        const validItems = itemsWithImage.length > 0 ? itemsWithImage : items;

                        // 保存第一个项的 tzdm（用于显示参数值）
                        if (validItems.length > 0 && validItems[0].tzdm) {
                            this.selectedBitData[`tzdm${prefix}`] = validItems[0].tzdm;
                        }

                        // 保存所有项的图片和名称（数组形式）
                        this.selectedBitData[`slt${prefix}List`] = validItems.map(item => ({
                            slt: item.slt || '',
                            tzxl: item.tzxl || ''
                        }));
                    };

                    // 更新 t01 (刀翼总数)
                    processItems(data.t01, '01');

                    // 更新 t02 (布齿密度)
                    processItems(data.t02, '02');

                    // 更新 t03 (切削齿尺寸)
                    processItems(data.t03, '03');

                    // 更新 t04 (切削齿后倾角)
                    processItems(data.t04, '04');

                    // 更新 t05 (冠部轮廓)
                    processItems(data.t05, '05');

                    console.log('根据接口返回数据更新后的 selectedBitData:', this.selectedBitData);
                }
            }).catch(error => {
                console.error('调用 ppZtxxx 接口失败:', error);
                // 返回 rejected promise，让调用方知道失败了
                return Promise.reject(error);
            });
        },

        // 关闭查看弹窗
        handleViewDialogClose() {
            this.viewDialogVisible = false;
            this.selectedBitData = {};
        }
    }
}
</script>

<style lang="scss" scoped>
.bit-design-recommendation {
    padding: 5px;

    .control-bar {
        display: flex;
        align-items: center;
        gap: 20px;
        margin-bottom: 5px;
        padding: 5px;
        background-color: #f5f7fa;
        border-radius: 4px;

        .control-item {
            display: flex;
            align-items: center;
            gap: 8px;

            label {
                font-weight: bold;
                color: #333;
                white-space: nowrap;
            }

            .control-value {
                background-color: #f5f7fa;
                color: #333;
                padding: 6px 12px;
                border-radius: 4px;
                font-weight: bold;
                border: 1px solid #dcdfe6;
                min-width: 80px;
                text-align: center;
            }

            .opening-info {
                background-color: #e6f7ff;
                color: #1890ff;
                padding: 4px 8px;
                border-radius: 4px;
                font-weight: bold;
                border: 1px solid #91d5ff;
            }

            .debug-info {
                background-color: #fff2e8;
                color: #fa8c16;
                padding: 4px 8px;
                border-radius: 4px;
                font-size: 12px;
                border: 1px solid #ffbb96;
                font-family: monospace;
            }
        }
    }

    .main-content {
        display: flex;
        flex-direction: column;
        gap: 20px;

        .charts-section {
            flex: 1;

            .charts-grid {
                display: grid;
                grid-template-columns: repeat(3, 1fr);
                gap: 15px;

                .chart-item {
                    background-color: #fff;
                    border: 1px solid #e4e7ed;
                    border-radius: 4px;
                    padding: 10px;

                    .chart {
                        border-radius: 4px;
                    }

                    .chart-title {
                        text-align: center;
                        margin-top: 5px;
                        font-size: 12px;
                        color: #666;
                    }
                }
            }
        }

        .recommendation-section {
            width: 100%;

            .recommendation-panel {
                width: 100%;
                background-color: #fff;
                border: 1px solid #e4e7ed;
                border-radius: 4px;
                padding: 20px;

                h3 {
                    margin: 0 0 15px 0;
                    text-align: center;
                    color: #333;
                }

                .action-buttons {
                    margin-top: 20px;
                    text-align: center;
                }
            }
        }
    }

    .view-dialog {
        :deep(.el-dialog__body) {
            padding: 0 !important;
            background-color: #f5f7fa;
            overflow: hidden;
        }

        :deep(.el-dialog) {
            margin-top: 5vh !important;
        }

        :deep(.el-dialog__header) {
            padding: 20px 20px 10px;
            background-color: #fff;
        }

        .view-dialog-content {
            padding: 0;
            overflow: hidden;
        }
    }
}
</style>
