<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="searchInput"
          @on-change="getlevel"
        ></Cascader>
      </div>
      <div class="filter">
        <label>{{ $t("900908") }}：</label>
        <DatePicker
          type="datetimerange"
          :value="dateTime"
          placeholder
          class="searchInput MaxWidth"
          @on-change="selectdate"
        ></DatePicker>
      </div>
      <div class="filter">
        <label>{{ $t("500088") }}：</label>
        <Select v-model="type1" class="searchSelect">
          <Option :value="0" v-text="$t('500072')">报警次数</Option>
          <Option :value="1" v-text="$t('810005')">报警时长</Option>
        </Select>
      </div>
      <div class="filter">
        <label>{{ $t("1129") }}：</label>
        <Select
          v-model="type2"
          class="searchSelect"
          @on-change="xTypechange"
          style="margin-right: 10px"
        >
          <Option :value="0" v-text="$t('500065')">时间单位</Option>
          <Option :value="4" v-text="$t('1132')">产线层级</Option>
          <Option :value="5" v-text="$t('900572')">故障代码</Option>
          <Option :value="6" v-text="$t('950005')">故障类别</Option>
        </Select>
        <Select v-model="type3" clearable class="searchSelect" v-show="showStr">
          <Option
            v-for="(item, key) in xTypeList"
            :value="item.value"
            :key="key"
            >{{ item.label }}</Option
          >
        </Select>
      </div>
      <div class="searchBtn">
        <Button
          type="primary"
          class="twoWord"
          icon="ios-search-outline"
          @click="search(0)"
          >{{ $t("1001") }}</Button
        >
        <Button
          type="primary"
          class="fourWord"
          icon="ios-cloud-download"
          @click="search(1)"
          >{{ $t("1007") }}</Button
        >
      </div>
    </div>
    <div class="divborder newEchartStyle">
      <div id="plant" class="three-level echartsId"></div>
      <div class="echartsTable">
        <Table
          v-if="type1 == 0"
          highlight-row
          :data="tableData1"
          :columns="tableColumns1"
        ></Table>
        <Table
          v-if="type1 == 1"
          highlight-row
          :data="tableData1"
          :columns="tableColumns2"
        ></Table>
      </div>
    </div>
  </div>
</template>

<script>
import moment from "moment";
import axios from "@/libs/api.request";
import echarts from "echarts";

export default {
  data() {
    return {
      leveldata: [], // 产线层级集合
      levelid: 0, // 产线层级id
      tableData1: [], // 列表数据
      dateTime: "", // 时间范围
      starttime: "", // 开始时间
      endtime: "", // 结束时间
      type1: 0, // 统计指标select
      type2: 0, // 横坐标select
      type3: 0, // 横坐标子select
      xTypeList: [
        { value: 0, label: "日" },
        { value: 1, label: "周" },
        { value: 2, label: "月" },
      ], // select 集合
      showStr: true, // 下拉框显示或隐藏
      page: 1,
      pagesize: 10,
      total: 0,
      obj: {},
      treedata1: [],
      datalevel: [],
      title: "",
      ytype: "",
      xname: "",
      acrossdisplay: "",
      abscissa: "",
      tableColumns1: [
        {
          type: "index2",
          title: this.$t("1008"),
          key: "xuhao",
          render: (h, params) => {
            return h(
              "span",
              params.index + (this.page - 1) * this.pagesize + 1
            );
          },
          width: 100,
        },
        {
          title: this.$t("1129"),
          key: "abscissa",
          align: "center",
        },
        {
          title: this.$t("800310"),
          key: "ordinate",
          align: "center",
        },
      ],
      tableColumns2: [
        {
          type: "index2",
          title: this.$t("1008"),
          key: "xuhao",
          render: (h, params) => {
            return h(
              "span",
              params.index + (this.page - 1) * this.pagesize + 1
            );
          },
          width: 100,
        },
        {
          title: this.$t("1129"),
          key: "abscissa",
          align: "center",
        },
        {
          title: this.$t("800309"),
          key: "ordinate",
          align: "center",
        },
      ],
      queryInfo:'',//跳转页面参数
    };
  },
  created(){
    //获取跳转传过来的值
    let queryInfo = JSON.parse(localStorage.getItem('queryInfo'));
    localStorage.removeItem('queryInfo'); //清除缓存数据
    if(queryInfo&&queryInfo!=undefined){
      this.queryInfo = queryInfo;
      this.levelid = queryInfo.sectionid;
    }
    // 初始化时间范围搜索条件
    this.inittime();
    this.initlevel();
  },
  mounted() {
    this.search(0);
  },
  methods: {
    // 初始化时间范围搜索条件
    inittime() {
      // 时间赋值
      var date = new Date();
      this.dateTime = [
        moment(date.getTime() - 3600 * 1000 * 24 * 13).format("YYYY-MM-DD ") +
          "00:00:00",
        moment(date.getTime()).format("YYYY-MM-DD HH:mm:ss"),
      ];

      if(this.queryInfo){
        this.dateTime = this.queryInfo.datetime;
      }
    },
    // 监听时间范围搜索条件变化
    selectdate(e) {
      this.dateTime = [e[0], e[1]];
      let dtStart = e[0];
      let dtEnd = e[1];
      let last_str = dtEnd.split(" ")[1];
      if (last_str == "00:00:00") {
        dtEnd = moment(dtEnd).format("YYYY-MM-DD") + " 23:59:59";
        // this.dateTime = [dtStart, dtEnd];
      }
      this.dateTime = [dtStart, dtEnd];
    },
    // 初始化产线层级搜索条件
    initlevel() {
      axios
        .request({
          url: "config/ProjectLevelSection/GetSectionTree",
          method: "get",
        })
        .then((res) => {
          const arr = [];
          this.datalevel = res.data.data;
          let sdata = res.data.data
          if(sdata!=null&&sdata!=undefined&&sdata&&sdata.length >0){
              this.levelid = res.data.data[0].value;
              arr.push(res.data.data[0].value);
          }
          this.leveldata = arr;
          this.search(0)
        });
    },
    // 监听产线层级搜索条件变化
    getlevel: function (data) {
      this.levelid = data[data.length - 1];
      this.getLevels();
    },
    // 监听横坐标搜索条件变化
    xTypechange() {
      this.showStr = true;
      if (this.type2 == 0) {
        this.xTypeList = [
          { value: 0, label: "日" },
          { value: 1, label: "周" },
          { value: 2, label: "月" },
        ];
        this.type3 = 0;
      } else if (this.type2 == 4) {
        this.getLevels();
      } else {
        this.showStr = false;
        this.xTypeList = [];
      }
    },
    getLevels() {
      this.xTypeList = [];
      axios
        .request({
          url:
            "/config/ProjectLevelSection/GetLevelsBySection?sectionId=" +
            this.levelid,
          method: "get",
        })
        .then((res) => {
          if (this.type2 === 0) {
            this.xTypeList = [
              { value: 0, label: "日" },
              { value: 1, label: "周" },
              { value: 2, label: "月" },
            ];
            this.type3 = 0;
          }
          // 产线层级
          if (res.data.ret === 1 && this.type2 === 4) {
            if (res.data.data.length !== 0) {
              res.data.data.forEach((item) => {
                this.xTypeList.push({ value: item.id, label: item.title });
              });
              this.type3 = this.xTypeList[0].value;
            } else {
              this.showStr = false;
            }
          }
        });
    },
    search(toexcel) {
      if (this.dateTime == undefined || this.dateTime == "") {
        this.$Message.error(this.$t(800154));
        return false;
      }
      if (this.type2 == 4) {
        if (this.type3 == undefined || this.type3 == "") {
          this.$Message.error(this.$t(1037));
          return false;
        }
      }

      let data = {
        xID: this.type2, // 横坐标  (0：时间单位； 4：产线层级；5：故障代码；6 故障类型)
        yID: this.type1, // 统计指标  0报警次数 1报警时长
        sectionID: !this.levelid ? 0 : this.levelid, // 产线层级ID
        patchID: this.type3, // 天 周 月
        startTime: moment(this.dateTime[0]).format("YYYY-MM-DD HH:mm:ss"),
        toexcel: toexcel,
        endTime: moment(this.dateTime[1]).format("YYYY-MM-DD HH:mm:ss"),
      };
      axios
        .request({
          url: "/cnc/MachineAlarm/GetAlarmDataForAnalysis",
          data,
          method: "post",
        })
        .then((res) => {
          if (toexcel === 0) {
            if (this.type2 === 0) {
              this.dateEchart(res.data.data);
            } else {
              this.editEchart(res.data.data);
            }
            this.xname = "";

            if (this.type2 === 0) {
              this.xname = this.$t("600532");
            } else if (this.type2 === 4) {
              this.xname = this.$t("1132");
            } else if (this.type2 === 5) {
              this.xname = this.$t("900572");
            } else if (this.type2 === 6) {
              this.xname = this.$t("200005");
            }

            if (this.type1 === 0) {
              this.tableColumns1 = [
                {
                  type: "index2",
                  title: this.$t("1008"),
                  key: "xuhao",
                  render: (h, params) => {
                    return h(
                      "span",
                      params.index + (this.page - 1) * this.pagesize + 1
                    );
                  },
                  width: 100,
                },
                {
                  title: this.xname,
                  key: "abscissa",
                  align: "center",
                },
                {
                  title: this.$t("800310"),
                  key: "ordinate",
                  align: "center",
                },
              ];
            } else {
              this.tableColumns2 = [
                {
                  type: "index2",
                  title: this.$t("1008"),
                  key: "xuhao",
                  render: (h, params) => {
                    return h(
                      "span",
                      params.index + (this.page - 1) * this.pagesize + 1
                    );
                  },
                  width: 100,
                },
                {
                  title: this.xname,
                  key: "abscissa",
                  align: "center",
                },
                {
                  title: this.$t("800309"),
                  key: "ordinate",
                  align: "center",
                },
              ];
            }

            this.mockTableData1(res.data.data);
          } else {
            document.location.href = axios.publicPath + "" + res.data.data;
          }
        });
    },
    mockTableData1(tablelist) {
      let data = [];
      tablelist.forEach((item) => {
        if (item) {
          data.push({
            abscissa: item.abscissa,
            ordinate:
              this.type1 === 0 ? item.ordinate : this.timechange(item.ordinate),
            rate: item.rate,
          });
        }
      });
      this.tableData1 = data;
    },
    editEchart(data) {
      var xpal = [];
      var barData = [];
      var lineData = [];
      var timeY = [];
      data.forEach((ele) => {
        xpal.push(ele.abscissa);
        timeY.push(ele.ordinate);
        lineData.push(
          this.$datatype.formatDecimal(ele.rate * 100, 1, 2, false)
        );
      });
      if (this.type1 === 0) {
        // 次数
        this.ytype = this.$t("800310");
        this.acrossdisplay = this.$t("200086");
        barData = timeY;
      } else {
        // 时间
        timeY.forEach((ele) => {
          barData.push(
            this.$datatype.formatDecimal(parseFloat(ele) / 60, 1, 2, false)
          );
        });
        this.ytype = this.$t("810007");
        this.acrossdisplay = this.$t("800311");
      }
      this.plant(
        xpal,
        barData,
        lineData,
        this.ytype,
        this.abscissa,
        this.acrossdisplay
      );
    },
    plant(xname, barData, lineData, ytype, abscissa, acrossdisplay) {
      var myChart = echarts.init(document.getElementById("plant"));
      var option = {
        title: {
          textStyle: {
            fontSize: 18,
            align: "center",
          },
          subtextStyle: {
            fontSize: 14,
          },
          // text: this.$t('500075'), /* 故障统计时间Pareto图 */
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            // 坐标轴指示器，坐标轴触发有效
            type: "cross", // 默认为直线，可选为：'line' | 'shadow'
          },
          extraCssText: "width:160px;height:80px;",
        },
        xAxis: [
          {
            type: "category",
            nameGap: 40,
            data: xname,
            axisLabel: {
              // interval: 0,
              rotate: 35,
            },
            name: abscissa,
            axisTick: {
              alignWithLabel: true,
            },
          },
        ],
        yAxis: [
          {
            type: "value",
            name: ytype,
            nameTextStyle: {
              fontSize: 18,
              padding: [0, 0, 0, 80], // 四个数字分别为上右下左与原位置距离
            },
            data: "",
          },
          {
            type: "value",
            axisLabel: {
              formatter: "{value}%",
            },
          },
        ],
        series: [
          {
            itemStyle: {
              normal: {
                label: {
                  show: true,
                },
              },
            },
            // yAxisIndex: 1,
            name: acrossdisplay,
            type: "bar",
            barMaxWidth: 70,
            // data:formatDecimal(parseFloat(barData/60,1,2,false))
            data: barData,
          },
          {
            itemStyle: {
              normal: {
                label: {
                  show: true,
                },
              },
            },
            yAxisIndex: 1,
            name: this.$t("500077"),
            type: "line",
            data: lineData,
          },
        ],
      };
      myChart.setOption(option);
    },
    dateEchart(data) {
      var y_name = this.type1 == 0 ? this.$t("800310") : this.$t("810007");
      var data_name = [];
      var data_value = [];
      if (data.length > 0) {
        data.forEach((ele) => {
          data_name.push(ele.abscissa);
          if (this.type1 === 0) {
            data_value.push(ele.ordinate); // 次数
          } else {
            console.log(ele);
            data_value.push((ele.ordinate / 60).toFixed(2));
          }
        });
      }
      var main_test = echarts.init(document.getElementById("plant"));
      let option_base = {
        title: {
          textStyle: {
            fontSize: 18,
          },
          subtextStyle: {
            fontSize: 14,
          },
        },
        // color: ['#3398DB'],
        tooltip: {
          trigger: "axis",
          axisPointer: {
            // 坐标轴指示器，坐标轴触发有效
            type: "shadow", // 默认为直线，可选为：'line' | 'shadow'
          },
          extraCssText: "width:160px;height:60px;",
        },
        legend: {
          name: "",
          top: "10px",
        },
        grid: {
          left: "5%",
          right: "4%",
          bottom: "8%",
          containLabel: true,
        },
        xAxis: [
          {
            type: "category",
            data: data_name,
            axisLabel: {
              // interval: 0,
              rotate: 35,
            },
            axisTick: {
              alignWithLabel: true,
            },
          },
        ],
        yAxis: [
          {
            name: y_name,
            nameTextStyle: { fontSize: 18, padding: [0, 0, 0, 150] },
            type: "value",
          },
        ],
        series: [
          {
            name: "",
            type: "bar",
            barMaxWidth: 70,
            barWidth: "60%",
            data: data_value,
            itemStyle: {
              normal: {
                label: {
                  show: true, //开启显示
                  position: "top", //在上方显示
                  textStyle: {
                    //数值样式
                    color: "#000",
                    fontSize: 12,
                  },
                  formatter: function (params) {
                    if (params.value > 0) {
                      return params.value;
                    } else {
                      return "";
                    }
                  },
                },
              },
            },
          },
        ],
      };
      main_test.clear();
      main_test.setOption(option_base);
    },
    timechange(num) {
      var str = "";
      if (num > 86400) {
        let d = Math.floor(num / 86400);
        let h = Math.floor((num % 86400) / 3600);
        let m = Math.floor(((num % 86400) % 3600) / 60);
        let s = ((num % 86400) % 3600) % 60;
        str =
          d +
          this.$t("1101") +
          h +
          this.$t("1102") +
          m +
          this.$t("1103") +
          s +
          this.$t("1104");
        return str;
      } else if (num > 3600) {
        let h = Math.floor(num / 3600);
        let m = Math.floor((num % 3600) / 60);
        let s = (num % 24) % 60;
        str = h + this.$t("1102") + m + this.$t("1103") + s + this.$t("1104");
        return str;
      } else if (num > 60) {
        let m = Math.floor(num / 60);
        let s = Math.floor(num % 60);
        str = "" + m + this.$t("1103") + s + this.$t("1104");
        return str;
      } else {
        str = num + this.$t("1104");
        return str;
      }
    },
  },
};
</script>
