<template>
  <div>
    <div class="divborder newSearchDiv" style="margin: 0px">
      <div class="filter">
        <label>{{ $t("900879") }}：</label>
        <Select
          v-model="lineid"
          label-in-value
          clearable
          class="searchSelect"
          @on-change="lingchange"
        >
          <Option v-for="item in lines" :value="item.id" :key="item.id">{{
            item.title
          }}</Option>
        </Select>
      </div>
      <div class="filter">
        <label>{{ $t("1026") }}：</label>
        <Select
          v-model="sectionid"
          label-in-value
          clearable
          class="searchSelect"
        >
          <Option v-for="item in sections" :value="item.id" :key="item.id">{{
            item.title
          }}</Option>
        </Select>
      </div>
      <div class="searchBtn">
        <Button
          type="primary"
          class="sixWord"
          icon="md-color-filter"
          @click="search()"
          >生产执行报工</Button
        >
      </div>
    </div>
    <div
      class="divborder newEchartStyle"
      style="overflow: initial; min-height: 520px"
    >
      <div class="reportleft" v-show="oderreport">
        <Input
          type="text"
          v-model="orderno"
          placeholder="请扫描工令单"
          class="searchInput middleWidth"
          @input="getOrderInfo()"
        />
        <div class="reportinfo">
          <p>
            <label>产品编号：</label><span>{{ productcode }}</span>
          </p>
          <p>
            <label>当前工位：</label><span>{{ routename }}</span>
          </p>
          <p>
            <label>产品名称：</label><span>{{ productname }}</span>
          </p>
          <p>
            <label>计划数量：</label><span>{{ plannum }}</span>
          </p>
          <p>
            <label>已报工数量：</label><span>{{ number }}</span>
          </p>
          <p>
            <label>合格数量：</label><span>{{ oknum }}</span>
          </p>
          <p>
            <label>不合格数量：</label><span>{{ noknum }}</span>
          </p>
          <p>
            <label>计划结束时间：</label><span>{{ plantime }}</span>
          </p>
          <p>
            <label>工令号：</label><span>{{ workorderno }}</span>
          </p>
          <p>
            <label>操作人：</label><span>{{ operator }}</span>
          </p>
        </div>
        <div>
          <!-- <Button v-show="showPgbtn" type="primary" @click="loadProgram" style="margin:0px 10px 0px 40px;">程序调用</Button> -->
          <Button
            v-show="showRebtn"
            type="primary"
            @click="addreport"
            style="margin: 0px 10px 0px 120px"
            >报工</Button
          >
        </div>
      </div>
      <div class="reportright" v-show="echartshow">
        <!-- 切片图 -->
        <div class="slice-map" ref="slicemap"></div>
        <!-- 切片下的图 -->
        <div>
          <!-- 状态图 -->
          <div class="statusTable">
            <Table :columns="statuscolumns1" :data="statusdata1"></Table>
          </div>
          <!-- 仪表图 -->
          <div class="oeeitem">
            <div class="oeeid" id="oeeid_one"></div>
            <div class="oeeid" id="oeeid_two"></div>
          </div>
        </div>
      </div>
    </div>

    <!-- 报工弹窗 -->
    <Modal
      class="newModalClass"
      :title="$t('1002')"
      v-model="lookModal"
      :styles="{ width: '550px' }"
    >
      <div class="modal_body" style="padding-right: 40px">
        <div class="filter">
          <label><i>*</i>时间范围：</label>
          <DatePicker
            type="datetimerange"
            :value="dateTime"
            class="searchInput MaxWidth"
            @on-change="selectdate"
          ></DatePicker>
        </div>
        <div class="filter">
          <label><i>*</i>休息时间：</label>
          <InputNumber
            v-model="addrestminutes"
            class="searchInput"
            type="number"
            :min="0"
          />
          <span>(分钟)</span>
        </div>
        <!-- <div class="filter">
              <label>生产程序号：</label>
              <Input v-if="ptype" v-model="addprogramno" class="searchInput" type="text"/>
              <Select v-else v-model="addprogramno" clearable class="searchSelect">
                <Option v-for="(item,key) in programList" :value="item.program_number" :key="key">{{ item.program_number }}</Option>
              </Select>
              <Button type="primary" style="margin-left:10px;" @click="getPgno()">查询程序号</Button>
          </div> -->
        <div class="filter">
          <label><i>*</i>工序：</label>
          <Select v-model="addroutename" clearable class="searchSelect">
            <Option
              v-for="(item, key) in routelist"
              :value="item.id"
              :key="key"
              >{{ item.name }}</Option
            >
          </Select>
        </div>
        <!-- <div class="filter">
              <label>报工数量：</label>
              <Input v-model="addoutput" class="searchInput" type="number" disabled/>
          </div> -->
        <div class="filter">
          <label><i>*</i>报工人：</label>
          <Select v-model="addreportname" clearable class="searchSelect">
            <Option
              v-for="(item, key) in userlist"
              :value="item.id"
              :key="key"
              >{{ item.text }}</Option
            >
          </Select>
        </div>
        <div class="filter">
          <label><i>*</i>OK产量：</label>
          <InputNumber
            v-model="addoknum"
            class="searchInput"
            type="number"
            :min="0"
          />
        </div>
        <div class="filter">
          <label><i>*</i>NOK产量：</label>
          <InputNumber
            v-model="addnoknum"
            class="searchInput"
            type="number"
            :min="0"
          />
        </div>
      </div>
      <div slot="footer">
        <Button
          type="text"
          size="large"
          @click="lookModal = false"
          v-text="$t('1033')"
          >取消</Button
        >
        <Button
          type="primary"
          size="large"
          @click="addreportPost"
          v-text="$t('1011')"
          >确定</Button
        >
      </div>
    </Modal>

    <!-- 上传程序 -->
    <Modal v-model="updatemodal" :styles="{ top: '40px', width: '900px' }">
      <div class="filter" style="line-height: 40px">
        <label style="width: 120px">产品名称/编号：</label>
        <Input v-model="name1" @on-change="getProgram" style="width: 200px" />
      </div>
      <div>
        <Table
          :columns="columns"
          :data="tableData"
          @on-row-click="onExpand"
          ref="tableExpand"
          @on-current-change="handleRowChange"
          highlight-row
          height="600"
        ></Table>
      </div>
      <p style="margin-top: 10px">{{ tipsmsg }}</p>
      <div slot="footer">
        <Button type="text" @click="updatemodal = false">取消</Button>
        <Button type="primary" @click="updateProgram()">确认</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import moment from "moment";
import echarts from "echarts";
import axios from "@/libs/api.request";
import { mapState } from "vuex";
export default {
  data() {
    return {
      productcode: "",
      productname: "",
      plannum: "",
      routename: "",
      number: "",
      oknum: "",
      noknum: "",
      plantime: "",
      workorderno: "",
      operator: "",
      lines: [],
      lineid: "0",
      sections: [],
      sectionid: "0",
      orderno: "", // 工令单号
      oderreport: false, // 左边工令单信息
      showPgbtn: false, // 程序按钮
      showRebtn: false, // 报工按钮
      echartshow: false, // 右边图显示
      dateTime: "",
      lookModal: false, // 报工弹窗
      machine_id: 0, // 设备id
      product_id: 0, // 产品id
      statusdata1: [],
      statuscolumns1: [
        {
          title: "状态",
          key: "status",
        },
        {
          title: "累计时长(小时)",
          key: "timenum",
        },
      ],
      programList: [], // 程序员
      addprogramno: "", // 程序号
      addrestminutes: 0, // 休息时间
      ptype: false,
      addoutput: "", // 报工数量
      routelist: [], // 工序列表
      addroutename: "", // 工序
      userlist: [], // 报工人
      addreportname: "", // 报工人
      addoknum: 0,
      addnoknum: 0,

      updatemodal: false, // 上传程序
      name1: "", // 程序号
      columns: [
        {
          type: "expand",
          width: 40,
          render: (h, params) => {
            if (params.row.id === this.detailobj.id) {
              var newArr = [];
              if (
                this.content !== null &&
                this.content !== undefined &&
                this.content !== ""
              ) {
                var infoArray = this.content.split("\n");
                infoArray.forEach((ele, i) => {
                  newArr.push(
                    h("p", [
                      h(
                        "span",
                        {
                          style: {
                            background: "#ddd",
                            display: "inline-block",
                            "text-align": "center",
                            padding: "0px 5px",
                            "min-width": "30px",
                          },
                        },
                        i + 1
                      ),
                      h("span", ele),
                    ])
                  );
                });
              }
              return h(
                "div",
                {
                  style: {
                    border: "1px solid black",
                    overflow: "auto",
                    width: "99%",
                    height: "200px",
                  },
                },
                [
                  h(
                    "div",
                    {
                      style: {
                        "white-space": "nowrap",
                        "max-width": "1000px",
                      },
                    },
                    newArr
                  ),
                ]
              );
            }
          },
        },
        {
          title: this.$t("1008"),
          key: "order",
          render: (h, params) => {
            return h(
              "span",
              params.index + (this.page1 - 1) * this.pagesize1 + 1
            );
          },
          width: 70,
          align: "center",
        },
        {
          title: "程序号",
          key: "program_code",
          align: "center",
        },
        {
          title: "产品名称",
          key: "productname",
          align: "center",
        },
        {
          title: "图纸号",
          key: "productcode",
          align: "center",
        },
        {
          title: "大小",
          key: "file_size",
          align: "center",
        },
        {
          title: "创建人",
          key: "createname",
          align: "center",
        },
        {
          title: "审核人",
          key: "checkname",
          align: "center",
        },
        {
          title: "创建备注",
          key: "create_remark",
          align: "center",
        },
      ],
      tableData: [],
      tipsmsg: "",
    };
  },
  computed: {
    ...mapState(["user"]),
  },
  created() {
    this.inilines();
  },
  methods: {
    selectdate(e) {
      this.dateTime = [e[0], e[1]];
      let dtStart = e[0];
      let dtEnd = e[1];
      let last_str = dtEnd.split(" ")[1];
      if (last_str === "00:00:00") {
        dtEnd = moment(dtEnd).format("YYYY-MM-DD") + " 23:59:59";
        this.dateTime = [dtStart, dtEnd];
      }
    },
    search() {
      if (this.lineid === "0" || this.lineid === undefined) {
        this.$Message.error(this.$t("800082"));
        return false;
      }
      if (this.sectionid === "0" || this.sectionid === undefined) {
        this.$Message.error(this.$t("1052"));
        return false;
      }
      var params = {
        id: this.sectionid,
        // id:4562
      };
      axios
        .request({
          url: "/config/Machine/GetmachineidBySection",
          params,
          method: "get",
        })
        .then((res) => {
          if (res.data.ret == 1) {
            /** ***工令单信息*******/
            this.showPgbtn = false;
            this.showRebtn = false;
            this.oderreport = true;
            this.orderno = "";
            this.clearInfo();
            /** ****切片******/
            this.echartshow = true;
            this.getReadyData(this.sectionid);
          } else {
            this.$Message.error(this.$t(res.data.msg));
          }
        });
    },
    loadProgram() {
      this.name1 = "";
      this.getProgram();
      this.updatemodal = true;
    },
    // 获取弹框内程序列表
    getProgram() {
      let data = {
        product: this.name1 ? this.name1 : this.productname,
      };
      this.request("/dnc/DncUpDown/getPrograms", data, "get").then((res) => {
        if (res.data.ret == 1) {
          this.renderModal(res.data.data);
        }
      });
    },
    renderModal(arr) {
      let a = [];
      arr.forEach((item, index) => {
        a.push({
          id: item.id,
          productcode: item.productcode,
          productname: item.productname,
          productid: item.productid,
          createname: item.createname,
          create_remark: item.create_remark,
          createmid: item.createmid,
          file_size: item.file_size,
          file_name: item.file_name,
          file_url: item.file_url,
          checkname: item.checkname,
          checkmid: item.checkmid,
          projectid: item.projectid,
          program_code: item.program_code,
          _expanded: false,
          _highlight: false,
        });
      });
      this.tableData = a;
    },
    onExpand(row, index) {
      this.tableData.forEach((item, i) => {
        // 这个循环是为了每次只能展开一个，其他自动收起，不需要可以去掉
        i !== index ? (this.tableData[i]._expanded = false) : "";
        i !== index ? (this.tableData[i]._highlight = false) : "";
      });
      this.tableData[index]._expanded = !this.tableData[index]._expanded;
      this.tableData[index]._highlight = true;

      this.tableData.sort();
    },
    handleRowChange(currentRow, oldCurrentRow) {
      this.detailobj = currentRow;
      this.getText(currentRow.file_url);
    },
    // 上传提交
    updateProgram() {
      if (
        this.detailobj == "" ||
        this.detailobj == undefined ||
        this.detailobj == null
      ) {
        this.$Message.error("请选择程序");
        return false;
      }

      let code = this.code;
      // debugger
      var data = {
        programcode: this.detailobj.program_code,
      };
      let url = "/dnc/DncUpDown/checkprograms";

      this.request(url, data, "get").then((res) => {
        if (res.data.ret == 1) {
          var msg = alert(this.$t(700134));
          if (msg) {
            this.uploadProgramPost();
          }
        } else {
          this.uploadProgramPost();
        }
      });
    },
    uploadProgramPost() {
      var data = {
        sectionid: this.sectionid,
        programid: this.detailobj.id,
      };
      this.request("/dnc/DncUpDown/uploadProgramPost", data, "post").then(
        (res) => {
          if (res.data.ret == 1) {
            this.updatemodal = false;
            this.$Message.success("上传成功");
          } else {
            this.$Message.error(this.$t(res.data.msg));
          }
        }
      );
    },
    getText(url) {
      // if (this.detailobj.id) {
      let data = {
        file_url: url,
      };

      this.request("/dnc/DncPgCreate/getContent", data, "get").then((res) => {
        if (res.data.ret == 1) {
          this.content = res.data.data.content;
        }
      });
    },
    addreport() {
      // 报工
      this.lookModal = true;
      this.init_route(); // 获取工序
      this.init_user(); // 获取报工人
    },
    addreportPost() {
      // 组装数据
      var data = {
        time: this.dateTime.join(" - "), // 开始时间
        output: this.addoutput, // 产量
        noknumber: this.addnoknum, // nok产量
        actualoutput: this.addoknum, // ok产量
        workercode: this.addreportname, // 报工人
        code: this.orderno, // 工单号
        programnumber: this.addprogramno, // 程序号
        machineId: this.machine_id,
        route_name: this.addroutename,
      };
      if (
        this.dateTime === "" ||
        this.addoknum === 0 ||
        this.addoknum === "" ||
        this.addnoknum === "" ||
        this.addreportname == "" ||
        this.addroutename === ""
      ) {
        this.$Message.error(this.$t("9000136"));
        return false;
      }

      var total = parseInt(this.addoknum) + parseInt(this.addnoknum);
      this.doReportPost(data);
      // 如果报工数量为空，提示
      // if(this.addoutput === "")
      // {
      //     this.doReportPost(data);
      // }
      // else
      // {
      //     if(total > this.addoutput)
      //     {
      //         if(confirm('ok产量与nok产量之和大于报工数量，是否继续提交'))
      //         {
      //             this.doReportPost(data);
      //         }
      //     }
      //     else
      //     {
      //         this.doReportPost(data);
      //     }
      // }
    },
    doReportPost(data) {
      axios
        .request({
          url: "/cnc/ProductReport/AddProducereport",
          data,
          method: "post",
        })
        .then((res) => {
          if (res.data.ret == 1) {
            this.lookModal = false;
            this.oknum = this.oknum + this.addoknum;
            this.noknum = this.noknum + this.addnoknum;
            this.number = this.oknum + this.noknum;
          } else {
            this.$Message.error(this.$t(res.data.msg));
          }
        });
    },
    init_user() {
      axios
        .request({
          url: "/cnc/ProductReport/GetWorkCode",
          method: "get",
        })
        .then((res) => {
          if (res.data.ret == 1) {
            this.userlist = res.data.data;
          }
        });
    },
    init_route() {
      var params = {
        productId: this.product_id,
      };
      axios
        .request({
          url: "/config/ProductRoute/GetRoutesByProduct",
          params,
          method: "get",
        })
        .then((res) => {
          if (res.data.ret == 1) {
            this.routelist = res.data.data;
          }
        });
    },
    getOrderInfo() {
      // 获取工单信息
      if (this.orderno == "") {
        return false;
      }
      // 清空数据
      this.clearInfo();

      let params = {
        sectionId: this.sectionid,
        orderNumber: this.orderno,
      };
      axios
        .request({
          url: "/cnc/WorkOrder/GetWorkOrderDetail",
          params,
          method: "get",
        })
        .then((res) => {
          if (res.data.ret == 1 && res.data.data != 0) {
            this.showRebtn = true;
            let info = res.data.data;
            this.machine_id = info.machineId;
            this.product_id = info.product_id;
            this.productcode = info.product_code;
            this.productname = info.product_name;
            this.plannum = info.quantity;
            this.routename = info.sectionName;
            this.number = info.producted_number;
            this.oknum = info.ok_number;
            this.noknum = info.nok_number;
            this.plantime = moment(info.delivery_time * 1000).format(
              "YYYY-MM-DD"
            );
            this.workorderno = this.orderno;
            this.operator = this.user.userName;
            // 程序调用按钮
            this.getTheBtnshow();
          }
        });
    },
    getPgno() {
      if (this.machine_id === 0 && this.machine_id === undefined) {
        this.$Message.error("请选择设备");
        return false;
      }
      if (this.dateTime === "") {
        this.$Message.error("请选择时间范围");
        return false;
      }

      var params = {
        machineid: this.machine_id,
        startTime: this.dateTime[0],
        endTime: this.dateTime[1],
      };
      axios
        .request({
          url: "/cnc/ProductReport/Getprogramlist",
          params,
          method: "get",
        })
        .then((res) => {
          this.programno = "";
          if (res.data.ret == 1) {
            this.programList = res.data.data.program_number;
            if (
              this.programList != "" &&
              this.programList != undefined &&
              this.programList.length > 0
            ) {
              this.ptype = false;
            } else {
              this.output = "";
              this.ptype = true;
              this.$Message.error("没有获取到程序号，可手动输入");
            }
          } else {
            this.$Message.error(this.$t(res.data.msg));
          }
        });
    },
    getTheBtnshow() {
      axios
        .request({
          url: "/config/Project/GetModuleByName?module=dnc",
          method: "get",
        })
        .then((res) => {
          if (res.data.ret == 1 && res.data != 0) {
            this.showPgbtn = true;
          }
        });
    },
    clearInfo() {
      this.machine_id = 0;
      this.product_id = 0;
      this.productcode = "";
      this.productname = "";
      this.plannum = "";
      this.routename = "";
      this.number = "";
      this.oknum = "";
      this.noknum = "";
      this.plantime = "";
    },
    inilines() {
      axios
        .request({
          url: "/config/Position/GetLine",
          method: "get",
        })
        .then((res) => {
          this.lines = res.data.data;
          this.prelines = res.data.data;
        });
    },
    lingchange() {
      var params = {
        line: this.lineid,
      };
      axios
        .request({
          url: "/config/Position/getstation",
          params,
          method: "get",
        })
        .then((res) => {
          this.sections = [];
          if (
            res.data.ret === 1 &&
            res.data.data != null &&
            res.data.data.length > 0
          ) {
            this.sections = res.data.data;
          }
        });
    },
    request(url, data, type) {
      if (type == "get") {
        return this.axios
          .request({
            url: url,
            params: data,
            method: type,
          })
          .then((res) => {
            return res;
          })
          .catch((error) => error);
      } else {
        return this.axios
          .request({
            url: url,
            data,
            method: type,
          })
          .then((res) => {
            return res;
          })
          .catch((error) => error);
      }
    },
    getReadyData(section_id) {
      let dt = new Date();
      var date = this.$time.getDate(0, 1);

      var timeSection =
        date +
        " 00:00:00 - " +
        date +
        " " +
        dt.getHours() +
        ":" +
        dt.getMinutes() +
        ":00";
      let params = {
        sectionId: section_id, // this.sectionid
        timeSection: timeSection,
      };
      axios
        .request({
          url: "/cnc/ProjectSectionMachine/MachineCanvasPrograms",
          params,
          method: "get",
        })
        .then((res) => {
          if (res.data.canvas && res.data.canvas.length > 0) {
            // 新切片
            this.GetCanvasData(res.data.canvas, res.data.pareto);
            // 获取oee
            this.getOee();
            /** ******运行时长********/
            var data = res.data.pareto[0].listShutdownHoldTime;
            var shutdown = 0;
            var running = 0;
            var debugging = 0;
            var free = 0;
            var fault = 0;
            data.forEach((item, index) => {
              if (item.factor == "shutdown") {
                shutdown = (item.timeSpan / 3600).toFixed(2);
              } else if (item.factor == "running") {
                running = (item.timeSpan / 3600).toFixed(2);
              } else if (item.factor == "debugging") {
                debugging = (item.timeSpan / 3600).toFixed(2);
              } else if (item.factor == "free") {
                free = (item.timeSpan / 3600).toFixed(2);
              } else if (item.factor == "fault") {
                fault = (item.timeSpan / 3600).toFixed(2);
              }
            });
            this.statusdata1 = [
              {
                status: "关机",
                timenum: shutdown,
              },
              {
                status: "运行",
                timenum: running,
              },
              {
                status: "调试",
                timenum: debugging,
              },
              {
                status: "空闲",
                timenum: free,
              },
              {
                status: "报警",
                timenum: fault,
              },
            ];
          } else {
            this.$Message.error(this.$t("1000"));
          }
        });
    },
    getOee() {
      let params = {
        sectionId: this.sectionid,
      };
      axios
        .request({
          url: "/cnc/WorkOrder/GetMachineReportOee",
          params,
          method: "get",
        })
        .then((res) => {
          var arr1 = {
            title: "综合OEE",
            name: "OEE",
            value: res.data.data.oee,
            id: "oeeid_one",
          };
          this.getOEEcharts(arr1);
          var arr2 = {
            title: "质量合格率",
            name: "质量合格率",
            value: res.data.data.quantityRate,
            id: "oeeid_two",
          };
          this.getOEEcharts(arr2);
        });
    },
    getOEEcharts(data) {
      var myChartone = echarts.init(document.getElementById(data.id));
      var option = {
        title: {
          text: data.title,
          left: "center",
          textStyle: {
            fontSize: 18,
          },
          subtextStyle: {
            fontSize: 14,
          },
        },
        tooltip: {
          formatter: "{a} <br/>{b} : {c}%",
        },
        toolbox: {
          // feature: {
          //     restore: {},
          //     saveAsImage: {}
          // }
        },
        series: [
          {
            name: data.title,
            type: "gauge",
            detail: { formatter: "{value}%" },
            data: [{ value: data.value }],
            axisLine: {
              // 坐标轴线
              lineStyle: {
                // 属性lineStyle控制线条样式
                color: [
                  [0.2, "#c23531"],
                  [0.8, "#63869e"],
                  [1, "#91c7ae"],
                ],
              },
            },
          },
        ],
      };

      // setInterval(function () {
      //     option.series[0].data[0].value = (Math.random() * 100).toFixed(2) - 0;
      //     myChart.setOption(option, true);
      // },2000);
      myChartone.setOption(option);
    },
    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);
      // $(".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;
        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);
            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) => {
            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
        ) {
          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
    ) {
      // var width = document.getElementsByClassName('echart-div-list').width
      var html = "";
      html +=
        '<div id="new_' +
        canvasDataKey +
        '" style="width: 100%;border: #83baff 0px solid;height: 180px;"></div>';
      let dom = this.$refs.slicemap;
      dom.innerHTML = html;

      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 = "";
            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: 6,
          axisLabel: {
            margin: 5,
            interval: 0,
            rotate: 0,
            showMaxLabel: false,
            formatter: (value) => {
              return this.fmtDate(value);
            },
          },
          splitLine: {
            show: true,
          },
          min: "dataMin",
          max: "dataMax",
        },

        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 (params) {
                  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);
      }
    },
    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;
    },
  },
};
</script>

<style lang="less" scoped>
.reportleft {
  width: 350px;
  height: 500px;
  background-color: #ddd;
  display: inline-block;
  padding: 10px;
  float: left;
  .reportinfo {
    padding: 10px;
    p {
      margin: 10px;
      label {
        width: 100px;
        text-align: right;
        display: inline-block;
      }
    }
  }
}
.reportright {
  display: inline-block;
  float: left;
  width: calc(~"100% - 350px");
  padding: 0px 10px;
  .slice-map {
    height: 200px;
    padding: 30px;
  }
  .statusTable {
    width: 30%;
    height: 300px;
    float: left;
  }
  .oeeitem {
    width: 70%;
    float: left;
    .oeeid {
      width: 50%;
      height: 300px;
      float: left;
    }
  }
}
</style>
