<template>
  <div class="t_mcoe">
    <div class="divborder newTableDiv">
      <div class="item">
        <div class="left">
          <div>
            <div class="title">OEE</div>
            <div class="echartdiv">
              <div class="echartitem">
                <div id="DynamicRate" class="echart"></div>
              </div>
            </div>
          </div>
          <div>
            <div class="title">设备状态分布</div>
            <div class="echartdiv">
              <div class="echartitem">
                <div id="StateDistribution" class="echart"></div>
              </div>
            </div>
          </div>
        </div>
        <div class="middle">
          <div class="m_content">
            <div class="title">生产进度一览</div>
            <div class="m_div">
              <div class="top">
                <div class="textcontent">
                  <div>今日已报工</div>
                  <div>{{ total }}</div>
                </div>
                <div class="textcontent">
                  <div>今日OK数</div>
                  <div>{{ totalOk }}</div>
                </div>
                <div class="textcontent">
                  <div>今日NOK数</div>
                  <div>{{ totalNok }}</div>
                </div>
              </div>
              <div class="down">
                <Table
                  v-if="tableData.length"
                  :data="tableData"
                  :columns="tableColumns"
                  :max-height="maxHeight"
                  class="baojunranggaide"
                >
                </Table>
              </div>
            </div>
          </div>
        </div>
        <div class="right">
          <div>
            <div class="title">质量合格率</div>
            <div class="echartdiv">
              <div class="echartitem">
                <div id="QualityRate" class="echart"></div>
              </div>
            </div>
          </div>
          <div>
            <div class="title">设备报警分析</div>
            <div class="echartdiv">
              <div class="echartitem">
                <div id="AlarmAnalysis" class="echart"></div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import axios from "@/libs/api.request";
import echarts from "echarts";
import moment from "moment";

export default {
  name: "t_mcoe",
  inject: ["reload"],
  props: {
    curLevel: {
      type: Array,
    },
    levelNums: {
      type: Number,
    },
    signDetail: {
      type: Object,
    },
  },
  data() {
    return {
      sectionid: 0,
      daterange: [],
      total: 0,
      totalOk: 0,
      totalNok: 0,
      tableData: [],
      tableColumns: [
        {
          title: "订单号",
          key: "orderno",
          align: "center",
        },
        {
          title: "工单号",
          key: "code",
          align: "center",
        },
        {
          title: "设备",
          key: "machine",
          align: "center",
        },
        {
          title: "产品名称",
          key: "productname",
          align: "center",
        },
        {
          title: "OK数量",
          key: "okcnt",
          align: "center",
        },
        {
          title: "NOK数量",
          key: "ngcnt",
          align: "center",
        },
        {
          title: "报工时间",
          key: "time",
          align: "center",
          width: 180,
        },
      ],
      maxHeight: 0,
      // Echarts 实例
      DynamicRate_echart: null,
      QualityRate_echart: null,
      State_echart: null,
      Alarm_echart: null,
    };
  },
  mounted() {
    const _this = this;
    // 若当前页面不是从签到签出页面跳转过来的，就返回签到签出页面
    if (!_this.curLevel.length) {
      _this.$router.replace({
        name: "t_sign",
      });
      return false;
    }
    _this.sectionid = _this.curLevel[_this.curLevel.length - 1];
    let today = moment(new Date()).format("YYYY-MM-DD");
    let begin = `${today} 00:00:00`;
    let end = `${today} 23:59:59`;
    _this.daterange = [begin, end];

    _this.baseEcharts();
    _this.search();
    _this.getMaxHeight();

    window.onresize = () => {
      if (_this.DynamicRate_echart) {
        _this.DynamicRate_echart.resize();
      }
      if (_this.QualityRate_echart) {
        _this.QualityRate_echart.resize();
      }
      if (_this.State_echart) {
        _this.State_echart.resize();
      }
      if (_this.Alarm_echart) {
        _this.Alarm_echart.resize();
      }
      _this.getMaxHeight();
    };
    _this.tableColumns = _this.$time.initTableTitle(_this.tableColumns);
  },
  methods: {
    baseEcharts() {
      //初始化图表
      this.baseEacherts_Dynamic("DynamicRate", "OEE"); // 时间稼动率
      this.baseEacherts_Quality("QualityRate", "质量合格率"); // 质量合格率
      this.baseEacherts_State("StateDistribution"); // 设备状态分布
      this.baseEacherts_Alarm("AlarmAnalysis"); // 设备报警分析
    },
    search() {
      this.getDynamicRate(); // 时间稼动率
      this.getStateDistribution(); // 设备状态分布
      this.getAlarmAnalysis(); // 设备报警分析
      this.getProductProgress(); // 生产进度一览
    },
    // 生产进度一览
    getProductProgress() {
      const _this = this;
      let { timestampToTime } = this;
      let params = {
        startdate: timestampToTime(new Date().getTime()),
        enddate: timestampToTime(new Date().getTime()),
      };
      _this.axios
        .request({
          url: "/cnc/PerformanceStatistics/GetReportDetails",
          params,
          method: "get",
        })
        .then((res) => {
          let result = res.data;
          if (result.ret == 1) {
            let data = result.data;
            _this.tableData = [];
            _this.total = 0;
            _this.totalOk = 0;
            _this.totalNok = 0;
            if (data && Array.isArray(data) && data.length) {
              _this.tableData = data.map((v) => {
                v.time = moment(v.time * 1000).format("YYYY-MM-DD HH:mm:ss");
                _this.total += v.okcnt + v.ngcnt;
                _this.totalOk += v.okcnt;
                _this.totalNok += v.ngcnt;
                return v;
              });
            }
            if (_this.total == 0) {
              _this.getQualityRate(0);
            } else {
              let number = (_this.totalOk / _this.total) * 100;
              _this.getQualityRate(number);
            }
          }
        });
    },
    // 时间格式化
    timestampToTime(timestamp) {
      var date = new Date(timestamp);
      var Y = date.getFullYear() + "-";
      var M =
        (date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1) + "-";
      var D = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
      return Y + M + D;
    },
    // 时间稼动率
    getDynamicRate() {
      var data = {
        startTime: moment(this.daterange[0]).format("YYYY-MM-DD HH:mm:ss"),
        endTime: moment(this.daterange[1]).format("YYYY-MM-DD HH:mm:ss"),
        sectionID: this.sectionid,
        toexcel: 0,
      };
      axios
        .request({
          url: "/cnc/ProductSum/EfficiencyAnalysisInfoFive",
          data,
          method: "post",
        })
        .then((res) => {
          let number = 0;
          if (res.data.ret === 1) {
            number = res.data.data.productivity;
          }
          let data = [{ value: number, name: "OEE" }];
          var main_test = echarts.init(document.getElementById("DynamicRate"));
          main_test.setOption({
            series: [
              {
                name: "OEE",
                data: data,
              },
            ],
          });
        });
    },
    // 质量合格率
    getQualityRate(number) {
      let data = [{ value: number, name: "质量合格率" }];
      var main_test = echarts.init(document.getElementById("QualityRate"));
      main_test.setOption({
        series: [
          {
            name: "质量合格率",
            data: data,
          },
        ],
      });
    },
    // 设备状态分布
    getStateDistribution() {
      var data = {
        startTime: moment(this.daterange[0]).format("YYYY-MM-DD HH:mm:ss"),
        endTime: moment(this.daterange[1]).format("YYYY-MM-DD HH:mm:ss"),
        xtype: 0,
        x_id: 0,
        sectionId: this.sectionid,
        sectionIdStr: "",
        toexcel: 0,
      };
      axios
        .request({
          url: "/cnc/ProjectSectionMachine/machineCanvasDataInfo",
          data,
          method: "post",
        })
        .then((res) => {
          let info = res.data.data;
          let dataname = [];
          let datanum = [];
          let datanumber = [];
          if (res.data.ret === 1 && info.length > 0) {
            let datanumber1 = [];
            let datanumber2 = [];
            let datanumber3 = [];
            let datanumber4 = [];
            let datanumber5 = [];
            info.forEach((value) => {
              dataname.push(value.datetime);
              datanum.push(value.data);
            });
            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);
            }
          }
          var main_test = echarts.init(
            document.getElementById("StateDistribution")
          );
          main_test.setOption({
            xAxis: [
              {
                data: dataname,
              },
            ],
            series: [
              {
                name: this.$t("500041"),
                type: "bar",
                barMaxWidth: 70,
                stack: this.$t("500067"),
                data: datanumber.length > 0 ? datanumber[1] : [],
                itemStyle: {
                  normal: {
                    color: "#5cb85c",
                  },
                },
              },
              {
                name: this.$t("500043"),
                type: "bar",
                barMaxWidth: 70,
                stack: this.$t("500067"),
                data: datanumber.length > 0 ? datanumber[3] : [],
                itemStyle: {
                  normal: {
                    color: "#f0ad4e",
                  },
                },
              },
              {
                name: this.$t("500042"),
                type: "bar",
                barMaxWidth: 70,
                stack: this.$t("500067"),
                data: datanumber.length > 0 ? datanumber[2] : [],
                itemStyle: {
                  normal: {
                    color: "#337ab7",
                  },
                },
              },
              {
                name: this.$t("500044"),
                type: "bar",
                barMaxWidth: 70,
                stack: this.$t("500067"),
                data: datanumber.length > 0 ? datanumber[4] : [],
                itemStyle: {
                  normal: {
                    color: "#d9534f",
                  },
                },
              },
              {
                name: this.$t("500040"),
                type: "bar",
                barMaxWidth: 70,
                stack: this.$t("500067"),
                data: datanumber.length > 0 ? datanumber[0] : [],
                itemStyle: {
                  normal: {
                    color: "#585858",
                  },
                },
              },
            ],
          });
        });
    },
    // 设备报警分析
    getAlarmAnalysis() {
      //设备报警分析
      var data = {
        startTime: moment(this.daterange[0]).format("YYYY-MM-DD HH:mm:ss"),
        endTime: moment(this.daterange[1]).format("YYYY-MM-DD HH:mm:ss"),
        sectionID: this.sectionid,
      };
      axios
        .request({
          url: "/cnc/MachineAlarm/GetAlarmDataForAnalysisCl",
          data,
          method: "post",
        })
        .then((res) => {
          let info = res.data.data;
          let xname = [];
          let ydata1 = [];
          let ydata2 = [];
          if (
            res.data.ret === 1 &&
            info != null &&
            info != undefined &&
            info.length > 0
          ) {
            info.forEach((item, index) => {
              xname.push(item.abscissa);
              ydata1.push(item.ordinate);
              ydata2.push(Math.round((item.ordinatecl / 3600) * 100) / 100);
            });
          }
          var main_test = echarts.init(
            document.getElementById("AlarmAnalysis")
          );
          main_test.setOption({
            xAxis: [
              {
                data: xname,
              },
            ],
            series: [
              {
                name: "报警次数",
                type: "bar",
                data: ydata1,
              },
              {
                name: "报警时长",
                type: "line",
                yAxisIndex: 1,
                data: ydata2,
              },
            ],
          });
        });
    },
    baseEacherts_Dynamic(id, title) {
      if (this.DynamicRate_echart) {
        this.DynamicRate_echart.dispose();
      }
      this.DynamicRate_echart = echarts.init(document.getElementById(id));
      let option = {
        tooltip: {
          formatter: "{a} <br/>{c}%",
        },
        toolbox: {
          show: true,
        },
        series: [
          {
            name: title,
            type: "gauge",
            z: 3,
            min: 0,
            max: 100,
            splitNumber: 5,
            radius: "90%",
            axisLine: {
              // 坐标轴线
              lineStyle: {
                // 属性lineStyle控制线条样式
                width: 18,
                color: [
                  [0.2, "#d9534f"],
                  [0.8, "#337ab7"],
                  [1, "#5cb85c"],
                ],
              },
            },
            axisTick: {
              // 坐标轴小标记
              length: 26, // 属性length控制线长
              lineStyle: {
                // 属性lineStyle控制线条样式
                color: "auto",
              },
            },
            splitLine: {
              // 分隔线
              length: 30, // 属性length控制线长
              lineStyle: {
                // 属性lineStyle（详见lineStyle）控制线条样式
                color: "auto",
              },
            },
            title: {
              // 其余属性默认使用全局文本样式，详见TEXTSTYLE
              fontWeight: "bolder",
              fontSize: 18,
              fontStyle: "italic",
            },
            detail: {
              // 其余属性默认使用全局文本样式，详见TEXTSTYLE
              formatter: function (value) {
                if (!value) {
                  value = 0;
                }
                let num = Math.round(value * 100) / 100;
                return num + "%";
              },
              fontWeight: "bolder",
              borderRadius: 3,
              backgroundColor: "#444",
              borderColor: "#aaa",
              shadowBlur: 5,
              shadowColor: "#333",
              shadowOffsetX: 0,
              shadowOffsetY: 3,
              borderWidth: 2,
              textBorderColor: "#000",
              textBorderWidth: 2,
              textShadowBlur: 2,
              textShadowColor: "#fff",
              textShadowOffsetX: 0,
              textShadowOffsetY: 0,
              fontFamily: "Arial",
              width: 85,
              color: "#eee",
              fontSize: 24,
              rich: {},
            },
            data: [],
          },
        ],
      };
      this.DynamicRate_echart.setOption(option);
      setTimeout(() => {
        this.DynamicRate_echart.resize(); // 精髓之所在
      }, 1);
    },
    baseEacherts_Quality(id, title) {
      if (this.QualityRate_echart) {
        this.QualityRate_echart.dispose();
      }
      this.QualityRate_echart = echarts.init(document.getElementById(id));
      let option = {
        tooltip: {
          formatter: "{a} <br/>{c}%",
        },
        toolbox: {
          show: true,
        },
        series: [
          {
            name: title,
            type: "gauge",
            z: 3,
            min: 0,
            max: 100,
            splitNumber: 5,
            radius: "90%",
            axisLine: {
              // 坐标轴线
              lineStyle: {
                // 属性lineStyle控制线条样式
                width: 18,
                color: [
                  [0.2, "#d9534f"],
                  [0.8, "#337ab7"],
                  [1, "#5cb85c"],
                ],
              },
            },
            axisTick: {
              // 坐标轴小标记
              length: 26, // 属性length控制线长
              lineStyle: {
                // 属性lineStyle控制线条样式
                color: "auto",
              },
            },
            splitLine: {
              // 分隔线
              length: 30, // 属性length控制线长
              lineStyle: {
                // 属性lineStyle（详见lineStyle）控制线条样式
                color: "auto",
              },
            },
            title: {
              // 其余属性默认使用全局文本样式，详见TEXTSTYLE
              fontWeight: "bolder",
              fontSize: 18,
              fontStyle: "italic",
            },
            detail: {
              // 其余属性默认使用全局文本样式，详见TEXTSTYLE
              formatter: function (value) {
                if (!value) {
                  value = 0;
                }
                let num = Math.round(value * 100) / 100;
                return num + "%";
              },
              fontWeight: "bolder",
              borderRadius: 3,
              backgroundColor: "#444",
              borderColor: "#aaa",
              shadowBlur: 5,
              shadowColor: "#333",
              shadowOffsetX: 0,
              shadowOffsetY: 3,
              borderWidth: 2,
              textBorderColor: "#000",
              textBorderWidth: 2,
              textShadowBlur: 2,
              textShadowColor: "#fff",
              textShadowOffsetX: 0,
              textShadowOffsetY: 0,
              fontFamily: "Arial",
              width: 85,
              color: "#eee",
              fontSize: 24,
              rich: {},
            },
            data: [],
          },
        ],
      };
      this.QualityRate_echart.setOption(option);
      setTimeout(() => {
        this.QualityRate_echart.resize(); // 精髓之所在
      }, 1);
    },
    baseEacherts_State(id) {
      if (this.State_echart) {
        this.State_echart.dispose();
      }
      this.State_echart = echarts.init(document.getElementById(id));
      var option = {
        title: false,
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "shadow",
          },
        },
        legend: {
          data: [
            this.$t("500041"),
            this.$t("500043"),
            this.$t("500042"),
            this.$t("500044"),
            this.$t("500040"),
          ], // 关机排在最后
        },
        grid: {
          left: "5%",
          right: "4%",
          bottom: "5%",
          containLabel: true,
        },
        xAxis: [
          {
            type: "category",
            data: [],
            axisLabel: {
              rotate: 0,
            },
            axisTick: {
              alignWithLabel: true,
            },
          },
        ],
        yAxis: [
          {
            type: "value",
            // name: "%",
            max: 100,
            min: 0,
            axisLabel: {
              formatter: "{value}%",
            },
          },
        ],
        series: [
          {
            name: this.$t("500041"),
            type: "bar",
            barMaxWidth: 60,
            stack: this.$t("500067"),
            data: [],
            itemStyle: {
              normal: {
                color: "#5cb85c",
              },
            },
          },
          {
            name: this.$t("500043"),
            type: "bar",
            barMaxWidth: 60,
            stack: this.$t("500067"),
            data: [],
            itemStyle: {
              normal: {
                color: "#f0ad4e",
              },
            },
          },
          {
            name: this.$t("500042"),
            type: "bar",
            barMaxWidth: 60,
            stack: this.$t("500067"),
            data: [],
            itemStyle: {
              normal: {
                color: "#337ab7",
              },
            },
          },
          {
            name: this.$t("500044"),
            type: "bar",
            barMaxWidth: 60,
            stack: this.$t("500067"),
            data: [],
            itemStyle: {
              normal: {
                color: "#d9534f",
              },
            },
          },
          {
            name: this.$t("500040"),
            type: "bar",
            barMaxWidth: 60,
            stack: this.$t("500067"),
            data: [],
            itemStyle: {
              normal: {
                color: "#585858",
              },
            },
          },
        ],
      };
      this.State_echart.setOption(option);
      setTimeout(() => {
        this.State_echart.resize(); // 精髓之所在
      }, 1);
    },
    baseEacherts_Alarm(id) {
      if (this.Alarm_echart) {
        this.Alarm_echart.dispose();
      }
      this.Alarm_echart = echarts.init(document.getElementById(id));
      let option = {
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "cross",
            crossStyle: {
              color: "#999",
            },
          },
        },
        toolbox: {},
        color: ["rgba(97, 165, 232, 1)", "rgba(126,207,81,1)"],
        legend: {
          data: ["报警次数", "报警时长"],
        },
        grid: {
          left: "5%",
          right: "5%",
          bottom: "5%",
          containLabel: true,
        },
        xAxis: [
          {
            type: "category",
            data: [],
            axisLabel: {
              rotate: 0,
            },
            axisPointer: {
              type: "shadow",
            },
          },
        ],
        yAxis: [
          {
            type: "value",
            name: "报警次数",
            min: 0,
            minInterval: 1,
            max: function (value) {
              return value.max;
            },
            axisLabel: {
              formatter: "{value} ",
            },
            splitLine: {
              show: false,
            },
            nameGap: 12,
            offset: -14,
          },
          {
            type: "value",
            name: "报警时长",
            min: 0,
            max: function (value) {
              return value.max;
            },
            axisLabel: {
              formatter: "{value}h",
            },
            splitLine: {
              show: false,
            },
            nameGap: 12,
            offset: -14,
          },
        ],
        series: [
          {
            name: "报警次数",
            type: "bar",
            data: [],
          },
          {
            name: "报警时长",
            type: "line",
            yAxisIndex: 1,
            data: [],
          },
        ],
      };
      this.Alarm_echart.setOption(option);
      setTimeout(() => {
        this.Alarm_echart.resize(); // 精髓之所在
      }, 1);
    },
    // 动态计算表格最大高度
    getMaxHeight() {
      const _this = this;
      _this.maxHeight = document.body.clientHeight - 300;
    },
  },
  beforeDestroy() {
    // 退出组件时手动清除 Echarts 实例
    const _this = this;
    if (_this.DynamicRate_echart) {
      _this.DynamicRate_echart.dispose();
      _this.DynamicRate_echart = null;
    }
    if (_this.QualityRate_echart) {
      _this.QualityRate_echart.dispose();
      _this.QualityRate_echart = null;
    }
    if (_this.State_echart) {
      _this.State_echart.dispose();
      _this.State_echart = null;
    }
    if (_this.Alarm_echart) {
      _this.Alarm_echart.dispose();
      _this.Alarm_echart = null;
    }
  },
};
</script>
<style lang="less">
.item {
  .middle {
    .baojunranggaide {
      tr,
      td {
        height: 40px !important;
      }
      .ivu-table-overflowX::-webkit-scrollbar {
        display: none;
      }
      .ivu-table-overflowY::-webkit-scrollbar {
        display: none;
      }
    }
  }
}
</style>
<style lang="less" scoped>
.divborder {
  margin-top: 0;
  margin-bottom: 0;
  border-radius: 8px;
  .item {
    width: 100%;
    .left {
      width: 25%;
      height: 80vh;
      float: left;
    }
    .middle {
      width: 50%;
      height: 80vh;
      padding: 0px 10px;
      float: left;
      .m_content {
        width: 100%;
        height: 100%;
        .m_div {
          width: 100%;
          height: calc(~"100% - 30px");
          border: 1px solid #ddd;
          .top {
            .textcontent {
              width: 33.3%;
              height: 100px;
              float: left;
              div {
                width: 100%;
                height: 50px;
                line-height: 50px;
                text-align: center;
                font-size: 36px;
                font-weight: bold;
              }
              div:first-child {
                font-size: 20px;
              }
            }
          }
          .top::after {
            display: block;
            content: "";
            clear: both;
          }
          .down {
            padding: 8px;
            // height: calc(~"100% - 130px");
          }
        }
      }
    }
    .right {
      width: 25%;
      height: 80vh;
      float: left;
    }
    .title {
      width: 100%;
      height: 30px;
      font-size: 16px;
      line-height: 30px;
      background: rgba(170, 170, 170, 1);
      color: #fff;
      padding-left: 12px;
    }
    .echartdiv {
      width: 100%;
      height: 35vh;
      border: 1px solid #ddd;
      margin-bottom: 16px;
      position: relative;
      .echartitem {
        position: relative;
        width: 100%;
        height: 35vh;
      }
    }
  }
  .item::after {
    display: block;
    content: "";
    clear: both;
  }
}
.echart {
  width: 100%;
  height: 35vh;
}
</style>