<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="订单编号" prop="workorderCode">
        <el-input
          v-model="queryParams.workorderCode"
          placeholder="请输入订单编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产线名称" prop="workorderName">
        <el-select v-model="queryParams.workorderName" placeholder="请选择产线名称"  clearable>
          <el-option
            v-for="item in lineBodys"
            :key="item.lineCode"
            :label="item.lineName"
            :value="item.lineCode"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="订单生产日期"  label-width="100px">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!--    <el-row :gutter="10" class="mb8">-->
    <!--      <el-col :span="1.5">-->
    <!--        <el-button-->
    <!--          type="warning"-->
    <!--          plain-->
    <!--          icon="el-icon-download"-->
    <!--          size="mini"-->
    <!--          @click="handleExport"-->
    <!--          v-hasPermi="['energy:orderenergy:export']"-->
    <!--        >导出</el-button>-->
    <!--      </el-col>-->
    <!--      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>-->
    <!--    </el-row>-->

    <!-- 图表容器 -->
    <div ref="chartContainer" style="width: 100%; height: 400px; margin: 20px 0;"></div>

    <!--    <pagination-->
    <!--      v-show="total>0"-->
    <!--      :total="total"-->
    <!--      :page.sync="queryParams.pageNum"-->
    <!--      :limit.sync="queryParams.pageSize"-->
    <!--      @pagination="getList"-->
    <!--    />-->

  </div>
</template>

<script>
import { getProductConsumptionComparison } from "@/api/energy/record/statistics";
import * as echarts from 'echarts';
import {selectLineBody} from "@/api/mes/mesLine";

export default {
  name: "productConsumptionComparison",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      //表格数据
      OrderEnergyList: [],
      lineBodys: [],
      // 日期范围
      dateRange: [
        this.parseTime(new Date().getTime() - 6 * 24 * 60 * 60 * 1000, '{y}-{m}-{d}'),
        this.parseTime(new Date(), '{y}-{m}-{d}')
      ],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        factoryId: null,
        productCode: null,
        productName: null,
        workorderName: null,
        equipmentName: null,
        electricityNo: null,
        attr1: null,
        attr2: null,
        attr3: null,
        attr4: null,
      },
      chart: null,
    };
  },
  created() {
    selectLineBody(this.queryParams).then((response) => {
      this.lineBodys = response.rows;
    });
    this.getList();
  },
  mounted() {
    this.initChart();
  },
  beforeDestroy() {
    if (this.chart) {
      this.chart.dispose();
    }
  },
  methods: {
    /** 初始化图表 */
    initChart() {
      this.chart = echarts.init(this.$refs.chartContainer);
      this.updateChart();
    },

    /** 更新图表数据 */
    updateChart() {
      if (!this.chart) return;

      const xData = this.OrderEnergyList.map(item => item.workorderName);
      const yData = this.OrderEnergyList.map(item => item.singleKw);

      const option = {
        title: {
          text: '产品单耗对比分析',
          subtext: '单位：KW·h/箱',
          left: 'center',
          top: 10,
          textStyle: {
            fontSize: 18,
            fontWeight: 'bold'
          },
          subtextStyle: {
            fontSize: 12,
            color: '#666'
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          backgroundColor: 'rgba(255, 255, 255, 0.9)',
          borderColor: '#ccc',
          borderWidth: 1,
          textStyle: {
            color: '#333'
          },
          formatter: function(params) {
            const data = params[0];
            return `<div style="padding: 3px;">
              <div style="font-weight: bold; margin-bottom: 5px;">${data.name}</div>
              <div style="display: flex; justify-content: space-between; align-items: center;">
                <span style="display: inline-block; width: 10px; height: 10px; background: #409EFF; margin-right: 5px;"></span>
                <span>单耗：</span>
                <span style="font-weight: bold; margin-left: 5px;">${data.value.toFixed(2)} KW·h/箱</span>
              </div>
            </div>`;
          }
        },
        grid: {
          left: '6%',
          right: '9%',
          bottom: '8%',
          top: '15%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: xData,
          axisLabel: {
            interval: 0,
            rotate: 30,
            fontSize: 12,
            color: '#666'
          },
          axisLine: {
            lineStyle: {
              color: '#ddd'
            }
          },
          axisTick: {
            alignWithLabel: true
          },
          name: '产品名称',
          nameTextStyle: {
            padding: [10, 0, 0, 0],
            color: '#666'
          }
        },
        yAxis: {
          type: 'value',
          name: '单耗（KW·h/箱）',
          nameTextStyle: {
            padding: [0, 0, 10, 0],
            color: '#666'
          },
          axisLabel: {
            formatter: '{value}',
            color: '#666'
          },
          splitLine: {
            lineStyle: {
              type: 'dashed',
              color: '#eee'
            }
          },
          axisLine: {
            show: true,
            lineStyle: {
              color: '#ddd'
            }
          }
        },
        series: [{
          name: '单耗',
          type: 'bar',
          data: yData,
          barWidth: '40%',
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: '#83bff6' },
              { offset: 0.5, color: '#409EFF' },
              { offset: 1, color: '#188df0' }
            ]),
            borderRadius: [4, 4, 0, 0]
          },
          emphasis: {
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#2378f7' },
                { offset: 0.7, color: '#2378f7' },
                { offset: 1, color: '#83bff6' }
              ])
            }
          },
          label: {
            show: true,
            position: 'top',
            distance: 10,
            formatter: '{c} KW·h/箱',
            fontSize: 12,
            color: '#666'
          }
        }]
      };

      this.chart.setOption(option);
    },

    /** 查询列表 */
    getList() {
      this.loading = true;
      getProductConsumptionComparison(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        // 将对象转换为数组格式
        const data = response.data.data;
        this.OrderEnergyList = Object.entries(data).map(([lineName, value]) => ({
          workorderName: lineName,
          singleKw: value
        }));
        this.total = this.OrderEnergyList.length;
        this.loading = false;
        this.updateChart();
      });
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('energy/report/analysis/orderenergy/export', {
        ...this.queryParams
      }, `单耗分析_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style scoped>
.chart-container {
  margin-top: 20px;
}
</style>
