<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
          :clearable="false"
          class="searchSelect"
          @on-change="getlevel"
        ></Cascader>
      </div>
      <div class="filter">
        <label>{{ $t("900908") }}：</label>
        <DatePicker
          type="datetimerange"
          :value="dateTime"
          confirm
          placeholder="请选择"
          format="yyyy-MM-dd HH:mm:ss"
          class="searchInput MaxWidth"
          @on-change="selectdate"
        ></DatePicker>
      </div>
      <!-- 班次 -->
      <div class="filter">
        <label>{{ $t("100045") }}：</label>
        <Select
          clearable
          filterable
          label-in-value
          class="searchSelect"
          v-model="classshift"
        >
          <Option
            v-for="item in classtimeList"
            :value="item.id"
            :key="item.id"
            >{{ item.title }}</Option
          >
        </Select>
      </div>
      <!-- 次级搜索条件--隐藏 -->
      <div v-show="!morecondition">
        <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="1" v-text="$t('1132')">产线层级</Option>
            <Option :value="2" v-text="$t('100045')">班次</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="filter">
          <label>{{ $t("950047") }}：</label>
          <Select
            v-model="sectionIdStr"
            clearable
            multiple
            class="searchSelect nowropStyle"
          >
            <Option
              v-for="(item, key) in allsections"
              :value="item.id"
              :key="key"
              >{{ item.name }}</Option
            >
          </Select>
        </div>
      </div>
      <!-- 横坐标 -->
      
      <!-- 快捷工位查询 -->
      
      <div class="searchBtn">
        <Button
          type="primary"
          class="twoWord intervalRight"
          icon="ios-search"
          @click="search(0)"
          >{{ $t("1001") }}</Button
        >
        <Button
          type="primary"
          class="fourWord"
          icon="md-close-circle"
          @click="clear()"
          >{{ $t("1039") }}</Button
        >
        <Button
          type="primary"
          class="fourWord"
          icon="ios-cloud-download"
          @click="search(1)"
          >{{ $t("1007") }}</Button
        >
      </div>
      <!-- 更多条件 按钮 -->
      <MoreConbtn @getCon="morecondition = !morecondition" :morecondition="morecondition"></MoreConbtn>
    </div>
    <div class="echart-div-list">
      <div class="loading-div">
        <div class="loading">
          <span></span>
          <span></span>
          <span></span>
          <span></span>
          <span></span>
        </div>
      </div>
    </div>
    <div class="divborder newEchartStyle">
      <div class="echartsId" id="canvasphoto"></div>
      <Table
        class="echartsTable"
        highlight-row
        :data="tableData1"
        :columns="tableColumns1"
      ></Table>
    </div>
  </div>
</template>

<script>
import moment from "moment";
import echarts from "echarts";
import axios from "@/libs/api.request";
export default {
  components: {},
  data() {
    return {
      morecondition:false,
      leveldata: [], // 产线层级集合
      levelid: 0, // 产线层级id
      tableData1: [], // 列表数据
      dateTime: "", // 时间范围
      starttime: "", // 开始时间
      endtime: "", // 结束时间
      type1: "", // 统计指标select
      type2: 0, // 横坐标select
      type3: 0, // 横坐标子select
      xTypeList: [], // select 集合
      showStr: true, // 下拉框显示或隐藏
      page: 1,
      pagesize: 10,
      total: 0,
      obj: {},
      treedata1: [],
      datalevel: [],
      classtimeList: [],
      sectionIdStr: "",
      classshift: 0, //  班次
      allsections: [],
      myChart: "",
      dtStart: "",
      dtEnd: "",
      tableColumns1: [
        {
          type: "index2",
          title: this.$t("1008"),
          key: "xuhao",
          render: (h, params) => {
            return h("span", params.index + 1);
          },
          width: 60
        },
        {
          title: this.$t("500066"),
          key: "datetime"
        },
        {
          title: this.$t("500041"),
          key: "hour2"
        },
        {
          title: this.$t("500043"),
          key: "hour4"
        },
        {
          title: this.$t("500042"),
          key: "hour3"
        },
        {
          title: this.$t("500044"),
          key: "hour5"
        },
        {
          title: this.$t("500040"),
          key: "hour1"
        }
      ],
      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();
    this.inidatetype();
    this.inisectionIds();
    this.GetClass();
    this.search(0);
  },
  methods: {
    inidatetype() {
      this.xTypeList = [
        { value: 0, label: "日" },
        { value: 1, label: "周" },
        { value: 2, label: "月" }
      ];
    },
    inittime() {
      // 时间赋值
      var date = new Date();
      this.dateTime = [
        moment(date.getTime()).format("YYYY-MM-DD ") + "00:00:00",
        moment(date.getTime()).format("YYYY-MM-DD ") + "23:59:59"
      ];
      if(this.queryInfo){
        this.dateTime = this.queryInfo.datetime;
      }
    },
    selectdate(e) {
      var date = new Date();
      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 = [e[0], dtEnd];
    },
    // 产线层级
    initlevel() {
      axios
        .request({
          url: "config/ProjectLevelSection/GetSectionTree",
          method: "get"
        })
        .then(res => {
          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];
      this.getLevels();
    },
    // 横坐标选择
    xTypechange() {
      this.showStr = true;
      this.type3 = 0;
      if (this.type2 === 0) {
        this.xTypeList = [
          { value: 0, label: "日" },
          { value: 1, label: "周" },
          { value: 2, label: "月" }
        ];
        this.type3 = 0;
      } else if (this.type2 === 1) {
        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 (res.data.ret === 1 && this.type2 === 1) {
            if (res.data.data.length !== 0) {
              this.showStr = true;
              res.data.data.forEach(item => {
                this.xTypeList.push({ value: item.id, label: item.title });
              });
              this.type3 = this.xTypeList[0].value;
            } else {
              this.showStr = false;
            }
          } else {
            if (this.type2 != 1) {
              this.xTypeList = [
                { value: 0, label: "日" },
                { value: 1, label: "周" },
                { value: 2, label: "月" }
              ];
            } else {
              this.xTypeList = [];
            }
          }
        });
    },
    inisectionIds() {
      axios
        .request({
          url: "/config/ProjectLevelSection/GetSectionSelect?reverselevel=1",
          method: "get"
        })
        .then(res => {
          // 产线层级
          if (res.data.ret === 1) {
            if (res.data.data.length !== 0) {
              res.data.data.forEach(item => {
                this.allsections.push({ id: item.id, name: item.name });
              });
            }
          }
        });
    },
    search(toexcel) {
      if (this.dateTime === undefined || this.dateTime === "") {
        this.$Message.error(this.$t("800154"));
        return false;
      }
      if(this.type2===0 || this.type2===1){
        if (this.type3 === undefined || this.type3 === "") {
          this.$Message.error(this.$t("500133"));
          return false;
        }
      }
      
      var sectionIds = [];
      if (this.sectionIdStr.length > 0) {
        this.sectionIdStr.forEach(ele => {
          sectionIds.push(parseInt(ele));
        });
      }
      var data = {
        startTime: moment(this.dateTime[0]).format("YYYY-MM-DD HH:mm:ss"),
        endTime: moment(this.dateTime[1]).format("YYYY-MM-DD HH:mm:ss"),
        xtype: this.type2 === 0 || 1 ? this.type2 : 2,  // 横坐标
        x_id: this.type3, //  相关联数据
        sectionId: this.levelid, // 产线层级
        sectionIdStr: sectionIds.join(","), // 快捷工位
        toexcel: toexcel,
        frequency: this.classshift === "" ? 0 : this.classshift // 班次
      };
      // console.log(data);
      // return false;
      axios
        .request({
          url: "/cnc/ProjectSectionMachine/MachineCanvasDataInfoCL",
          data,
          method: "post"
        })
        .then(res => {
          if (toexcel === 0) {
            this.getALLData(res.data.data);
          } else {
            document.location.href = axios.publicPath + "" + res.data.data;
          }
        });
    },
    // 班次接口
    GetClass() {
      axios
        .request({
          url: "/cnc/ProjectSectionMachine/GetClass",
          method: "get"
        })
        .then(res => {
          this.classtimeList = [];
          if (res.data.ret === 1) {
            this.classtimeList = res.data.data;
          }
        });
    },
    getALLData(allData) {
      var dataname = [];
      var datanum = [];
      allData.forEach(value => {
        dataname.push(value.datetime);
        datanum.push(value.data);
      });
      var datanumber = [];
      var datanumber1 = [];
      var datanumber2 = [];
      var datanumber3 = [];
      var datanumber4 = [];
      var datanumber5 = [];
      if (datanum) {
        datanum.forEach(v => {
          datanumber1.push(v.num1);
          datanumber2.push(v.num2);
          datanumber3.push(v.num3);
          datanumber4.push(v.num4);
          datanumber5.push(v.num5);
        });
        datanumber.push(datanumber1);
        datanumber.push(datanumber2);
        datanumber.push(datanumber3);
        datanumber.push(datanumber4);
        datanumber.push(datanumber5);
      }
      this.getCanvasDataPhoto(dataname, datanumber);
      // 处理表格数据
      this.mockTableData1(datanum);
    },
    // 画图
    getCanvasDataPhoto(dataname, datanumber) {
      if (
        this.myChart !== null &&
        this.myChart !== "" &&
        this.myChart !== undefined
      ) {
        this.myChart.dispose();
      }
      this.myChart = echarts.init(document.getElementById("canvasphoto"));
      var option = {
        title: {
          textStyle: {
            fontSize: 18
          },
          subtextStyle: {
            fontSize: 14
          }
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            // 坐标轴指示器，坐标轴触发有效
            type: "shadow" // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        legend: {
          data: [
            this.$t("500041"),
            this.$t("500043"),
            this.$t("500042"),
            this.$t("500044"),
            this.$t("500040")
          ] // 关机排在最后
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true
        },
        xAxis: [
          {
            type: "category",
            data: dataname,
            axisLabel: {
              // interval: 0,
              rotate: 35
            },
            axisTick: {
              alignWithLabel: true
            }
          }
        ],
        yAxis: [
          {
            type: "value",
            name: "%",
            max: 100,
            min: 0
          }
        ],
        series: [
          {
            name: this.$t("500041"),
            type: "bar",
            barMaxWidth: 70,
            stack: this.$t("500067"),
            data: datanumber[1],
            itemStyle: {
              normal: {
                color: "#5cb85c"
              }
            }
          },
          {
            name: this.$t("500043"),
            type: "bar",
            barMaxWidth: 70,
            stack: this.$t("500067"),
            data: datanumber[3],
            itemStyle: {
              normal: {
                color: "#f0ad4e"
              }
            }
          },
          {
            name: this.$t("500042"),
            type: "bar",
            barMaxWidth: 70,
            stack: this.$t("500067"),
            data: datanumber[2],
            itemStyle: {
              normal: {
                color: "#337ab7"
              }
            }
          },
          {
            name: this.$t("500044"),
            type: "bar",
            barMaxWidth: 70,
            stack: this.$t("500067"),
            data: datanumber[4],
            itemStyle: {
              normal: {
                color: "#d9534f"
              }
            }
          },
          {
            name: this.$t("500040"),
            type: "bar",
            barMaxWidth: 70,
            stack: this.$t("500067"),
            data: datanumber[0],
            itemStyle: {
              normal: {
                color: "#585858"
              }
            }
          }
        ]
      };
      this.myChart.setOption(option);
    },
    mockTableData1(tablelist) {
      let data = [];
      tablelist.forEach(item => {
        if (item) {
          data.push({
            datetime: item.datetime,
            hour1: item.hour1 + this.$t(1102) + " (" + item.num1 + "%)",
            hour2: item.hour2 + this.$t(1102) + " (" + item.num2 + "%)",
            hour3: item.hour3 + this.$t(1102) + " (" + item.num3 + "%)",
            hour4: item.hour4 + this.$t(1102) + " (" + item.num4 + "%)",
            hour5: item.hour5 + this.$t(1102) + " (" + item.num5 + "%)",
            num1: item.num1,
            num2: item.num2,
            num3: item.num3,
            num4: item.num4,
            num5: item.num5
          });
        }
      });
      this.tableData1 = data;
    },
    clear() {
      this.inittime();
      this.initlevel();
      this.type2 = 0;
      this.type3 = 0;
      this.inidatetype();
      this.sectionIdStr = "";
      this.search(0);
    }
  }
};
</script>
<style lang="less" scoped>
.echart-div-list {
  // margin-top: 15px;
  border: 0px solid #ddd;
  // padding: 15px;
}
</style>
