<template>
  <div class="testdiv">
    <div class="divborder newSearchDiv" style="margin: 0px">
      <div class="filter">
        <label>{{ $t("1132") }}：</label>
        <Cascader
          :data="datalevel"
          :value="leveldata"
          trigger="click"
          change-on-select
          class="searchSelect"
          @on-change="getlevel"
        ></Cascader>
      </div>
      <div class="filter">
        <label>{{ $t(900908) }}：</label>
        <DatePicker
          type="datetimerange"
          :value="dateTime"
          class="searchInput MaxWidth"
          @on-change="selectdate"
        ></DatePicker>
      </div>
      <div class="searchBtn">
        <Button
          type="primary"
          class="twoWord intervalRight"
          icon="ios-search-outline"
          @click="search()"
          >{{ $t(1001) }}</Button
        >
        <Button
          type="primary"
          class="fourWord"
          icon="ios-close-circle-outline"
          @click="clear()"
          >{{ $t(1039) }}</Button
        >
      </div>
    </div>
    <div class="divborder newEchartStyle">
      <h3 v-text="this.$t(500127)" style="margin-left: 60px">
        {{ $t(500127) }}
      </h3>
      <div class="echartsId" id="production"></div>
      <!-- <h3 v-text="this.$t(500128)" style="margin-left: 60px">
        {{ $t(500128) }}
      </h3>
      <div class="echartsId" id="course"></div> -->
    </div>
  </div>
</template>
<script>
import moment from "moment";
import echarts from "echarts";
import axios from "@/libs/api.request";

export default {
  components: {},
  data() {
    return {
      // 产线层级集合
      leveldata: [],
      // 产线层级id
      levelid: 0,
      // 时间范围
      dateTime: [],
      // 开始时间
      starttime: "",
      // 结束时间
      endtime: "",
      obj: {},
      treedata1: [],
      datalevel: [],
      myChart1: "",
      myChart2: "",
    };
  },
  created() {
    this.initTime();
    this.initLevel();
  },
  methods: {
    // 初始化搜索时间范围
    initTime() {
      // 时间赋值
      let date = new Date();
      this.dateTime = [
        moment(date.getTime() - 1000 * 3600 * 24 * 7).format("YYYY-MM-DD") +
          " " +
          "00:00:00",
        moment(date.getTime()).format("YYYY-MM-DD HH:mm:ss"),
      ];
    },
    selectdate(v) {
      if (v[1].split(" ")[1] == "00:00:00") {
        v[1] = v[1].split(" ")[0] + " " + "23:59:59";
      }
      this.dateTime = v;
    },
    // 获取产线层级级联数据
    initLevel() {
      this.axios
        .request({
          url: "config/ProjectLevelSection/GetSectionTree",
          method: "get",
        })
        .then((res) => {
          this.levelid = res.data.data[0].value;
          const arr = [];
          this.datalevel = res.data.data;
          arr.push(res.data.data[0].value);
          this.leveldata = arr;
        });
    },
    // 监听产线层级当前选中
    getlevel: function (data) {
      this.levelid = data[data.length - 1];
    },
    search() {
      if (this.dateTime === undefined || this.dateTime === "") {
        this.$Message.error(this.$t(800154));
        return false;
      }
      if (this.levelid == null || this.levelid == undefined) {
        this.$Message.error(this.$t(1037));
        return false;
      }
      var data = {
        startTime: this.dateTime[0]
          ? moment(this.dateTime[0]).format("YYYY-MM-DD HH:mm:ss")
          : "",
        endTime: this.dateTime[1]
          ? moment(this.dateTime[1]).format("YYYY-MM-DD HH:mm:ss")
          : "",
        sectionId: this.levelid,
      };
      axios
        .request({
          url: "/cnc/ProductSum/efficiencyAnalysisInfo",
          data,
          method: "post",
        })
        .then((res) => {
          if (res.data.ret === 1 && res.data.data !== 1) {
            this.getProductivity(res.data.data);
            this.getTackTime(res.data.data);
          } else {
            this.clearEchart();
          }
        });
    },
    getProductivity(allData) {
      var startTime = moment(this.dateTime[0]).format("YYYY-MM-DD HH:mm:ss");
      var select_time =
        Date.parse(new Date()) / 1000 - Date.parse(startTime) / 1000;
      let xName = [];
      let barData = [];
      allData.forEach((ele) => {
        if (ele.machineName === undefined || ele.machineName === null) {
          ele.machineName = "";
        }
        xName.push(ele.title);
        if (select_time <= 0) {
          barData.push(this.$datatype.formatDecimal(0, 1, 2, false));
        } else {
          barData.push(ele.productivity);
        }
      });
      this.scxlyEchart(xName, barData);
    },
    scxlyEchart(xName, barData) {
      var newBarData = [];
      barData.forEach((ele) => {
        var pp = {};
        pp.value = ele;
        pp.itemStyle = {};
        if (ele <= 7) {
          pp.itemStyle.color = "#d9534f";
        } else if (ele > 7 && ele <= 85) {
          pp.itemStyle.color = "#f0ad4e";
        } else {
          pp.itemStyle.color = "#33ccff";
        }
        newBarData.push(pp);
      });

      if (
        this.myChart1 !== null &&
        this.myChart1 !== "" &&
        this.myChart1 !== undefined
      ) {
        this.myChart1.dispose();
      }
      this.myChart1 = echarts.init(document.getElementById("production"));
      var option = {
        title: {
          textStyle: {
            fontSize: 18,
          },
          subtextStyle: {
            fontSize: 14,
          },
        },
        grid: {
          bottom: 160,
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            // 坐标轴指示器，坐标轴触发有效
            type: "shadow", // 默认为直线，可选为：'line' | 'shadow'
          },
        },
        xAxis: [
          {
            type: "category",
            data: xName,
            name: this.$t(1026),
            axisLabel: {
              rotate: 35,
            },
            axisTick: {
              alignWithLabel: true,
            },
          },
        ],
        yAxis: [
          {
            type: "value",
            name: this.$t(500129),
          },
        ],
        series: [
          {
            name: this.$t("500130"),
            type: "bar",
            barMaxWidth: 70,
            data: newBarData,
            itemStyle: {
              normal: {
                label: {
                  show: newBarData.length > 35 ? false : true, // 开启显示
                  position: "top", // 在上方显示
                  textStyle: {
                    // 数值样式
                    color: "black",
                    fontSize: 12,
                  },
                },
              },
            },
          },
        ],
      };
      this.myChart1.setOption(option);
    },
    clearEchart() {
      this.myChart1 = echarts.init(document.getElementById("production"));
      var option = {
        title: {
          textStyle: {
            fontSize: 18,
          },
          subtextStyle: {
            fontSize: 14,
          },
        },
        grid: {
          bottom: 160,
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            // 坐标轴指示器，坐标轴触发有效
            type: "shadow", // 默认为直线，可选为：'line' | 'shadow'
          },
        },
        xAxis: [
          {
            type: "category",
            data: [],
            name: this.$t("1026"),
            axisLabel: {
              // interval: 0,
              rotate: 35,
            },
            axisTick: {
              alignWithLabel: true,
            },
          },
        ],
        yAxis: [
          {
            type: "value",
            name: this.$t("500129"),
          },
        ],
        series: [
          {
            name: this.$t("500130"),
            type: "bar",
            barMaxWidth: 70,
            data: [],
          },
        ],
      };
      this.myChart1.setOption(option);

      // this.myChart2 = echarts.init(document.getElementById("course"));
      // var option2 = {
      //   title: {
      //     textStyle: {
      //       fontSize: 18,
      //     },
      //     subtextStyle: {
      //       fontSize: 14,
      //     },
      //   },
      //   grid: {
      //     bottom: 160,
      //   },
      //   tooltip: {
      //     trigger: "axis",
      //     axisPointer: {
      //       // 坐标轴指示器，坐标轴触发有效
      //       type: "shadow", // 默认为直线，可选为：'line' | 'shadow'
      //     },
      //   },
      //   xAxis: [
      //     {
      //       type: "category",
      //       name: this.$t("1026"),
      //       data: [],
      //       axisLabel: {
      //         // interval: 0,
      //         rotate: 35,
      //       },
      //       axisTick: {
      //         alignWithLabel: true,
      //       },
      //     },
      //   ],
      //   yAxis: [
      //     {
      //       type: "value",
      //       name: "CT（S）",
      //     },
      //   ],
      //   series: [
      //     {
      //       name: "CT",
      //       type: "bar",
      //       barMaxWidth: 70,
      //       data: [],
      //     },
      //   ],
      // };
      // this.myChart2.setOption(option2);
    },
    getTackTime(data) {
      let xName = [];
      let barData = [];
      data.forEach((ele) => {
        if (
          ele.yield === undefined ||
          ele.yield === "NaN" ||
          ele.yield === ""
        ) {
          ele.cycleTime = 0;
        }
        xName.push(ele.title);
        if (ele.productivity === 0 || ele.yield === 0) {
          barData.push(this.$datatype.formatDecimal(0, 1, 2, false));
        } else {
          barData.push(this.$datatype.formatDecimal(ele.yield, 1, 2, false));
        }
      });
      // this.gcjptEchart(xName, barData);
    },
    // 过程节拍图
    gcjptEchart(xName, barData) {
      if (this.myChart2) {
        this.myChart2.dispose();
      }

      this.myChart2 = echarts.init(document.getElementById("course"));
      var option = {
        title: {
          textStyle: {
            fontSize: 18,
          },
          subtextStyle: {
            fontSize: 14,
          },
        },
        grid: {
          bottom: 160,
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            // 坐标轴指示器，坐标轴触发有效
            type: "shadow", // 默认为直线，可选为：'line' | 'shadow'
          },
          formatter: function (params) {
            var result = params[0].name + "</br>";
            params.forEach(function (value, index) {
              result +=
                '<span style="display:inline-block;margin-right:5px;border-radius:10px;width:9px;height:9px;background-color:' +
                params[index].color +
                '"></span>';
              result +=
                params[index].seriesName +
                "：" +
                params[index].data +
                " " +
                "S" +
                "<br/>";
            });
            return result;
          },
        },
        xAxis: [
          {
            type: "category",
            name: this.$t("1026"),
            data: xName,
            axisLabel: {
              // interval: 0,
              rotate: 35,
            },
            axisTick: {
              alignWithLabel: true,
            },
          },
        ],
        yAxis: [
          {
            type: "value",
            name: "CT（S）",
          },
        ],
        series: [
          {
            name: "CT",
            type: "bar",
            barMaxWidth: 70,
            data: barData,
            itemStyle: {
              normal: {
                label: {
                  show: barData.length > 35 ? false : true, // 开启显示
                  position: "top", // 在上方显示
                  textStyle: {
                    // 数值样式
                    color: "black",
                    fontSize: 12,
                  },
                },
              },
            },
          },
        ],
      };
      this.myChart2.setOption(option);
    },
    clear() {
      this.initTime();
      this.initLevel();
      this.search();
    },
  },
};
</script>
