<template>
	<div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="98px">
      <el-form-item label="生产时间">
        <el-date-picker
          v-model="queryParams.monthValue"
          type="month"
          value-format="yyyy-MM"
          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-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="['mes:prepare:export']"-->
<!--        >导出</el-button>-->
<!--      </el-col>-->
<!--      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>-->
<!--    </el-row>-->


    <el-table :data="tableData" border style="width: 100%">
      <el-table-column
        prop="equipment_name"
        label="产线"
        fixed="left"
        width="150">
      </el-table-column>
      <el-table-column
        prop="category"
        label="类别"
        fixed="left"
        width="150">
      </el-table-column>
      <el-table-column
        prop="total_monthly_summary"
        label="当月汇总"
        fixed="left"
        width="150">
      </el-table-column>
      <el-table-column
        v-for="day in days"
        :key="day"
        :prop="day"
        :label="`${day.replace('day', '')}`"
        :width="150"
        align="center"
        :formatter="formatNullToZero">
      </el-table-column>
    </el-table>

    <div id="main" style="width: 100%; height: 820px; background: #fff"></div>

	</div>
</template>

<script>
import { getmonthProductionSut} from "@/api/mes/reportWork";
import * as echarts from 'echarts'

export default {
  name: "Index",

  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 日期范围

      // 备料单表格数据
      tableData: [],
      days: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        monthValue:''
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        monthValue: [
          { required: true, message: '生产时间不能为空', trigger: 'change' }
        ]
      },
      charts: "",
      legendData:[],
      seriesData:[]
    };
  },

  created() {

    const currentMonth = new Date().toISOString().substr(0, 7);
    this.queryParams.monthValue = currentMonth;
    this.getList();
  },
  methods: {
    indexMethod(index) {
      return index + 1;
    },
    /** 查询备料单列表 */
    getList() {
      this.seriesData=[];
      this.legendData=[];
      this.loading = true;
      getmonthProductionSut(this.queryParams).then(response => {
        // this.prepareList = response.rows;
        const data = response.data;
        // this.total = response.total;
        this.loading = false;
        if (data.length > 0) {
          // 获取所有键
          const allKeys = Object.keys(data[0]);
          // 使用正则表达式过滤出符合日期格式的键
          this.days = allKeys.filter(key => /^\d{4}-\d{2}-\d{2}$/.test(key)).sort();
          // 计算每行的日期列数据总和，并设置到 'total_monthly_summary' 字段
          data.forEach(row => {
            let totalSummary = 0;
           const dailyValues = []; // 用于存放每天的值
            this.days.forEach(day => {
              const value = row[day] || 0;
              totalSummary += value;
             dailyValues.push(value); // 将每天的值按顺序存入 dailyValues 数组中
              totalSummary += (row[day] || 0);
            });
            row.total_monthly_summary = totalSummary;
            this.legendData.push(row.equipment_name);
            this.seriesData.push({
              name: row.equipment_name, // 使用机器名或其他标识作为系列名称
              type: 'line',
              stack: 'Total',
              data: dailyValues,
              itemStyle: {
                color: this.getRandomColor(), // 随机颜色
                lineStyle: {
                  color: this.getRandomColor(),
                },
              },
            });
          });
        }
        this.tableData = data;
        // 更新折线图数据
        this.drawLine("main");

      }).catch(() => {
        this.loading = false;
      });
    },
    formatNullToZero(row, column, cellValue) {
      return cellValue === null || cellValue === undefined ? 0 : cellValue;
    },
    getRandomColor() {
      const letters = '0123456789ABCDEF';
      let color = '#';
      for (let i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * 16)];
      }
      return color;
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {};
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('mes/reportWork/getDailyReportExport', {
        ...this.queryParams
      }, `dailyReport${new Date().getTime()}.xlsx`)
    },


    drawLine(id) {
      // 初始化折线图
      this.charts = echarts.init(document.getElementById(id));


      // 设置折线图数据和样式
      this.charts.setOption({
        title: {
          text: '产量趋势'
        },
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: this.legendData
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        toolbox: {
          feature: {
            saveAsImage: {}
          }
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: this.days
        },
        yAxis: {
          type: 'value',
        },
        series: this.seriesData
      });
    },
  }
};
</script>
