<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"
          style="width:260px;"
        ></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('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 class="searchBtn">
        <!-- 查询 -->
        <Button
          type="primary"
          class="twoWord"
          icon="ios-search-outline"
          @click="searchdata()"
        >{{$t("1001")}}</Button>
        <!-- 清空查询 -->
        <Button
          type="primary"
          class="fourWord"
          icon="ios-close-circle-outline"
          @click="clear()"
        >{{$t("1039")}}</Button>
      </div>
    </div>
    <!-- 主体内容 -->
    <div class="divborder" id="slicemap" style="overflow:visible;">
      <div
        v-for="(item,index) in allsections_echarts"
        :id="'new_'+index"
        :key="index"
        class="canvas"
      ></div>
    </div>
    <!-- 弹框 -->
    <Modal class="newModalClass" v-model="showModal" :styles="{width:'600px'}">
      <p slot="header">
        <span>{{ $t("666601") }}</span>
      </p>
      <div class="modal_body">
        <div class="filter">
          <label>{{$t("400000")}}：</label>
          <label class="sliceLabel">{{machinestate}}</label>
        </div>
        <div class="filter">
          <label>{{$t("900908")}}：</label>
          <label class="sliceLabel">{{timerange}}</label>
        </div>
        <div class="filter">
          <label>{{$t("500083")}}：</label>
          <label class="sliceLabel">{{duration}}</label>
        </div>
        <div class="filter">
          <label>{{$t("900858")}}：</label>
          <label class="sliceLabel">{{iserror}}</label>
        </div>
        <div class="filter">
          <label>
            <i>*</i>
            {{$t("950085")}}：
          </label>
          <Select
            v-model="parentmode"
            clearable
            class="searchSelect MaxWidth"
            @on-change="parentmodechange"
          >
            <Option
              v-for="(item,key) in parentmodes"
              :value="item.id"
              :key="key"
            >{{item.workingmodename}}</Option>
          </Select>
        </div>
        <div class="filter">
          <label>
            <i>*</i>
            {{$t("950049")}}：
          </label>
          <Select v-model="childmode" clearable class="searchSelect MaxWidth">
            <Option
              v-for="(item,key) in childmodes"
              :value="item.id"
              :key="key"
            >{{item.workingmodename}}</Option>
          </Select>
        </div>
        <div class="filter">
          <label>
            <i>*</i>
            {{$t("1209")}}：
          </label>
          <Select v-model="user" label-in-value class="searchSelect MaxWidth" @on-change="getText">
            <Option v-for="(item,key) in users" :value="item.id" :key="key">{{item.text}}</Option>
          </Select>
        </div>
        <div class="filter">
          <label>{{$t("1030")}}：</label>
          <Input class="searchInput MaxWidth" v-model="remark" />
        </div>
      </div>
      <div slot="footer">
        <Button size="large" @click="showModal=false">{{$t("1033")}}</Button>
        <Button type="primary" size="large" @click="setSliceInfo()">{{$t("1011")}}</Button>
      </div>
    </Modal>
  </div>
</template>

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

export default {
  data() {
    return {
      echo_start_timestamp: 0,
      echo_end_timestamp: 0,
      // 产线层级集合
      leveldata: [],
      // 产线层级id
      levelid: 0,
      // 列表数据
      tableData1: [],
      // 时间范围
      dateTime: "",
      // 开始时间
      starttime: "",
      // 结束时间
      endtime: "",
      page: 1,
      pagesize: 10,
      total: 0,
      obj: {},
      treedata1: [],
      datalevel: [],
      sectionIdStr: "",
      allsections: [],
      allsections_echarts: [],
      showModal: false,
      machinestate: "",
      timerange: "",
      duration: "",
      iserror: "",

      parentmodes: [],

      childmodes: [],

      users: [],
      username: "",
      remark: "",
      machineId: 0,
      // 父级工作模式
      parentmode: "",
      // 子级工作模式
      childmode: "",
      // 填写人员
      user: "",
      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.inisectionIds();
    this.searchdata();
  },
  methods: {
    inittime() {
      let dt = new Date();
      var date = this.$time.getDate(0, 1);
      var hour = date + " 08:10:00";
      var now = date + " " + dt.getHours() + ":" + dt.getMinutes() + ":00";
      var hour1 = date + " 00:10:00";
      if (now > hour) {
        // 如果现在时间大于8小时，时间段就是8点到现在时间减去10分钟
        this.dateTime = [
          date + " 08:00:00",
          this.$time.timestampToTimeSpan(
            (Date.parse(now) - 10 * 60 * 1000) / 1000
          ),
        ];
      } else {
        if (now < hour1) {
          this.dateTime = [
            date + " 00:00:00",
            this.$time.timestampToTimeSpan(now / 1000),
          ];
        } else {
          this.dateTime = [
            date + " 00:00:00",
            this.$time.timestampToTimeSpan(
              (Date.parse(now) - 10 * 60 * 1000) / 1000
            ),
          ];
        }
      }

      if(this.queryInfo){
        this.dateTime = this.queryInfo.datetime;
      }

    },
    selectdate(e) {
      this.dateTime = [e[0], e[1]];
      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();
    },
    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;
            }
          }
        });
    },
    inisectionIds() {
      axios
        .request({
          url: "/config/ProjectLevelSection/GetSectionSelect?reverselevel=1",
          method: "get",
        })
        .then((res) => {
          // 产线层级
          this.allsections = [];
          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 });
              });
              this.allsections_echarts = this.allsections;
            }
          }
        });
    },
    searchdata() {
      this.search();
    },
    search() {
      if (this.dateTime === undefined || this.dateTime === "") {
        this.$Message.error(this.$t("800154"));
        return false;
      }
      var sectionIds = [];
      if (this.sectionIdStr.length > 0) {
        this.sectionIdStr.forEach((ele) => {
          sectionIds.push(parseInt(ele));
        });
      }

      // 节点赋值
      this.allsections_echarts = this.allsections;
      var timeSection =
        moment(this.dateTime[0]).format("YYYY-MM-DD HH:mm:ss") +
        " - " +
        moment(this.dateTime[1]).format("YYYY-MM-DD HH:mm:ss");
      var params = {
        timeSection: timeSection,
        sectionId: this.levelid,
        sectionIdStr: sectionIds.join(","),
      };
      axios
        .request({
          url: "/cnc/ProjectSectionMachine/MachineCanvasPrograms",
          params,
          method: "get",
        })
        .then((res) => {
          this.allsections_echarts = res.data.pareto;
          this.echo_start_timestamp =
            new Date(res.data.startTime).getTime() / 1000;
          this.echo_end_timestamp = new Date(res.data.endTime).getTime() / 1000;
          this.GetCanvasData(res.data.canvas, res.data.pareto);
        });
    },
    // 本方法中对每一条 X-Range 图的图例百分比进行了处理
    GetCanvasData(canvasData, paretoData) {
      // 获取状态占比
      let statusData = [];
      paretoData.forEach((ele) => {
        var paretoAllData = ele.listShutdownHoldTime;
        var paretoSpan = ele.total;
        let beforePer = 0;
        // 所有时间总和
        let totalSubmit = 0;
        let lineData = [];
        // 除了关机时间，其他时间之和
        let totaltime = 0;
        paretoAllData.forEach((ele) => {
          totalSubmit += ele.timeSpan;
          if (ele.factor === "shutdown") {
          } else {
            totaltime += ele.timeSpan;
          }
        });

        // 数据都是0时
        if (totalSubmit === 0) {
          totalSubmit = parseInt(paretoSpan);
          var tmp_paretoAllData = paretoAllData;
          tmp_paretoAllData[0].timeSpan = parseInt(paretoSpan);
          tmp_paretoAllData.forEach((ele) => {
            beforePer = ele.timeSpan / totalSubmit;
            lineData.push(
              this.$datatype.formatDecimal(beforePer * 100, 1, 2, false) + "%"
            );
          });
        } else {
          // 数据不是0时，关机时间等于总时间减去其他四个状态时间之和
          // 给关机时间重新赋值
          let data_paretoAllData = paretoAllData;
          // 关机时间
          let numtime = paretoSpan - totaltime;
          if (numtime < 0) {
            numtime = 0;
          }
          // 重新赋值关机时间
          data_paretoAllData.forEach((ele) => {
            if (ele.factor === "shutdown") {
              ele.timeSpan = numtime;
            }
          });
          data_paretoAllData.forEach((ele) => {
            // 关机时间除以时间段
            if (ele.factor === "shutdown") {
              beforePer = numtime / paretoSpan;
              lineData.push(
                this.$datatype.formatDecimal(beforePer * 100, 1, 2, false) + "%"
              );
            } else {
              beforePer = ele.timeSpan / paretoSpan;
              lineData.push(
                this.$datatype.formatDecimal(beforePer * 100, 1, 2, false) + "%"
              );
            }
          });
        }
        statusData.push(lineData);
      });
      this.createcanvas(canvasData, statusData);
      // statusData存放了每一条 X-Range 图的图例百分比数据
      // $(".slice-map").show();
      // $(".loading-div").hide();
    },
    createcanvas(canvasData, statusData) {
      canvasData.forEach((canvasDataVal, canvasDataKey) => {
        // 在没有数据，只有一条数据时，用来调整切片图的样式，人为填充2-3条数据。
        let temp_v = 1;
        /**********************/
        // 处理程序号数据
        var programNos = [];
        var programNoss;
        var programNosValue;
        // 如果每一条数据中的 programNos 数组有数据
        if (
          canvasDataVal.programNos != null &&
          canvasDataVal.programNos.length > 0
        ) {
          canvasDataVal.programNos.forEach((ele) => {
            programNoss = {};
            programNosValue = [];
            // 在这里将开始时间和结束时间转换成时间戳形式
            var start = this.$time.datestrtotime(ele.startTime);
            var end = this.$time.datestrtotime(ele.endTime);
            // 数组中各位置数据：开始时间 结束时间 设备ID 程序号 产量
            programNosValue.push(start);
            programNosValue.push(end);
            programNosValue.push(ele.machineId);
            programNosValue.push(ele.programNo);
            programNosValue.push(ele.yield);
            programNoss.isprogram = ele.isprogram;
            programNoss.color = ele.color;
            programNoss.value = programNosValue;
            programNos.push(programNoss);
          });
        }

        var list = [];
        /**********************/
        // 如果条线状态数据为空数组
        if (
          canvasDataVal.list_msh !== null &&
          canvasDataVal.list_msh.length < 1
        ) {
          var start_time = Date.parse(canvasDataVal.t_start_time);
          var end_time = Date.parse(canvasDataVal.t_end_time);
          list = [
            [start_time, end_time + temp_v, 0],
            [end_time - temp_v, end_time, 0],
          ];
        } //如果条线状态数据只有一条
        else if (
          canvasDataVal.list_msh !== null &&
          canvasDataVal.list_msh.length === 1
        ) {
          canvasDataVal.list_msh.forEach((canvasDataVal_v) => {
            // 条线状态数据只有一条，人为分割成三条数据
            // 开始时间-开始时间+1  开始时间+1-结束时间-1  结束时间-1-结束时间
            // 数组各位置数据 开始时间 结束时间 设备状态 设备ID 是否异常 工作模式 工作模式ID 备注 操作人ID 是否是假数据 父级工作模式ID 父级工作模式
            list = [
              [
                canvasDataVal_v.start_time,
                canvasDataVal_v.start_time + temp_v,
                canvasDataVal_v.machine_status,
                canvasDataVal.machineID,
                canvasDataVal_v.isException,
                canvasDataVal_v.workMode,
                canvasDataVal_v.workModeId,
                encodeURI(canvasDataVal_v.remark),
                canvasDataVal_v.userId,
                canvasDataVal_v.isFake,
                canvasDataVal_v.workModeParentId,
                canvasDataVal_v.workModeParent,
              ],
              [
                canvasDataVal_v.start_time + temp_v,
                canvasDataVal_v.end_time - temp_v,
                canvasDataVal_v.machine_status,
                canvasDataVal.machineID,
                canvasDataVal_v.isException,
                canvasDataVal_v.workMode,
                canvasDataVal_v.workModeId,
                encodeURI(canvasDataVal_v.remark),
                canvasDataVal_v.userId,
                canvasDataVal_v.isFake,
                canvasDataVal_v.workModeParentId,
                canvasDataVal_v.workModeParent,
              ],
              [
                canvasDataVal_v.end_time - temp_v,
                canvasDataVal_v.end_time,
                canvasDataVal_v.machine_status,
                canvasDataVal.machineID,
                canvasDataVal_v.isException,
                canvasDataVal_v.workMode,
                canvasDataVal_v.workModeId,
                encodeURI(canvasDataVal_v.remark),
                canvasDataVal_v.userId,
                canvasDataVal_v.isFake,
                canvasDataVal_v.workModeParentId,
                canvasDataVal_v.workModeParent,
              ],
            ];
          });
        } // 如果条线状态数据不止一条
        else if (
          canvasDataVal.list_msh !== null &&
          canvasDataVal.list_msh.length > 1
        ) {
          // 条件状态数据不止一条，就正常处理，不需要人为造假数据
          // 数组各位置数据 开始时间 结束时间 设备状态 设备ID 是否异常 工作模式 工作模式ID 备注 操作人ID 是否是假数据 父级工作模式ID 父级工作模式 操作人名称
          canvasDataVal.list_msh.forEach((canvasDataVal_v) => {
            var data = [];
            data.push(canvasDataVal_v.start_time);
            data.push(canvasDataVal_v.end_time);
            data.push(canvasDataVal_v.machine_status);
            data.push(canvasDataVal.machineID);
            data.push(canvasDataVal_v.isException);
            data.push(canvasDataVal_v.workMode);
            data.push(canvasDataVal_v.workModeId);
            data.push(encodeURI(canvasDataVal_v.remark));
            data.push(canvasDataVal_v.userId);
            data.push(canvasDataVal_v.isFake);
            data.push(canvasDataVal_v.workModeParentId);
            data.push(canvasDataVal_v.workModeParent);
            data.push(canvasDataVal_v.userName);
            list.push(data);
          });
        }
        // 如果处理得到的切片数据有效
        if (list !== null && list.length > 1) {
          var data = [];
          data.push(list[list.length - 1][1] + 1);
          data.push(list[list.length - 1][1] + 1);
          data.push(0);
          data.push(0);
          data.push(0);
          data.push(0);
          data.push(0);
          data.push(0);
          data.push(0);
          data.push(0);
          data.push(0);
          data.push("");
          list.push(data);

          // 第一条加入空数据，处理空白条问题
          var arr = [];
          list.unshift(arr);
        }

        // document.getElementById('new_'+canvasDataKey).innerHTML = ''
        // 画图
        this.newGetCanvasDrawing(
          list,
          canvasDataKey,
          canvasDataVal.machineTitle,
          statusData[canvasDataKey],
          programNos
        );
      });
    },
    newGetCanvasDrawing(
      data,
      canvasDataKey,
      machineTitle,
      machineStatus,
      data1
    ) {
      const _this = this;
      var nameList = [
        this.$t("500040"),
        this.$t("500041"),
        this.$t("500042"),
        this.$t("500043"),
        this.$t("500044"),
        this.$t("500220"),
      ];
      var colorList = [
        "#22333b",
        "#5cb85c",
        "#3574ad",
        "#f0ad4e",
        "#d71518",
        "#FFFF33",
      ];
      data = echarts.util.map(data, function (item, index) {
        return {
          value: item,
          itemStyle: {
            normal: {
              color: colorList[item[2]],
            },
          },
        };
      });
      var option = {
        title: {
          text: machineTitle,
          left: "50",
          padding: [5, 0, 0, 0],
          textStyle: {
            fontSize: 18,
          },
          subtextStyle: {
            fontSize: 14,
          },
        },
        tooltip: {
          backgroundColor: "rgba(255,0,0,0)", // 通过设置rgba调节背景颜色与透明度
          formatter: (params) => {
            // 显示设备状态、程序号、产品名称、是否异常、工作模式
            var showHtm = "";
            // 数组各位置数据 开始时间 结束时间 设备状态 设备ID 是否异常 工作模式 工作模式ID 备注 操作人ID 是否是假数据 父级工作模式ID 父级工作模式
            var from = this.fmtDate(params.value[0]);
            var to = this.fmtDate(params.value[1]);
            var status = nameList[params.value[2]];
            if (
              params.data.isprogram !== undefined &&
              params.data.isprogram === 1
            ) {
              var programno = params.value[3];
              var yield1 = params.value[4];
              showHtm +=
                '<div style="background-color:gray;border-radius:5px;">' +
                this.$t("600009") +
                "：" +
                programno +
                "<br>" +
                this.$t("500108") +
                "：" +
                yield1 +
                "<br>" +
                "from： " +
                from +
                "<br>" +
                "to： " +
                to +
                "</div>";
              return showHtm;
            } else {
              var isException = params.value[4]; // 是否异常
              var workMode = params.value[5]; // 子级工作模式
              var workModeParent = params.value[11]; // 父级工作模式
              var backgroundColor =
                isException === 1 ? "rgba(255,0,0,0.7)" : "gray";
              var ExceptionStr =
                isException === 1 ? this.$t("1000020") : this.$t("1000021");
              showHtm +=
                '<div style="background-color:' +
                backgroundColor +
                ';border-radius:5px;">' +
                this.$t("400000") +
                ": " +
                status +
                "<br>" +
                this.$t("900858") +
                "：" +
                ExceptionStr +
                "<br>" +
                this.$t("950085") +
                "：" +
                workModeParent +
                "<br>" +
                this.$t("950049") +
                "：" +
                workMode +
                "<br>" +
                "from： " +
                from +
                "<br>" +
                "to： " +
                to +
                "</div>";
              return showHtm;
            }
          },
        },
        legend: {
          orient: "horizontal",
          padding: [30, 0, 0, 0],
          data: nameList,
          formatter: (name) => {
            var index = 0;
            var clientlabels = nameList;
            // var clientcounts = [9, 1, 10, 45, 77];
            var clientcounts = machineStatus;
            clientlabels.forEach(function (value, i) {
              if (value === name) {
                index = i;
              }
            });
            return name + "  " + clientcounts[index];
          },
        },
        color: colorList,
        grid: {
          top: "28%",
          left: "5%",
          right: "5%",
          bottom: "67",
          containLable: true,
        },
        xAxis: {
          show: true,
          scale: true,
          splitNumber: 8,
          axisLabel: {
            margin: 5,
            interval: 0,
            rotate: 0,
            showMaxLabel: false,
            formatter: (value) => {
              return this.fmtDate(value);
            },
          },
          splitLine: {
            show: true,
          },
          // min: "dataMin",
          // max: "dataMax",
          min: _this.echo_start_timestamp,
          max: _this.echo_end_timestamp,
        },
        yAxis: {
          show: false,
          max: 1,
          min: 0,
          splitNumber: 1,
        },
        series: [
          {
            type: "custom",
            renderItem: this.renderItem,
            dimensions: ["from", "to", "profit"],
            name: [this.$t("500040")],
            data: data,
          },
          {
            type: "custom",
            renderItem: this.renderItem,
            dimensions: ["from", "to", "profit"],
            name: [this.$t("500041")],
            data: data,
          },
          {
            type: "custom",
            renderItem: this.renderItem,
            dimensions: ["from", "to", "profit"],
            name: [this.$t("500042")],
            data: data,
          },
          {
            type: "custom",
            renderItem: this.renderItem,
            dimensions: ["from", "to", "profit"],
            name: [this.$t("500043")],
            data: data,
          },
          {
            type: "custom",
            renderItem: this.renderItem,
            dimensions: ["from", "to", "profit"],
            name: [this.$t("500044")],
            data: data,
          },
          {
            type: "custom",
            renderItem: this.renderItem2,
            dimensions: ["from", "to", "profit"],
            name: [this.$t("500041")],
            itemStyle: {
              normal: {
                // 随机显示程序号背景色
                // color:function(d){return "#"+Math.floor(Math.random()*(256*256*256-1)).toString(16);}
                // 定制显示（按顺序）
                color: function (params) {
                  // var colorList = ['#FF6EB4','#DEB887','#DB7093','#9B30FF','#A0522D', '#87CEFF','#00FA9A'];
                  // var index=params.dataIndex;

                  // //颜色循环显示
                  // if(params.dataIndex >= colorList.length)
                  // {
                  //     index=params.dataIndex%colorList.length;
                  // }
                  // return colorList[index];
                  return params.data.color;
                },
              },
            },
            data: data1,
          },
        ],
      };
      var div = document.getElementById("new_" + canvasDataKey);
      var myChart = echarts.init(div);
      if (typeof option === "object") {
        myChart.setOption(option, true);
      }
      // 点击事件
      myChart.on("click", (params) => {
        // 弹出框
        var data = params.value;
        if (
          params.data.isprogram !== undefined &&
          params.data.isprogram === 1
        ) {
        } else {
          // 假数据，不弹出
          if (data[9] === 1) {
            return false;
          }
          // 设备状态
          var status = "";
          switch (data[2]) {
            case 0:
              status = this.$t("500040");
              break;
            case 1:
              status = this.$t("500041");
              break;
            case 2:
              status = this.$t("500042");
              break;
            case 3:
              status = this.$t("500043");
              break;
            case 4:
              status = this.$t("500044");
              break;
            case 5:
              status = this.$t("500220");
              break;
            default:
              status = "";
              break;
          }
          this.machinestate = status;
          // 时间天、小时、分钟、秒
          this.duration = this.timechange(data[1] - data[0]);
          this.timerange =
            this.$time.timestampToTimeSpan(data[0]) +
            " - " +
            this.$time.timestampToTimeSpan(data[1]);
          this.iserror =
            data[4] === 1 ? this.$t("1000020") : this.$t("1000021");
          this.remark = decodeURI(data[7]);
          this.machineId = data[3];
          this.iniparentmodes(data[3]);
          this.parentmode = data[10];
          this.inichildmodes(this.parentmode);
          this.childmode = data[6];

          this.iniusers();
          if (data[8] === 0) {
            // 加载当前用户
            this.user = this.$store.state.user.userId;
          } else {
            this.user = data[8];
          }
          this.username = data[12];
          this.showModal = true;
        }
      });
    },
    iniparentmodes(machineid) {
      axios
        .request({
          url:
            "/cnc/MachineWordingMode/GetParentModesByMachineId?machineID=" +
            machineid,
          method: "get",
        })
        .then((res) => {
          this.parentmodes = res.data.data;
        });
    },
    inichildmodes(parentid) {
      var data = {
        parentIds: parentid,
      };
      this.axios
        .request({
          url: "/cnc/MachineWordingMode/GetSonModesByParents",
          data,
          method: "post",
        })
        .then((res) => {
          this.childmode = "";
          this.childmodes = res.data.data;
          if (res.data.data.length > 0) {
            res.data.data.forEach((item, index) => {
              if (index === 0) {
                this.childmode = item.id;
              }
            });
          }
        });
    },
    parentmodechange() {
      this.inichildmodes(this.parentmode);
    },
    iniusers() {
      axios
        .request({
          url: "/cnc/InformationConfiguration/Getusers",
          method: "get",
        })
        .then((res) => {
          this.users = res.data.data;
        });
    },
    renderItem(params, api) {
      var yValue = 1;
      var start = api.coord([api.value(0), yValue]);
      var size = api.size([api.value(1) - api.value(0), yValue]);
      var style = api.style();
      return {
        type: "rect",
        shape: {
          x: start[0],
          y: start[1],
          width: size[0],
          height: 50,
        },
        style: style,
      };
    },
    renderItem2(params, api) {
      var yValue = 1;
      var start = api.coord([api.value(0), yValue]);
      var size = api.size([api.value(1) - api.value(0), yValue]);
      var style = api.style();
      return {
        type: "rect",
        shape: {
          x: start[0],
          y: start[1] + 54,
          width: size[0],
          height: 7,
        },
        style: style,
      };
    },
    fmtDate(UNIX_timestamp) {
      var a = new Date(UNIX_timestamp * 1000);
      var months = [
        "01",
        "02",
        "03",
        "04",
        "05",
        "06",
        "07",
        "08",
        "09",
        "10",
        "11",
        "12",
      ];
      var month = months[a.getMonth()];
      var date = (a.getDate() < 10 ? "0" + a.getDate() : a.getDate()) + " ";
      var hour = (a.getHours() < 10 ? "0" + a.getHours() : a.getHours()) + ":";
      var min =
        (a.getMinutes() < 10 ? "0" + a.getMinutes() : a.getMinutes()) + ":";
      var sec = a.getSeconds() < 10 ? "0" + a.getSeconds() : a.getSeconds();
      var time = month + "/" + date + hour + min + sec;
      return time;
    },
    // 清空查询
    clear() {
      // 清空产线层级搜索条件
      this.leveldata = [];
      this.levelid = 0;
      // 清空快捷工位查询搜索条件
      this.sectionIdStr = "";
      // 初始化时间范围搜索条件
      this.inittime();
      // 查询
      this.searchdata();
    },

    // 设置切片信息
    setSliceInfo() {
      // 拿到当前组件实例
      const _this = this;
      // 解构取值
      let {
        machineId,
        childmode,
        username,
        timerange,
        remark,
        parentmode,
        user,
      } = this;
      // 表单必填验证
      if (!parentmode) {
        _this.$Message.error(_this.$t(666602));
        return false;
      }

      if (!childmode) {
        _this.$Message.error(_this.$t(666603));
        return false;
      }

      if (!user) {
        _this.$Message.error(_this.$t(666604));
        return false;
      }

      // 组装请求参数
      let data = {
        machineId,
        modeId: childmode,
        userName: username,
        time: timerange,
        remark,
      };
      _this.axios
        .request({
          url: "/cnc/MachineWordingMode/SetWorkingMode",
          data,
          method: "post",
        })
        .then((res) => {
          let result = res.data;
          if (result.ret == 1) {
            _this.showModal = false;
            _this.searchdata();
            _this.$Message.success(_this.$t("" + result.msg));
          } else {
            _this.searchdata();
            _this.$Message.error(_this.$t("" + result.msg));
          }
        });
    },

    getText(val) {
      this.username = val.label;
    },
    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>
<style lang="less" scoped>
.echart-div-list {
  margin-top: 15px;
  border: 1px solid #ddd;
  padding: 15px;
}

.canvas {
  height: 180px;
  min-width: 1000px;
}

.sliceLabel {
  width: 300px !important;
  text-align: left !important;
}
</style>
