var page_function = {
  components: {},
  data() {
    return {
      VarMenuPage: "trend",
      VarMenu: "area",
      VarPageContainerCss: "height:calc(100vh - 65px);",

      //  查詢條件
      search: {
        start_at: moment().subtract(7, 'days').format("YYYY-MM-DD"),
        end_at: moment().format("YYYY-MM-DD"),
        machine1: null,
        machine2: null,
        machine3: null,
        machine4: null,
        machine5: null,
      },
      //  機台下拉選項
      machineOptions: [],
      machineColor: {
        machine1: '#ed4b41',
        machine2: '#e1a03e',
        machine3: '#0f8e61',
        machine4: '#1e43c6',
        machine5: '#d32bcd',
      },
      //  趨勢圖
      TrendObj: {
        IntervalTime: 60,
        options: {
          calculable: true,
          grid: {
            top: "10%",
            left: "2%",
            right: "2%",
            bottom: "10%",
            containLabel: true
          },
          legend: {
            top: 10,
            data: [],
            textStyle: {
              fontFamily: "Microsoft JhengHei",
              fontWeight: "bolder",
              fontSize: 14,
            },
          },
          dataZoom: [
            {
              show: true,
              realtime: true,
            },
            {
              type: "inside",
              realtime: true,
            },
            {
              show: true,
              yAxisIndex: 0,
              filterMode: "empty",
              width: 30,
              height: "80%",
              showDataShadow: false,
              left: "100%",
            },
          ],
          tooltip: {
            trigger: "axis",
          },
          xAxis: [
            {
              type: "category",
              nameTextStyle: {
                fontFamily: "Microsoft JhengHei",
              },
              axisLabel: {
                fontWeight: "bold",
                fontSize: 16,
              },
              data: [],
              axisTick: {
                alignWithLabel: false
              }
            },
          ],
          yAxis: [
            {
              type: "value",
              name: "稼動率(%)",
              position: "right",
              alignTicks: true,
              // offset: 80,
              axisLine: {
                show: true,
                lineStyle: {
                  color: "#ED4B41",
                },
              },
              axisLabel: {
                formatter: "{value} ",
              },
            },
            {
              type: "value",
              name: "產量",
              position: "left",
              alignTicks: true,
              // offset: 80,
              axisLine: {
                show: true,
                lineStyle: {
                  color: "#ED4B41",
                },
              },
              axisLabel: {
                formatter: "{value} ",
              },
            },
          ],
          series: [
            // {
            //   name: "Electricity",
            //   type: "bar",
            //   smooth: true,
            //   // prettier-ignore
            //   data: [300, 280, 250, 260, 270, 300, 550, 500, 400, 390, 380, 390, 400, 500, 600, 750, 800, 700, 600, 400],
            // },
            // {
            //   name: "Electricity",
            //   type: "line",
            //   yAxisIndex: 1,
            //   smooth: true,
            //   itemStyle: {
            //     normal: {
            //       color: "green",
            //       lineStyle: { color: "green" },
            //       borderColor: "green",
            //     },
            //   },
            //   // prettier-ignore
            //   data: [300, 280, 250, 260, 270, 300, 550, 500, 400, 390, 380, 390, 400, 500, 600, 750, 800, 700, 600, 400],
            // },
            // {
            //   name: "Electricity2",
            //   type: "bar",
            //   smooth: true,
            //   itemStyle: {
            //     normal: {
            //       color: "orange",
            //       // areaStyle: {color : itmColor},
            //       lineStyle: { color: "orange" },
            //       borderColor: "orange",
            //     },
            //   },
            //   // prettier-ignore
            //   data: [30, 28, 25, 26, 20, 30, 55, 500, 400, 390, 380, 390, 400, 500, 600, 750, 800, 700, 600, 400],
            // },
          ],
        },
      },
      dataTable: {
        columns: [],
        data: [],
      },

    };
  },

  computed: {
    machineOptionsNameMap() {
      return _.reduce(this.machineOptions, (obj, val) => {
        obj[val['value']] = val['label'];
        return obj;
      }, {});
    },
  },

  watch: {},

  mounted() {
    this.$set(this.WebSetup, "caption", "趨勢圖");
    this.MenuSetup.opened = false;
    this.VarMenuIsOverlay = true;
    this.loadMachineOptions();
  },

  methods: {
    //  載入各機台下拉選單
    async loadMachineOptions() {
      let that = this;
      that.$q.loading.show();
      var params = {
        Action: "LoadMachineOptions",
        Datas: {},
      }
      await this.FnWebAPIGet(params).then((res) => {
        this.machineOptions = _.map(res.data.data, (item) => {
          return {
            "value": item['machine_id'],
            "label": item['machine_name']
          }
        })
        this.search.machine1 = _.first(this.machineOptions)['value']
        this.searchData();
      }).catch(function (err) {
        that.$q.loading.hide();
        console.log(err);
      });
    },

    //  趨勢圖 
    searchData() {
      let that = this;
      that.$q.loading.show();
      this.TrendObj['options']['xAxis'][0]['data'] = []
      this.TrendObj['options']['series'] = []
      this.dataTable['columns'] = [
        { name: 'work_date', label: '日期', field: 'work_date' }
      ];
      this.dataTable['data'] = [];
      // const machinesArray = Object.values(this.search).slice(2).filter(value => value !== null);
      var macArr = [];
      var macColorMap = {};
      _.each(this.search, (v, k) => {
        if (k.startsWith('machine') && v != null) {
          macArr.push(v);
          macColorMap[v] = this.machineColor[k]; //對應機台顏色
        }
      });
      // 產生xAxis日期
      for (var d = moment(this.search.start_at); d.isSameOrBefore(this.search.end_at); d = d.add(1, 'day')) {
        this.TrendObj['options']['xAxis'][0]['data'].push(d.format('YYYY-MM-DD'));
      }

      var params = {
        Action: "TrendData",
        Datas: {
          start_at: this.search.start_at,
          end_at: this.search.end_at,
          machinesArray: macArr
        },
      }
      this.FnWebAPIGet(params).then((res) => {
        if (_.size(res.data.data) > 0) {
          // 整理匯出欄位
          _.each(_.uniq(_.map(res.data.data, 'machine_name')), (mc) => {
            this.dataTable['columns'].push({ name: mc, label: mc, field: mc });
            this.dataTable['columns'].push({ name: `${mc}稼動率`, label: `${mc}稼動率`, field: `${mc}稼動率` });
          });
          var groupedData = _.groupBy(res.data.data, "work_date")

          _.each(groupedData, (inv, date) => {
            console.log(inv, date)
            var dataObj = { work_date: date }; // data日期
            //  塞入xAxis 日期資料
            // this.TrendObj['options']['xAxis'][0]['data'].push(date);

            _.each(inv, (item) => {
              var itemStyleColor = macColorMap[item['machine_id']];
              var seriesIndex = _.findIndex(this.TrendObj['options']['series'], { name: item['machine_name'] });

              if (seriesIndex === -1) {
                // 如果 series 中還沒有該 machine_name，添加新的 series
                this.TrendObj['options']['series'].push({
                  name: item['machine_name'],
                  type: "bar",
                  smooth: true,
                  yAxisIndex: 1,
                  data: [],
                  itemStyle: {
                    color: itemStyleColor
                  }
                });
                seriesIndex = this.TrendObj['options']['series'].length - 1;
              }

              // 確保 data 陣列的長度與 xAxis 一致
              // for (let i = _.size(this.TrendObj['options']['series'][seriesIndex]['data']); i < _.size(this.TrendObj['options']['xAxis'][0]['data']) - 1; i++) {
              //   this.TrendObj['options']['series'][seriesIndex]['data'].push(null);
              // }

              // 添加當前 machine_output 到相應的 series
              this.TrendObj['options']['series'][seriesIndex]['data'].push([date, item['machine_output']]);

              // 稼動率（與產量做法類似）
              var seriesIndexUte = _.findIndex(this.TrendObj['options']['series'], { name: `${item['machine_name']} 稼動率` });
              if (seriesIndexUte === -1) {
                // 如果 series 中還沒有該 machine_name，添加新的 series
                this.TrendObj['options']['series'].push({
                  name: `${item['machine_name']} 稼動率`,
                  type: "line",
                  smooth: true,
                  yAxisIndex: 0,
                  data: [],
                  itemStyle: {
                    color: itemStyleColor
                  }
                });
                seriesIndexUte = this.TrendObj['options']['series'].length - 1;
              }

              // 確保 data 陣列的長度與 xAxis 一致
              // for (let i = _.size(this.TrendObj['options']['series'][seriesIndexUte]['data']); i < _.size(this.TrendObj['options']['xAxis'][0]['data']) - 1; i++) {
              //   this.TrendObj['options']['series'][seriesIndexUte]['data'].push(null);
              // }

              // 添加當前 ute 到相應的 series
              this.TrendObj['options']['series'][seriesIndexUte]['data'].push([date, this.FnFormatNumber(item['ute'], 1)]);
              dataObj[item['machine_name']] = item['machine_output'];
              dataObj[`${item['machine_name']}稼動率`] = this.FnFormatNumber(item['ute'], 1);
            });
            this.dataTable['data'].push(dataObj);
          });
          // 確保所有 series 的資料長度與 xAxis 一致
          // _.each(this.TrendObj['options']['series'], series => {
          //   while (_.size(series['data']) < _.size(this.TrendObj['options']['xAxis'][0]['data'])) {
          //     series['data'].push(null);
          //   }
          // });
        } else {
          this.FnNotify(res.data.message == 'OK' ? '無資料' : res.data.message, 'warning')
        }
        that.$q.loading.hide();
      }).catch(function (err) {
        console.log(err);
        that.$q.loading.hide();
      });
      this.$refs.trend.refresh();
    },

    refresh() {
      this.search.start_at = new Date(new Date().setDate(new Date().getDate() - 7));
      this.search.end_at = new Date();
      this.search.machine1 = null;
      this.search.machine2 = null;
      this.search.machine3 = null;
      this.search.machine4 = null;
      this.search.machine5 = null;
    },
    exportData() {
      if (this.dataTable.columns.length > 0 && this.dataTable.data.length > 0) {
        this.FnReportDownload('csv', this.dataTable.data, this.dataTable.columns, '趨勢圖下載');
      } else {
        this.FnNotify('無資料', 'warning');
      }

    },
  },
};
