<template>
  <div class="drilling-time-chart-container" v-loading="loading">
    <div v-if="jh" class="well-number-display">
      <span class="well-label">井号:</span>
      <span class="well-number">{{ jh }}</span>
    </div>
    <div class="chart-wrapper">
      <!-- <el-button type="primary" icon="el-icon-download" size="small" class="export-btn" @click="exportChart"
                :disabled="!myChart">
                导出图片
            </el-button> -->
      <div id="drillingTimeChart" class="chart"></div>
    </div>
  </div>
</template>

<script>
import * as echarts from "echarts";
import { getljqxData } from "@/api/system/cjsjLas";
import { listLjSssjSd } from "@/api/optimization/ljSssjSd";

export default {
  name: "DrillingTimeChart",
  props: {
    jh: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      chartData: null,
      myChart: null,
      resizeHandler: null,
      loading: false,
    };
  },
  mounted() {
    this.loadChartData();
    this.$once("hook:beforeDestroy", this.cleanup);
  },
  watch: {
    jh: {
      handler() {
        this.loadChartData();
      },
      immediate: false,
    },
  },
  methods: {
    loadChartData() {
      if (!this.jh) {
        return;
      }
      this.loading = true;
      // 获取录井曲线数据和录井整米数据
      Promise.all([getljqxData({ jh: this.jh }), listLjSssjSd({ jh: this.jh })])
        .then(([ljqxRes, ljSssjRes]) => {
          this.chartData = this.processData(ljqxRes, ljSssjRes);
          this.initChart();
          this.loading = false;
        })
        .catch((error) => {
          console.error("获取数据失败:", error);
          this.$message.error("获取数据失败，请重试");
          // 如果API失败，使用模拟数据
          this.chartData = this.generateMockData();
          this.initChart();
          this.loading = false;
        });
    },

    processData(ljqxRes, ljSssjRes) {
      // 处理录井曲线数据
      const processArrayData = (dataList, fieldName) => {
        if (!dataList || !Array.isArray(dataList) || dataList.length === 0) {
          return [];
        }
        // 如果数据是对象数组格式 [{dept: xxx, value: xxx}, ...]
        if (
          typeof dataList[0] === "object" &&
          dataList[0].hasOwnProperty("dept")
        ) {
          return dataList.map((item) => ({
            depth: item.dept || item.depth,
            value: item[fieldName] || item.value || item,
          }));
        }
        // 如果是普通数组，需要从录井整米数据中获取深度
        return dataList
          .map((value, index) => {
            const depth =
              ljSssjRes && ljSssjRes.rows && ljSssjRes.rows[index]
                ? ljSssjRes.rows[index].js
                : null;
            return { depth, value };
          })
          .filter(
            (item) =>
              item.depth !== null &&
              item.value !== null &&
              item.value !== undefined
          );
      };

      // 处理钻时数据（从录井整米数据中获取）
      let drillingTimeData = [];
      if (ljSssjRes && ljSssjRes.rows && Array.isArray(ljSssjRes.rows)) {
        drillingTimeData = ljSssjRes.rows
          .filter(
            (item) =>
              item.js !== null &&
              item.js !== undefined &&
              item.zs !== null &&
              item.zs !== undefined
          )
          .map((item) => ({
            depth: item.js,
            value: item.zs,
          }));
      }

      // 处理其他数据
      const torqueData = processArrayData(ljqxRes.njList, "nj");
      const standpipePressureData = processArrayData(ljqxRes.lyList, "ly");
      const drillingPressureData = processArrayData(ljqxRes.zyList, "zy");
      const rpmData = processArrayData(ljqxRes.zs1List, "zs1");

      // 处理泵冲数据（总泵冲）
      let pumpStrokeData = [];
      if (ljSssjRes && ljSssjRes.rows && Array.isArray(ljSssjRes.rows)) {
        pumpStrokeData = ljSssjRes.rows
          .filter(
            (item) =>
              item.js !== null &&
              item.js !== undefined &&
              item.zbc !== null &&
              item.zbc !== undefined
          )
          .map((item) => ({
            depth: item.js,
            value: item.zbc,
          }));
      }

      return {
        drillingTime: drillingTimeData,
        torque: torqueData,
        standpipePressure: standpipePressureData,
        drillingPressure: drillingPressureData,
        rpm: rpmData,
        pumpStroke: pumpStrokeData,
      };
    },

    generateMockData() {
      // 生成模拟数据，作为备用
      const depthData = [];
      const drillingTimeData = [];
      const torqueData = [];
      const standpipePressureData = [];
      const drillingPressureData = [];
      const rpmData = [];
      const pumpStrokeData = [];

      const startDepth = 1695;
      const endDepth = 2095;
      const step = 1;

      for (let depth = startDepth; depth <= endDepth; depth += step) {
        depthData.push(depth);
        drillingTimeData.push({ depth, value: Math.random() * 15 + 5 });
        torqueData.push({ depth, value: Math.random() * 5 + 5 });
        standpipePressureData.push({ depth, value: Math.random() * 5 + 10 });
        drillingPressureData.push({ depth, value: Math.random() * 50 + 50 });
        rpmData.push({ depth, value: Math.random() * 10 + 5 });
        pumpStrokeData.push({ depth, value: Math.random() * 20 + 120 });
      }

      return {
        drillingTime: drillingTimeData,
        torque: torqueData,
        standpipePressure: standpipePressureData,
        drillingPressure: drillingPressureData,
        rpm: rpmData,
        pumpStroke: pumpStrokeData,
      };
    },

    initChart() {
      if (!this.chartData) {
        const chartDom = document.getElementById("drillingTimeChart");
        if (chartDom && this.myChart) {
          this.myChart.clear();
        }
        return;
      }

      const chartDom = document.getElementById("drillingTimeChart");
      if (!chartDom) {
        console.error("未找到图表容器");
        return;
      }

      if (chartDom.offsetWidth === 0 || chartDom.offsetHeight === 0) {
        console.log("容器尺寸为0，200ms后重试");
        setTimeout(() => this.initChart(), 200);
        return;
      }

      if (this.myChart) {
        this.myChart.dispose();
      }

      this.myChart = echarts.init(chartDom);

      const {
        drillingTime,
        torque,
        standpipePressure,
        drillingPressure,
        rpm,
        pumpStroke,
      } = this.chartData;

      // 转换数据格式为 [depth, value] 格式
      const convertToChartData = (dataArray) => {
        if (!dataArray || !Array.isArray(dataArray)) {
          return [];
        }
        return dataArray
          .filter(
            (item) =>
              item &&
              item.depth !== null &&
              item.depth !== undefined &&
              item.value !== null &&
              item.value !== undefined
          )
          .map((item) => [item.depth, item.value])
          .sort((a, b) => a[0] - b[0]); // 按深度排序
      };

      const drillingTimeChartData = convertToChartData(drillingTime);
      console.log(drillingTimeChartData, "drillingTimeChartData");
      const torqueChartData = convertToChartData(torque);
      const standpipePressureChartData = convertToChartData(standpipePressure);
      const drillingPressureChartData = convertToChartData(drillingPressure);
      const rpmChartData = convertToChartData(rpm);
      const pumpStrokeChartData = convertToChartData(pumpStroke);

      // 计算深度范围
      const allDepths = [
        ...drillingTimeChartData.map((d) => d[0]),
        ...torqueChartData.map((d) => d[0]),
        ...standpipePressureChartData.map((d) => d[0]),
        ...drillingPressureChartData.map((d) => d[0]),
        ...rpmChartData.map((d) => d[0]),
        ...pumpStrokeChartData.map((d) => d[0]),
      ].filter((d) => d !== null && d !== undefined);

      const minDepth =
        allDepths.length > 0 ? Math.floor(Math.min(...allDepths) / 10) * 10 : 0;
      const maxDepth =
        allDepths.length > 0
          ? Math.ceil(Math.max(...allDepths) / 10) * 10
          : 1000;

      const option = {
        title: {
          text: "录井钻时图",
          left: "center",
          top: 10,
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "cross",
          },
          formatter: (params) => {
            if (!params || params.length === 0) {
              return "";
            }
            // 获取深度值（x轴的值）
            const depth =
              params[0].axisValue ||
              (params[0].data && params[0].data[0]) ||
              "";
            let result = `井深: ${depth} m<br/>`;
            params.forEach((param) => {
              if (param.value !== null && param.value !== undefined) {
                const unit = param.seriesName.includes("钻时")
                  ? "min/m"
                  : param.seriesName.includes("扭矩")
                  ? "kN•m"
                  : param.seriesName.includes("立压")
                  ? "MPa"
                  : param.seriesName.includes("钻压")
                  ? "kN"
                  : param.seriesName.includes("转速")
                  ? "rpm"
                  : "";
                result += `${param.seriesName}: ${param.value}${
                  unit ? " " + unit : ""
                }<br/>`;
              }
            });
            return result;
          },
        },
        legend: {
          data: [
            "钻时 (min/m)",
            "扭矩 (kN•m)",
            "立压 (MPa)",
            "钻压 (kN)",
            "转速 (rpm)",
            "泵冲",
          ],
          top: 40,
          right: 50,
          icon: "rect",
          itemWidth: 20,
          itemHeight: 2,
          itemGap: 10,
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          top: "15%",
          containLabel: true,
        },
        xAxis: {
          type: "value",
          name: "井深 (m)",
          nameLocation: "center",
          nameGap: 30,
          axisLabel: {
            formatter: "{value}",
          },
          min: minDepth,
          max: maxDepth,
        },
        yAxis: [
          {
            type: "value",
            name: "钻时 / 扭矩 / 立压",
            position: "left",
            nameLocation: "center",
            nameGap: 50,
            axisLabel: {
              formatter: "{value}",
            },
            splitLine: {
              show: true,
              lineStyle: {
                type: "dashed",
              },
            },
          },
          {
            type: "value",
            name: "钻压 / 转速 / 泵冲",
            position: "right",
            nameLocation: "center",
            nameGap: 50,
            axisLabel: {
              formatter: "{value}",
            },
            splitLine: {
              show: false,
            },
          },
        ],
        series: [
          {
            name: "钻时 (min/m)",
            type: "line",
            yAxisIndex: 0,
            data: drillingTimeChartData,
            smooth: true,
            symbol: "none",
          },
          {
            name: "扭矩 (kN•m)",
            type: "line",
            yAxisIndex: 0,
            data: torqueChartData,
            smooth: true,

            symbol: "none",
          },
          {
            name: "立压 (MPa)",
            type: "line",
            yAxisIndex: 0,
            data: standpipePressureChartData,
            smooth: true,

            symbol: "none",
          },
          {
            name: "钻压 (kN)",
            type: "line",
            yAxisIndex: 1,
            data: drillingPressureChartData,
            smooth: true,

            symbol: "none",
          },
          {
            name: "转速 (rpm)",
            type: "line",
            yAxisIndex: 1,
            data: rpmChartData,
            smooth: true,

            symbol: "none",
          },
          {
            name: "泵冲",
            type: "line",
            yAxisIndex: 1,
            data: pumpStrokeChartData,
            smooth: true,

            symbol: "none",
          },
        ],
      };

      this.myChart.setOption(option);
      this.resizeHandler = () => this.myChart.resize();
      window.addEventListener("resize", this.resizeHandler);
    },

    exportChart() {
      if (!this.myChart) {
        this.$message.warning("图表未初始化，无法导出");
        return;
      }
      try {
        const url = this.myChart.getDataURL({
          type: "png",
          pixelRatio: 2,
          backgroundColor: "#fff",
        });

        const link = document.createElement("a");
        link.href = url;
        link.download = `录井钻时图_${this.jh}_${new Date().getTime()}.png`;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);

        this.$message.success("图片导出成功");
      } catch (error) {
        console.error("导出图片失败:", error);
        this.$message.error("导出图片失败，请重试");
      }
    },

    cleanup() {
      if (this.myChart) {
        this.myChart.dispose();
        this.myChart = null;
      }
      if (this.resizeHandler) {
        window.removeEventListener("resize", this.resizeHandler);
        this.resizeHandler = null;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.drilling-time-chart-container {
  width: 100%;
  height: 100%;
  position: relative;
  box-sizing: border-box;
}

.well-number-display {
  position: absolute;
  top: 16px;
  left: 16px;
  z-index: 5;
  background: transparent;
  padding: 8px 12px;
  display: flex;
  align-items: center;
  gap: 6px;
  font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
  transition: all 0.3s ease;
  opacity: 0.9;
}

.well-number-display:hover {
  opacity: 1;
}

.well-label {
  color: #6b7280;
  font-size: 13px;
  font-weight: 500;
  white-space: nowrap;
}

.well-number {
  color: #3b82f6;
  font-size: 14px;
  font-weight: 600;
}

.chart-wrapper {
  position: relative;
  width: 100%;
  height: calc(100vh - 230px);
  min-height: 600px;
}

.chart {
  width: 100%;
  height: 100%;
}

.export-btn {
  position: absolute;
  top: 10px;
  right: 10px;
  z-index: 100;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}
</style>
