import * as echarts from '../../components/ec-canvas/echarts';

Page({
  data: {
    initScatterData : [],
    ecLine: {
      onInit: function (canvas, width, height, dpr) {
        const lineChart = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr // new
        });
        canvas.setChart(lineChart);
        lineChart.setOption(getLineOption());

        return lineChart;
      }
    },
    ecInitScatter: {
      onInit: function (canvas, width, height, dpr) {
        const initScatter = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr
        });
        canvas.setChart(initScatter);
        getInitScatterOption().then(option => {
          initScatter.setOption(option)
        });

        return initScatter;
      }
    },
  ecMidScatter: {
    onInit: function (canvas, width, height, dpr) {
      const midScatter = echarts.init(canvas, null, {
        width: width,
        height: height,
        devicePixelRatio: dpr // new
      });
      canvas.setChart(midScatter);
      getMidScatterOption().then(option => {
        midScatter.setOption(option)
      });

      return midScatter;
    }
  },
    ecFinalScatter: {
      onInit: function (canvas, width, height, dpr) {
        const finalScatter = echarts.init(canvas, null, {
          width: width,
          height: height,
          devicePixelRatio: dpr // new
        });
        canvas.setChart(finalScatter);
        getFinalScatterOption().then(option => {
          finalScatter.setOption(option)
        });

        return finalScatter;
      }
    },
  },

  onReady() {
    // You can add any additional logic here if needed
  }
});


function getInitScatterOption() {
  const fetchScatterData = () => {
    return new Promise((resolve, reject) => {
      wx.request({
        url: 'https://soilgd.com:5000/model-scatter-data/7',
        method: 'GET',
        timeout: 5000,
        success: (res) => {
          console.log('接口响应:', res);
          // 校验状态码
          if (res.statusCode !== 200) {
            reject(new Error(`请求失败，状态码: ${res.statusCode}`));
            return;
          }

          // 校验数据结构
          if (!res.data?.scatter_data || !Array.isArray(res.data.scatter_data)) {
            reject(new Error('接口数据格式错误'));
            return;
          }

          resolve(res.data.scatter_data);
        },
        fail: (err) => {
          reject(new Error(`网络错误: ${err.errMsg}`));
        }
      });
    });
  };
  
    // 核心计算逻辑
    const calculateChartOptions = (scatterData) => {
      const calculateDataRange = (data) => {
        const xValues = data.map(item => item[0]);
        const yValues = data.map(item => item[1]);
        
        return {
          xMin: Math.min(...xValues),
          xMax: Math.max(...xValues),
          yMin: Math.min(...yValues),
          yMax: Math.max(...yValues)
        };
      };
  
      const range = calculateDataRange(scatterData);
      console.log(scatterData)
      const padding = 0.1;
      const xMin = range.xMin - Math.abs(range.xMin * padding);
      const xMax = range.xMax + Math.abs(range.xMax * padding);
      const yMin = range.yMin - Math.abs(range.yMin * padding);
      const yMax = range.yMax + Math.abs(range.yMax * padding);
      const axisMin = Math.min(xMin, yMin);
      const axisMax = Math.max(xMax, yMax);
  
      return {
        tooltip: {
          trigger: 'axis',
          axisPointer: { type: 'cross' }
        },
        grid: {
          left: '3%',
          right: '22%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          name: 'True Values',
          type: 'value',
          min: axisMin,
          max: axisMax,
          axisLabel: {
            formatter: value => parseFloat(value).toFixed(2)
          }
        },
        yAxis: {
          name: 'Predicted Values',
          type: 'value',
          min: parseFloat(axisMin).toFixed(2),
          max: parseFloat(axisMax).toFixed(2)
        },
        series: [
          {
            name: 'True vs Predicted',
            type: 'scatter',
            data: scatterData,
            symbolSize: 10,
            itemStyle: {
              color: '#1f77b4',
              opacity: 0.7,
              borderColor: '#fff',
              borderWidth: 0.5
            },
          },
          {
            name: 'Trendline',
            type: 'line',
            data: [[axisMin, axisMin], [axisMax, axisMax]],
            lineStyle: {
              type: 'dashed',
              color: '#ff7f0e',
              width: 2
            }
          }
        ]
      };
    };
  
  return new Promise(async (resolve) => {
    let retryCount = 0;
    const maxRetries = 2;

    while (retryCount <= maxRetries) {
      try {
        const scatterData = await fetchScatterData();
        resolve(calculateChartOptions(scatterData));
        return;
      } catch (error) {
        console.error(`第 ${retryCount + 1} 次尝试失败:`, error);
        
        if (retryCount === maxRetries) {
          resolve({
            xAxis: { show: false },
            yAxis: { show: false },
            series: [{
              type: 'scatter',
              data: [],
              silent: true
            }],
            graphic: {
              type: 'text',
              text: '数据加载失败',
            }
          })
        }
        retryCount++;
        await new Promise(r => setTimeout(r, 1000)); // 1秒后重试
        }
      }
    });
  }
// 反酸模型  中间代  散点图
function getMidScatterOption() {
  /**
   * 计算数据的最大最小值
   * @param {Array} data - 散点数据数组
   * @returns {Object} 包含 xMin, xMax, yMin, yMax 的对象
   */
  const fetchScatterData = () => {
    return new Promise((resolve, reject) => {
      wx.request({
        url: 'https://soilgd.com:5000/model-scatter-data/6',
        method: 'GET',
        timeout: 5000,
        success: (res) => {
          console.log('接口响应:', res);
          // 校验状态码
          if (res.statusCode !== 200) {
            reject(new Error(`请求失败，状态码: ${res.statusCode}`));
            return;
          }

          // 校验数据结构
          if (!res.data?.scatter_data || !Array.isArray(res.data.scatter_data)) {
            reject(new Error('接口数据格式错误'));
            return;
          }

          resolve(res.data.scatter_data);
        },
        fail: (err) => {
          reject(new Error(`网络错误: ${err.errMsg}`));
        }
      });
    });
  };
  
    // 核心计算逻辑
    const calculateChartOptions = (scatterData) => {
      const calculateDataRange = (data) => {
        const xValues = data.map(item => item[0]);
        const yValues = data.map(item => item[1]);
        
        return {
          xMin: Math.min(...xValues),
          xMax: Math.max(...xValues),
          yMin: Math.min(...yValues),
          yMax: Math.max(...yValues)
        };
      };
  
      const range = calculateDataRange(scatterData);
      console.log(scatterData)
      const padding = 0.1;
      const xMin = range.xMin - Math.abs(range.xMin * padding);
      const xMax = range.xMax + Math.abs(range.xMax * padding);
      const yMin = range.yMin - Math.abs(range.yMin * padding);
      const yMax = range.yMax + Math.abs(range.yMax * padding);
      const axisMin = Math.min(xMin, yMin);
      const axisMax = Math.max(xMax, yMax);
  
      return {
        tooltip: {
          trigger: 'axis',
          axisPointer: { type: 'cross' }
        },
        grid: {
          left: '3%',
          right: '22%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          name: 'True Values',
          type: 'value',
          min: axisMin,
          max: axisMax,
          axisLabel: {
            formatter: value => parseFloat(value).toFixed(2)
          }
        },
        yAxis: {
          name: 'Predicted Values',
          type: 'value',
          min: parseFloat(axisMin).toFixed(2),
          max: parseFloat(axisMax).toFixed(2)
        },
        series: [
          {
            name: 'True vs Predicted',
            type: 'scatter',
            data: scatterData,
            symbolSize: 10,
            itemStyle: {
              color: '#1f77b4',
              opacity: 0.7,
              borderColor: '#fff',
              borderWidth: 0.5
            },
          },
          {
            name: 'Trendline',
            type: 'line',
            data: [[axisMin, axisMin], [axisMax, axisMax]],
            lineStyle: {
              type: 'dashed',
              color: '#ff7f0e',
              width: 2
            }
          }
        ]
      };
    };
  
  return new Promise(async (resolve) => {
    let retryCount = 0;
    const maxRetries = 2;

    while (retryCount <= maxRetries) {
      try {
        const scatterData = await fetchScatterData();
        resolve(calculateChartOptions(scatterData));
        return;
      } catch (error) {
        console.error(`第 ${retryCount + 1} 次尝试失败:`, error);
        
        if (retryCount === maxRetries) {
          resolve({
            xAxis: { show: false },
            yAxis: { show: false },
            series: [{
              type: 'scatter',
              data: [],
              silent: true
            }],
            graphic: {
              type: 'text',
              text: '数据加载失败',
            }
          })
        }
        retryCount++;
        await new Promise(r => setTimeout(r, 1000)); // 1秒后重试
        }
      }
    });
  }
// 反酸模型  最终代  散点图
function getFinalScatterOption() {
  /**
   * 计算数据的最大最小值
   * @param {Array} data - 散点数据数组
   * @returns {Object} 包含 xMin, xMax, yMin, yMax 的对象
   */
  const fetchScatterData = () => {
    return new Promise((resolve, reject) => {
      wx.request({
        url: 'https://soilgd.com:5000/model-scatter-data/25',
        method: 'GET',
        timeout: 5000,
        success: (res) => {
          console.log('接口响应:', res);
          // 校验状态码
          if (res.statusCode !== 200) {
            reject(new Error(`请求失败，状态码: ${res.statusCode}`));
            return;
          }

          // 校验数据结构
          if (!res.data?.scatter_data || !Array.isArray(res.data.scatter_data)) {
            reject(new Error('接口数据格式错误'));
            return;
          }

          resolve(res.data.scatter_data);
        },
        fail: (err) => {
          reject(new Error(`网络错误: ${err.errMsg}`));
        }
      });
    });
  };
  
    // 核心计算逻辑
    const calculateChartOptions = (scatterData) => {
      const calculateDataRange = (data) => {
        const xValues = data.map(item => item[0]);
        const yValues = data.map(item => item[1]);
        
        return {
          xMin: Math.min(...xValues),
          xMax: Math.max(...xValues),
          yMin: Math.min(...yValues),
          yMax: Math.max(...yValues)
        };
      };
  
      const range = calculateDataRange(scatterData);
      console.log(scatterData)
      const padding = 0.1;
      const xMin = range.xMin - Math.abs(range.xMin * padding);
      const xMax = range.xMax + Math.abs(range.xMax * padding);
      const yMin = range.yMin - Math.abs(range.yMin * padding);
      const yMax = range.yMax + Math.abs(range.yMax * padding);
      const axisMin = Math.min(xMin, yMin);
      const axisMax = Math.max(xMax, yMax);
  
      return {
        tooltip: {
          trigger: 'axis',
          axisPointer: { type: 'cross' }
        },
        grid: {
          left: '3%',
          right: '22%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          name: 'True Values',
          type: 'value',
          min: axisMin,
          max: axisMax,
          axisLabel: {
            formatter: value => parseFloat(value).toFixed(2)
          }
        },
        yAxis: {
          name: 'Predicted Values',
          type: 'value',
          min: parseFloat(axisMin).toFixed(2),
          max: parseFloat(axisMax).toFixed(2)
        },
        series: [
          {
            name: 'True vs Predicted',
            type: 'scatter',
            data: scatterData,
            symbolSize: 10,
            itemStyle: {
              color: '#1f77b4',
              opacity: 0.7,
              borderColor: '#fff',
              borderWidth: 0.5
            },
          },
          {
            name: 'Trendline',
            type: 'line',
            data: [[axisMin, axisMin], [axisMax, axisMax]],
            lineStyle: {
              type: 'dashed',
              color: '#ff7f0e',
              width: 2
            }
          }
        ]
      };
    };
  
  return new Promise(async (resolve) => {
    let retryCount = 0;
    const maxRetries = 2;

    while (retryCount <= maxRetries) {
      try {
        const scatterData = await fetchScatterData();
        resolve(calculateChartOptions(scatterData));
        return;
      } catch (error) {
        console.error(`第 ${retryCount + 1} 次尝试失败:`, error);
        
        if (retryCount === maxRetries) {
          resolve({
            xAxis: { show: false },
            yAxis: { show: false },
            series: [{
              type: 'scatter',
              data: [],
              silent: true
            }],
            graphic: {
              type: 'text',
              text: '数据加载失败',
            }
          })
        }
        retryCount++;
        await new Promise(r => setTimeout(r, 1000)); // 1秒后重试
        }
      }
    });
  }

function getLineOption() {
  return {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['Random Forest', 'XGBoost', 'Gradient Boosting']  // 模型名称
    },
    grid: {
      left: '3%',
      right: '17%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      name: '模型迭代',
      type: 'category',
      boundaryGap: false,
      data: ['1代','2代','3代','4代','5代','6代','7代','8代','9代']  // train_sizes按10%递增
    },
    yAxis: {
      name: 'Score (R^2)',
      type: 'value'
    },
    series: [
      {
        name: 'Random Forest',
        type: 'line',
        data: [-0.17101591951095463, -0.556719360354051, -0.04083550751401055, -0.20858221504075436, 0.07297292282221035, 0.19857845644421734, 0.28407131176770184, 0.27979356883596496, 0.36904808817286416, 0.4183018571701477]  // 使用您的实际R2分数数据
      },
      {
        name: 'XGBoost',
        type: 'line',
        data: [-1.1811781145886937, -1.5645641005612534, -0.12619079632263497, 0.03324096120721032, 0.06969290639267578, 0.12375262461601955, 0.5331670468884062, 0.49454793164801647, 0.31904329339597803, 0.2712670704381914]
      },
      {
        name: 'Gradient Boosting',
        type: 'line',
        data: [-0.8583039298789095, -1.073316171952042, 0.09659300885027666, 0.06097833957434784, 0.191975498544109, 0.3718334600546489, 0.3948098332187753, 0.4398778520728397, 0.452609022210963, 0.41484634172723023]
      }
    ]
  };
}
