<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="daterange"
          :value="dateTime"
          placeholder
          class="searchInput middleWidth"
          @on-change="selectdate"
        ></DatePicker>
      </div>

      <div class="filter">
        <label>{{$t('5500090')}}：</label>
        <Select
          v-model="parentmode"
          clearable
          multiple
          @on-change="modechange"
          class="searchSelect nowropStyle"
        >
          <Option
            v-for="(item,key) in parentmodes"
            :value="item.id"
            :key="key"
          >{{ item.workingmodename }}</Option>
        </Select>
      </div>
      <div class="filter">
        <label>{{$t('5500091')}}：</label>
        <Select v-model="childmode" clearable multiple class="searchSelect nowropStyle">
          <Option
            v-for="(item,key) in childmodes"
            :value="item.id"
            :key="key"
          >{{ item.workingmodename }}</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="4" v-text="$t('1132')">产线层级</Option>
            <Option :value="5" v-text="$t('800264')">工作模式</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>
      <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="divborder newEchartStyle">
      <!-- 图表 -->
      <div class="echartsId" id="plant"></div>
      <!-- 图表 end-->

      <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: [
        { value: 0, label: "日" },
        { value: 1, label: "周" },
        { value: 2, label: "月" },
      ], // select 集合
      showStr: true, // 下拉框显示或隐藏
      page: 1,
      pagesize: 10,
      total: 0,
      obj: {},
      treedata1: [],
      datalevel: [],
      parentmode: "",
      parentmodes: [],
      childmode: "",
      childmodes: [],
      myChart: "",
      xname: "",
      tableColumns1: [
        {
          type: "index2",
          title: this.$t("1008"),
          key: "xuhao",
          render: (h, params) => {
            return h("span", params.index + 1);
          },
          width: 60,
        },
        {
          title: this.$t("1129"),
          key: "abscissa",
        },
        {
          title: this.$t("500086"),
          key: "ordinate",
        },
      ],
      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.iniworkmode();
  },
  methods: {
    iniworkmode() {
      axios
        .request({
          url: "/cnc/MachineWordingMode/ShowParentWorkModeList",
          method: "get",
        })
        .then((res) => {
          this.parentmodes = res.data.data;
        });
    },
    modechange() {
      var f_array = [];
      if (this.parentmode.length > 0) {
        this.parentmode.forEach((ele) => {
          f_array.push(parseInt(ele));
        });
      }
      var data = {
        parentIds: f_array.join(","),
      };
      axios
        .request({
          url: "/cnc/MachineWordingMode/GetSonModesByParents",
          data,
          method: "post",
        })
        .then((res) => {
          this.childmodes = res.data.data;
        });
    },
    inidatetype() {
      this.xTypeList = [
        { value: 0, label: "日" },
        { value: 1, label: "周" },
        { value: 2, label: "月" },
      ];
    },
    inittime() {
      // 时间赋值
      var date = new Date();
      var start = this.$time.timestampToTime(
        date.getTime() - 3600 * 1000 * 24 * 7
      );
      var end = this.$time.timestampToTime(date.getTime());
      this.dateTime = [start, end];

      if(this.queryInfo){
        this.dateTime = this.queryInfo.datetime;
      }
    },
    selectdate(e) {
      this.dateTime = [e[0], e[1]];
    },
    // 产线层级
    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);
        });
    },
    // 产线层级选择
    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 if (this.type2 === 5) {
        this.xTypeList = [
          { value: 1, label: "父级工作模式" },
          { value: 2, label: "子级工作模式" },
        ];
        this.type3 = 0;
      }
    },
    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.type3 === undefined || this.type3 === "") {
        this.$Message.error(this.$t("5500238"));
        return false;
      }
      var f_array = [];
      var s_array = [];
      if (this.parentmode.length > 0) {
        this.parentmode.forEach((ele) => {
          f_array.push(parseInt(ele));
        });
      }
      if (this.childmode.length > 0) {
        this.childmode.forEach((ele) => {
          s_array.push(parseInt(ele));
        });
      }
      var data = {
        startTime: moment(this.dateTime[0]).format("YYYY-MM-DD"),
        endTime: moment(this.dateTime[1]).format("YYYY-MM-DD"),
        patchID: this.type3,
        xID: this.type2,
        sectionId: !this.levelid ? 0 : this.levelid,
        parent_mode: f_array.join(","),
        working_mode: s_array.join(","),
        toexcel: toexcel,
      };
      axios
        .request({
          url: "/cnc/MachineWordingMode/WorkingModeAnalysis",
          data,
          method: "post",
        })
        .then((res) => {
          if (toexcel === 0) {
            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("800264");
            }

            this.tableColumns1.forEach((item, index) => {
              if (item.key === "abscissa") {
                item.title = this.xname;
              }
            });

            // 时间单位
            if (this.type2 === 0) {
              this.dateEchart(res.data.data, this.$t("900865"));
              this.mockTableData1(res.data.data);
            } else if (this.type2 === 4) {
              this.sectionEchart(res.data.data);
              this.mockTableData1(res.data.data, this.$t("1132"));
            } else if (this.type2 === 5) {
              var th_name =
                this.type1 === 1 ? this.$t("950085") : this.$t("950049");
              this.sectionEchart(res.data.data);
              this.mockTableData1(res.data.data, th_name);
            }
          } else {
            document.location.href = axios.publicPath + "" + res.data.data;
          }
        });
    },
    dateEchart(data, yname) {
      var x_array = [];
      var y_array = [];
      data.forEach((ele) => {
        x_array.push(ele.abscissa);
        var num = Math.round((ele.ordinate / 60) * 100) / 100;
        y_array.push(num);
      });
      this.myChart = echarts.init(document.getElementById("plant"));
      let option_base = {
        title: {
          textStyle: {
            fontSize: 18,
          },
          subtextStyle: {
            fontSize: 14,
          },
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            // 坐标轴指示器，坐标轴触发有效
            type: "shadow", // 默认为直线，可选为：'line' | 'shadow'
          },
          extraCssText: "width:160px;height:60px;",
        },
        legend: {
          name: "",
          top: "10px",
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "8%",
          containLabel: true,
        },
        xAxis: [
          {
            type: "category",
            data: x_array,
            axisTick: {
              alignWithLabel: true,
            },
          },
        ],
        yAxis: [
          {
            name: yname,
            nameTextStyle: { fontSize: 18 },
            type: "value",
          },
        ],
        series: [
          {
            name: "",
            type: "bar",
            barMaxWidth: 70,
            barWidth: "60%",
            data: y_array,
            itemStyle: {
              normal: {
                label: {
                  show: true, //开启显示
                  position: "top", //在上方显示
                  textStyle: {
                    //数值样式
                    color: "#000",
                    fontSize: 12,
                  },
                  formatter: function (params) {
                    if (params.value > 0) {
                      return params.value;
                    } else {
                      return "";
                    }
                  },
                },
              },
            },
          },
        ],
      };
      this.myChart.setOption(option_base);
    },
    sectionEchart(data) {
      var x_name = [];
      var y_array = [];
      var lineData = [];
      data.forEach((ele) => {
        x_name.push(ele.abscissa);
        var num = Math.round((ele.ordinate / 60) * 100) / 100;
        y_array.push(num);
        lineData.push(this.$datatype.formatDecimal(ele.rate, 1, 2, false));
      });
      if (
        this.myChart !== null &&
        this.myChart !== "" &&
        this.myChart !== undefined
      ) {
        this.myChart.dispose();
      }
      this.myChart = echarts.init(document.getElementById("plant"));
      var option = {
        title: {
          text: "" /* 故障统计时间Pareto图 */,
          textStyle: {
            align: "center",
            fontSize: 18,
          },
          subtextStyle: {
            fontSize: 14,
          },
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            // 坐标轴指示器，坐标轴触发有效
            type: "cross", // 默认为直线，可选为：'line' | 'shadow'
          },
          extraCssText: "width:160px;height:80px;",
        },
        xAxis: [
          {
            type: "category",
            nameGap: 40,
            data: x_name,
            name: "",
            axisTick: {
              alignWithLabel: true,
            },
          },
        ],
        yAxis: [
          {
            type: "value",
            name: this.$t("900865"),
            nameTextStyle: { fontSize: 18 },
            data: "",
          },
          {
            type: "value",
            axisLabel: {
              formatter: "{value}%",
            },
          },
        ],
        series: [
          {
            itemStyle: {
              normal: {
                label: {
                  show: true,
                },
              },
            },
            name: this.$t("500086"),
            type: "bar",
            barMaxWidth: 70,
            data: y_array,
          },
          {
            itemStyle: {
              normal: {
                label: {
                  show: true,
                },
              },
            },
            yAxisIndex: 1,
            name: this.$t("500077"),
            type: "line",
            data: lineData,
          },
        ],
      };
      this.myChart.setOption(option);
    },
    mockTableData1(tablelist) {
      let data = [];
      tablelist.forEach((item) => {
        if (item) {
          data.push({
            abscissa: item.abscissa,
            ordinate: this.timechange(
              Math.round(item.ordinate * 60 * 100) / 100
            ),
            Rate: item.rate,
          });
        }
      });
      this.tableData1 = data;
    },
    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 = Math.floor(((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 = Math.floor(num - h * 3600 - m * 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 = Math.floor(num) + this.$t("1104");
        return str;
      }
    },
    clear() {
      this.inittime();
      this.initlevel();
      this.type2 = 0;
      this.type3 = 0;
      this.parentmode = "";
      this.childmode = "";
      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>
