<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"
          placeholder
          class="searchInput MaxWidth"
          @on-change="selectdate"
        ></DatePicker>
      </div>
      <div class="filter">
        <label>{{ $t("1129") }}：</label>
        <Select v-model="type2" class="searchSelect" @on-change="xTypechange">
          <Option :value="2">{{ $t("100088") }}</Option>
          <Option :value="1">{{ $t("1132") }}</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("900910") }}</label>
        <Select
          v-model="date1"
          label-in-value
          clearable
          @on-change="timechange"
          class="searchSelect"
        >
          <Option :value="1" id="今天">{{ $t("900911") }}</Option>
          <Option :value="2" id="昨天">{{ $t("900390") }}</Option>
          <Option :value="3" id="本周">{{ $t("900912") }}</Option>
          <Option :value="4" id="上周">{{ $t("900913") }}</Option>
          <Option :value="5" id="本月">{{ $t("900914") }}</Option>
          <Option :value="6" id="上月">{{ $t("900915") }}</Option>
          <Option :value="7" id="本年">{{ $t("900916") }}</Option>
          <Option :value="8" id="上年">{{ $t("900917") }}</Option>
        </Select>
      </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>
    </div>

    <div class="divborder newEchartStyle demo-spin-col">
      <Spin fix v-show="showSpin">
        <Icon type="ios-loading" :size="25" class="demo-spin-icon-load"></Icon>
        <div>Loading</div>
      </Spin>
      <div id="chart-div" class="echartsId"></div>
      <Table
        v-if="showTable"
        class="echartsTable"
        :data="tableData1"
        :columns="tableColumns1"
        :max-height="500"
      ></Table>
    </div>
  </div>
</template>

<script>
import moment from "moment";
import echarts from "echarts";
import axios from "@/libs/api.request";
export default {
  components: {},
  data() {
    return {
      leveldata: [], // 产线层级集合
      levelid: 0, // 产线层级id
      tableData1: [], // 列表数据
      dateTime: "", // 时间范围
      starttime: "", // 开始时间
      endtime: "", // 结束时间
      type2: 2, // 横坐标select
      type3: 0, // 横坐标子select
      xTypeList: [], // select 集合
      showStr: false, // 下拉框显示或隐藏
      page: 1,
      pagesize: 10,
      total: 0,
      obj: {},
      treedata1: [],
      datalevel: [],
      date1: "",
      myChart: "",
      tableColumns1: [
        {
          type: "index2",
          title: this.$t("1008"),
          key: "xuhao",
          render: (h, params) => {
            return h("span", params.index + 1);
          },
          width: 60,
        },
        {
          title: this.$t("200003"),
          key: "title",
        },
        {
          title: this.$t("600009"),
          key: "program_code",
        },
        {
          title: this.$t("100088"),
          key: "product_name",
        },
        {
          title: this.$t("900967"),
          key: "route_name",
        },
        {
          title: this.$t("600647"),
          key: "yield",
        },
        // {
        //   title: this.$t("600664"),
        //   key: "averagetime",
        // },
        // {
        //   title: this.$t("600665"),
        //   key: "totaltime",
        // },
        // {
        //   title: this.$t('901089'),
        //   key: 'efficiency'
        // },
        // {
        //   title: this.$t('900999'),
        //   key: 'oee'
        // }
      ],
      queryInfo: "", //跳转页面参数
      showTable: false,
      showSpin: false,
    };
  },
  created() {
    //获取跳转传过来的值
    let queryInfo = JSON.parse(localStorage.getItem("queryInfo"));
    localStorage.removeItem("queryInfo"); //清除缓存数据
    if (queryInfo && queryInfo != undefined) {
      this.queryInfo = queryInfo;
      this.levelid = queryInfo.sectionid;
    }
  },
  mounted() {
    this.inittime(); // 初始化
    this.initlevel();
    this.tableColumns1 = this.$time.initTableTitle(this.tableColumns1);
  },
  methods: {
    timechange() {
      var time = this.$time.changetime(this.date1).split(" - ");
      this.dateTime = [time[0], time[1]];
    },
    inittime() {
      // 时间赋值
      var date = new Date();
      this.dateTime = [
        moment(date.getTime() - 3600 * 1000 * 24 * 4).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];
      }
    },
    // 产线层级
    initlevel() {
      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;
          this.search(0);
        });
    },
    // 横坐标选择
    xTypechange() {
      this.showStr = true;
      if (this.type2 === 1) {
        this.getLevels();
      } else {
        this.showStr = false;
      }
    },
    // 产线层级选择
    getlevel: function (data) {
      this.levelid = data[data.length - 1];
      this.getLevels();
    },
    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) {
              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;
      }
      var data = {
        startTime:
          this.dateTime && this.dateTime[0]
            ? moment(this.dateTime[0]).format("YYYY-MM-DD HH:mm:ss")
            : "",
        endTime:
          this.dateTime && this.dateTime[1]
            ? moment(this.dateTime[1]).format("YYYY-MM-DD HH:mm:ss")
            : "",
        type: this.type2,
        typeValue: this.type3,
        sectionId: this.levelid,
        toexcel: toexcel,
      };
      this.showTable = false;
      this.showSpin = true;
      axios
        .request({
          url: "/cnc/ProductSum/ListMachineYieldBySignDetail",
          data,
          method: "post",
        })
        .then((res) => {
          this.showTable = true;
          this.showSpin = false;
          if (toexcel === 0) {
            this.getALLData(res.data);
          } else {
            if (res.data.data.length > 0) {
              document.location.href = axios.publicPath + "" + res.data.data;
            } else {
              this.$Message.error(this.$t("1053"));
              return false;
            }
          }
        })
        .catch(() => {
          this.showTable = true;
          this.showSpin = false;
        });
    },
    getALLData(allData) {
      let xName = allData.xdata;
      let sData = allData.ydata;
      if (xName != undefined && sData != undefined) {
        this.echartSet("chart-div", xName, sData);
      } else {
        this.echartSet("chart-div", [], []);
      }

      // 处理表格数据
      this.tableData1 = [];
      if (allData.ret === 1 && allData.data !== 1) {
        this.mockTableData1(allData.data);
      }
    },
    echartSet(ele, xName, sData) {
      this.myChart = echarts.init(document.getElementById(ele));
      var option = {
        title: {
          textStyle: {
            fontSize: 18,
          },
          subtextStyle: {
            fontSize: 14,
          },
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            // 坐标轴指示器，坐标轴触发有效
            type: "shadow", // 默认为直线，可选为：'line' | 'shadow'
          },
        },
        toolbox: {
          feature: {
            dataView: { show: true, readOnly: false },
            magicType: { show: true, type: ["line", "bar"] },
            restore: { show: true },
            saveAsImage: { show: true },
          },
        },
        xAxis: [
          {
            name: this.type2 === 2 ? this.$t("100088") : this.$t("1132"),
            type: "category",
            data: xName,
            axisLabel: {
              // interval: 0,
              rotate: 35,
            },
            axisTick: {
              alignWithLabel: true,
            },
            nameLocation: "end",
          },
        ],
        yAxis: [
          {
            type: "value",
            name: this.$t("500108"),
          },
        ],
        series: [
          {
            name: "",
            type: "bar",
            barMaxWidth: 70,
            data: sData,
            itemStyle: {
              normal: {
                label: {
                  show: sData.length > 35 ? false : true, // 开启显示
                  position: "top", // 在上方显示
                  textStyle: {
                    // 数值样式
                    color: "black",
                    fontSize: 12,
                  },
                },
              },
            },
          },
        ],
      };
      this.myChart.setOption(option);
    },
    mockTableData1(tablelist) {
      let data = [];
      tablelist.forEach((item) => {
        if (item) {
          data.push({
            title: item.title,
            program_code: item.program_code,
            product_name: item.product_name,
            route_name: item.route_name,
            yield: item.yield,
            efficiency: item.efficiency,
            oee: item.oee,
            averagetime: `${(item.averagetime / 60).toFixed(2)}分钟`,
            totaltime: `${(item.totaltime / 60).toFixed(2)}分钟`,
          });
        }
      });
      this.tableData1 = data;
    },
    clear() {
      this.date1 = 0;
      this.inittime();
      this.initlevel();
      this.type2 = 2;
      this.xTypechange();
      this.search(0);
    },
  },
};
</script>
<style lang="less" scoped>
.echart-div-list {
  margin-top: 15px;
  border: 0px solid #ddd;
  padding: 15px;
}
.demo-spin-icon-load {
  animation: ani-demo-spin 1s linear infinite;
}
@keyframes ani-demo-spin {
  from {
    transform: rotate(0deg);
  }
  50% {
    transform: rotate(180deg);
  }
  to {
    transform: rotate(360deg);
  }
}
.demo-spin-col {
  position: relative;
}
</style>
