<template>
  <div class="testdiv">
    <!-- 看板标题 -->
    <div class="top_title">
      <span>{{ title }}</span>
      <img :src="imgLogo" class="logo" @click="back" />
      <div class="times_bg">{{ nowTime }}</div>
      <div class="setting" @click="openSet()">
        <img src="../../../static/images/setting.svg" />
      </div>
    </div>
    <div class="middle_bottom">
      <div ref="echartDiv" style="overflow: visible">
        <div v-for="(v, i) in erts" :id="`nw_${i}`" :key="i" class="cvs"></div>
      </div>
    </div>
    <!-- 弹出框 -->
    <Modal :styles="setting" v-model="setModal" footer-hide>
      <p slot="header">
        <span>请选择要跳转的组合</span>
      </p>
      <div class="modal_body" style="max-height: 160px; overflow-y: auto">
        <List size="small">
          <ListItem v-for="(v, i) in combList" :key="i">
            <span class="setItem" @click="play(v.id)">{{ v.title }}</span>
          </ListItem>
        </List>
      </div>
    </Modal>
  </div>
</template>

<script>
import moment from "moment";
import echarts from "echarts";
import { mapState } from "vuex";
import i18n from "@/locale";

export default {
  inject: ["reload"],
  data() {
    return {
      imgLogo: require("../../../static/images/siger.png"),
      nowTime: moment(new Date().getTime()).format("YYYY-MM-DD"),
      erts: [],
      charts: {},
      combList: [],
      setModal: false,
    };
  },
  computed: {
    ...mapState(["user"]),
    combId() {
      return this.$route.query.combId;
    },
    condition() {
      return this.$route.query.condition;
    },
    title() {
      return this.$route.query.title;
    },
    setting() {
      return {
        position: "fixed",
        top: "50px",
        right: "50px",
        width: "250px",
      };
    },
  },
  created() {
    if (this.user.logo) {
      this.imgLogo = this.user.logo;
    }
  },
  mounted() {
    this.inisectionIds();
    this.searchdata();
  },
  methods: {
    openSet() {
      const _this = this;
      _this.axios
        .request({
          url: "/dashboard/DashboardConfig/GetCombList",
          method: "get",
        })
        .then((res) => {
          let result = res.data;
          if (result.ret == 1) {
            _this.combList = result.data_comb;
            _this.setModal = true;
          }
        });
    },
    // 页面播放
    play(combId) {
      const _this = this;
      let params = {
        id: combId,
        projectid: _this.user.projectId,
      };
      _this.axios
        .request({
          url: "/dashboard/DashboardShow/getallcombpages",
          params,
          method: "get",
        })
        .then((res) => {
          let result = res.data;
          if (result.ret == 1) {
            _this.$router.replace({ name: "8000063", query: { combId } });
            _this.reload();
          }
        });
    },
    // 初始化页面产线容器
    inisectionIds() {
      let allsections = [];
      let conditionArr = this.condition ? this.condition.split("-") : [];
      for (let i = 0; i < conditionArr.length; i++) {
        allsections.push({});
      }
      this.erts = allsections;
    },
    searchdata() {
      let condition = this.condition;
      this.$nextTick(() => {
        this.search(condition);
      });
    },
    search(condition) {
      let params = {
        timeSection: `${this.nowTime} 00:00:00 - ${this.nowTime} ${moment(
          new Date().getTime()
        ).format("HH:mm:ss")}`,
        sectionIdStr: condition ? condition.replace(/-/g, ",") : "",
        // 占位
        // sectionId: "1",
      };
      this.axios
        .request({
          url: "/cnc/ProjectSectionMachine/MachineCanvasProgramsDP",
          params,
          method: "get",
        })
        .then((res) => {
          let result = res.data;
          this.GetCanvasData(result.canvas, result.pareto);
        });
    },
    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((e) => {
          totalSubmit += e.timeSpan;
          if (e.factor == "shutdown") {
          } else {
            totaltime += e.timeSpan;
          }
        });
        // 如果状态分布数组中各状态时间加起来的总和是 0 时
        if (totalSubmit == 0) {
          totalSubmit = parseInt(paretoSpan);
          var tmp_paretoAllData = paretoAllData;
          tmp_paretoAllData[0].timeSpan = parseInt(paretoSpan);
          tmp_paretoAllData.forEach((el) => {
            beforePer = el.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((le) => {
            if (le.factor == "shutdown") {
              le.timeSpan = numtime;
            }
          });
          data_paretoAllData.forEach((v) => {
            // 关机状态特殊处理
            if (v.factor == "shutdown") {
              beforePer = numtime / paretoSpan;
              lineData.push(
                this.$datatype.formatDecimal(beforePer * 100, 1, 2, false) + "%"
              );
            } else {
              beforePer = v.timeSpan / paretoSpan;
              lineData.push(
                this.$datatype.formatDecimal(beforePer * 100, 1, 2, false) + "%"
              );
            }
          });
        }
        statusData.push(lineData);
      });
      this.createcanvas(canvasData, statusData);
    },
    createcanvas(canvasData, statusData) {
      canvasData.forEach((canvasDataVal, canvasDataKey) => {
        // 在没有数据，只有一条数据时，用来调整切片图的样式，人为填充2-3条数据。
        let temp_v = 1;
        /**********************/
        // 处理程序号数据
        var programNos = [];
        var programNoss;
        var programNosValue;
        if (canvasDataVal.programNos && canvasDataVal.programNos.length) {
          canvasDataVal.programNos.forEach((ele) => {
            programNoss = {};
            programNosValue = [];
            var start = this.$time.datestrtotime(ele.startTime);
            var end = this.$time.datestrtotime(ele.endTime);
            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 && 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 &&
          canvasDataVal.list_msh.length == 1
        ) {
          canvasDataVal.list_msh.forEach((canvasDataVal_v) => {
            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 &&
          canvasDataVal.list_msh.length > 1
        ) {
          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 && 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('nw_'+canvasDataKey).innerHTML = ''
        // 画图
        this.newGetCanvasDrawing(
          list,
          canvasDataKey,
          canvasDataVal.machineTitle,
          statusData[canvasDataKey],
          programNos
        );
      });
    },
    newGetCanvasDrawing(
      data,
      canvasDataKey,
      machineTitle,
      machineStatus,
      data1
    ) {
      var nameList = [
        i18n.t(500040),
        i18n.t(500041),
        i18n.t(500042),
        i18n.t(500043),
        i18n.t(500044),
        i18n.t(500220),
      ];
      var colorList = [
        "#C6C5CB",
        "#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,
          textStyle: {
            color: "#FFFFFF",
          },
          top: "middle",
        },
        tooltip: {
          backgroundColor: "rgba(255,0,0,0)", // 通过设置rgba调节背景颜色与透明度
          formatter: (params) => {
            // 显示设备状态、程序号、产品名称、是否异常、工作模式
            var showHtm = "";
            var from = this.fmtDate(params.value[0]);
            var to = this.fmtDate(params.value[1]);
            var status = nameList[params.value[2]];
            if (params.data.isprogram && params.data.isprogram == 1) {
              var programno = params.value[3];
              var yield1 = params.value[4];
              showHtm +=
                '<div style="padding:5px;background-color:gray;border-radius:10px;">' +
                i18n.t("600009") +
                ":" +
                programno +
                "<br>" +
                i18n.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 ? i18n.t("1000020") : i18n.t("1000021");
              showHtm +=
                '<div style="padding:5px;background-color:' +
                backgroundColor +
                ';border-radius:10px;">' +
                i18n.t("400000") +
                ": " +
                status +
                "<br>" +
                i18n.t("900858") +
                "：" +
                ExceptionStr +
                "<br>" +
                i18n.t("950085") +
                "：" +
                workModeParent +
                "<br>" +
                i18n.t("950049") +
                "：" +
                workMode +
                "<br>" +
                "from: " +
                from +
                "<br>" +
                "to: " +
                to +
                "</div>";
              return showHtm;
            }
          },
        },
        legend: [
          {
            show: true,
            right: 0,
            top: "middle",
            itemGap: 4,
            icon: "circle",
            data: [
              i18n.t(500040),
              "",
              i18n.t(500041),
              "",
              i18n.t(500042),
              "",
              i18n.t(500043),
              "",
              i18n.t(500044),
            ],
            selectedMode: false,
            formatter: function (name) {
              var index = 0;
              nameList.forEach(function (v, i) {
                if (v == name) {
                  index = i;
                }
              });
              return machineStatus[index];
            },
            textStyle: {
              color: "#fff",
              fontSize: 12,
            },
          },
        ],
        color: colorList,
        grid: {
          top: "24%",
          left: "8%",
          right: "6%",
          bottom: "30%",
          containLable: true,
        },
        xAxis: {
          show: true,
          scale: true,
          splitNumber: 10,
          axisLabel: {
            margin: 12,
            interval: 0,
            showMaxLabel: false,
            formatter: (value) => {
              return this.fmtDate(value);
            },
            textStyle: {
              color: "#fff",
              fontSize: 12,
            },
          },
          splitLine: {
            show: false,
          },
          min: "dataMin",
          max: "dataMax",
        },
        yAxis: {
          show: false,
          max: 1,
          min: 0,
          splitNumber: 1,
        },
        series: [
          {
            type: "custom",
            renderItem: this.renderItem,
            dimensions: ["from", "to", "profit"],
            name: [i18n.t("500040")],
            data: data,
          },
          {
            type: "custom",
            renderItem: this.renderItem,
            dimensions: ["from", "to", "profit"],
            name: [i18n.t("500041")],
            data: data,
          },
          {
            type: "custom",
            renderItem: this.renderItem,
            dimensions: ["from", "to", "profit"],
            name: [i18n.t("500042")],
            data: data,
          },
          {
            type: "custom",
            renderItem: this.renderItem,
            dimensions: ["from", "to", "profit"],
            name: [i18n.t("500043")],
            data: data,
          },
          {
            type: "custom",
            renderItem: this.renderItem,
            dimensions: ["from", "to", "profit"],
            name: [i18n.t("500044")],
            data: data,
          },
          // {
          //   type: "custom",
          //   renderItem: this.renderItem2,
          //   dimensions: ["from", "to", "profit"],
          //   name: [i18n.t("500041")],
          //   itemStyle: {
          //     normal: {
          //       color: function (params) {
          //         return params.data.color;
          //       },
          //     },
          //   },
          //   data: data1,
          // },
        ],
      };
      var div = document.getElementById("nw_" + canvasDataKey);
      if (div) {
        if (!this.charts) {
          this.charts = {};
        }
        this.charts[`nw_${canvasDataKey}`] = echarts.init(div);
        this.charts[`nw_${canvasDataKey}`].setOption(option, true);
      }
    },
    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: 5,
    //     },
    //     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;
    },
    // 回退上一级
    back() {
      this.$router.go(-1);
    },
    // 给定分子和分母计算百分比
    percent(num, total) {
      if (num == 0 || total == 0) {
        return 0;
      }
      // 小数点后两位百分比
      return Math.round((num / total) * 10000) / 100.0;
    },
  },
  beforeDestroy() {
    let { charts } = this;
    for (let key in charts) {
      charts[key].clear();
      echarts.dispose(charts[key]);
      charts[key] = null;
    }
    charts = null;
    //删除dom节点
    if (this.$refs.echartDiv) {
      this.$refs.echartDiv.innerHTML = "";
    }
    this.erts = null; //节点
  },
  beforeRouteEnter(to, from, next) {
    if (from.path == "/") {
      next((vm) => {
        vm.$router.replace({ name: "8000063", query: { combId: vm.combId } });
      });
      return false;
    }
    next();
  },
};
</script>
<style lang="less" scoped>
.cvs {
  height: 100px;
}

.testdiv {
  width: 100%;
  max-width: 1920px;
  height: 100%;
  background-image: url("../../../static/images/u0.png");
  background-size: 100% 100%;
  padding: 11px;
  box-sizing: border-box;
  overflow-y: auto;
}

.top_title {
  width: 100%;
  height: 106px;
  background: url("../../../static/images/u2.png") center center no-repeat;
  background-size: 81.25% 100%;
  padding: 0 25px 0 40px;
  box-sizing: border-box;
  display: inline-block;
  text-align: center;
  font-size: 59px;
  color: #fff;
  font-weight: bold;
  line-height: 100px;
  position: relative;
  font-style: italic;

  .logo {
    width: 200px;
    height: 60px;
    float: left;
    margin-top: 27px;
    cursor: pointer;
  }

  .times_bg {
    width: 200px;
    height: 40px;
    font-size: 24px;
    text-align: center;
    line-height: 40px;
    color: #fff;
    float: right;
    background: url("../../../static/images/u4.png") center center no-repeat;
    background-size: 100% 40px;
    margin-top: 34px;
  }
}

.middle_bottom {
  margin-top: 0px;
}

::-webkit-scrollbar {
  display: none;
}
.setting {
  display: inline-block;
  position: fixed;
  right: 20px;
  top: -20px;
  img {
    width: 40px;
    cursor: pointer;
  }
}
.setItem {
  font-size: 14px;
  cursor: pointer;
}
.setItem:hover {
  color: #2d8cf0;
  font-weight: bold;
}
</style>
