<template>
  <div class="testdiv">
    <!-- 看板标题 -->
    <div class="top_title">
      {{passtitle}}动态看板
      <img :src="imgLogo" alt class="logo" v-on:click="back" />
      <div class="times_bg">{{nowTime}}</div>
      <!-- <Icon class="backBtn" type="md-arrow-round-back" size="40" v-on:click="back" /> -->
      <div class="IconSetting">
        <img src="../../../static/images/setting.svg" alt @click="setting()" />
      </div>
    </div>
    <!-- 弹出框 -->
    <Modal
      class="settingmodal"
      title
      v-model="settingmodal"
      :styles="{position:'fixed',top:'60px',right:'35px',width:'450px'}"
    >
      <div class="modal_body" style="width:430px!important;padding:0 0px;">
        <div class="out_row">
          <label>选择展示通道:</label>
          <Select
            v-model="topassid"
            @on-change="changeSection()"
            label-in-value
            style="width:200px;margin-left:9px;"
          >
            <Option v-for="(item,key) in passList" :value="item.id" :key="key">{{item.title}}</Option>
          </Select>
        </div>
        <div class="out_row">
          <label>查询其他日期:</label>
          <DatePicker
            class="publicinput"
            type="date"
            v-model="datetime"
            placeholder
            style="width:200px;margin-left:9px;"
          ></DatePicker>
        </div>
        <div class="out_row">
          <label>通道员工总数:</label>
          <input v-model="peoplenum" class="publicinput" type="number" />
        </div>
        <div class="out_row">
          <label>班次信息设置:</label>
          <Select v-model="shifttype" label-in-value style="width:200px;margin-left:9px;">
            <Option :value="8">8小时制</Option>
            <Option :value="12">12小时制</Option>
          </Select>
        </div>
        <div class="out_row">
          <label>班次开始时间:</label>
          <Select v-model="shiftid" label-in-value style="width:200px;margin-left:9px;">
            <Option
              v-for="(item,key) in shiftList"
              :value="item.name"
              :key="key"
            >{{ item.name + ":00" }}</Option>
          </Select>
        </div>
        <div class="out_row">
          <label>当班计划产量:</label>
          <input v-model="plannum" class="publicinput" type="number" />
        </div>
      </div>
      <div slot="footer">
        <Button type="text" size="large" @click="settingmodal = false">{{$t("1033")}}</Button>
        <Button type="primary" size="large" @click="search()">{{$t("900312")}}</Button>
        <Button type="primary" size="large" @click="settingadd()">{{$t("960445")}}</Button>
        <Button type="primary" size="large" v-on:click="back">退出看板</Button>
      </div>
    </Modal>
    <!-- 看板标题 end -->
    <!-- 看板内容 -->
    <div class="container">
      <!-- 左边看板 -->
      <div class="formBox_left">
        <!-- 各通道OEE分布 -->
        <div class="formBox compre_analysis">
          <div class="form_title">每小时产出看板</div>
          <div :class="hourlength>8?'formMain_long':'formMain_longt'">
            <ul class="tableTitle">
              <li>时间</li>
              <li>状态</li>
              <li>产品</li>
              <li>目标</li>
              <li>生产</li>
              <li>差额</li>
              <!-- <li>人数</li>
                  <li>报废</li>
              <li>返工</li>-->
            </ul>
            <div class="table">
              <ul class="timesBox">
                <li v-for="(item,index) in produceHourList" :key="index">
                  <ul class="table_right">
                    <!-- <li><div>{{item.Hour}}</div></li> -->
                    <li>
                      <span>{{item.hour}}:00</span>
                    </li>
                  </ul>
                </li>
              </ul>
              <div class="table_left" :style="{'max-height':maxheight+'px','overflow':'hidden'}">
                <div
                  class="state"
                  v-for="(item,idx) in stateList"
                  :key="idx"
                  :style="{'height':'100%','width':'100%'}"
                >
                  <div :style="{'height':item.stateHeight+'px','background-color':item.color}"></div>
                  <!-- <div  :style="{'height':item.stateHeight+'px;','background':item.color}"></div> -->
                  <!-- <div class="stateGreen" v-if="item.state === 0" :style="{'height':item.stateHeight+'px'}"></div> -->
                  <!-- <div class="stateYellow" v-else-if="item.state === 1" :style="{'height':item.stateHeight+'px'}"></div>
                  <div class="stateGray" v-else-if="item.state === 2" :style="{'height':item.stateHeight+'px'}"></div>-->
                </div>
              </div>
              <ul class="tableBox">
                <li v-if="produceList.length == 0"></li>
                <li v-for="(item,index) in produceHourList" :key="index" v-else>
                  <ul class="table_right">
                    <li>
                      <div>{{item.product}}</div>
                    </li>
                    <li>
                      <div>{{item.target}}</div>
                    </li>
                    <li>
                      <div>{{item.produce}}</div>
                    </li>
                    <li
                      @click="show_andon(item.hourTimeStamp)"
                      :class="item.balance>0?'greenTxt':(item.balance<0?'redTxt':'')"
                    >
                      <div>{{item.balance}}</div>
                    </li>
                    <!-- <li><div>{{item.produceNum}}</div></li>
                            <li><div>{{item.produceScrap}}</div></li>
                    <li><div>{{item.produceRework}}</div></li>-->
                  </ul>
                </li>
              </ul>
            </div>
            <div class="totalBox" :style="{'margin-bottom':'20px'}" v-show="totaldiv">
              <!-- <div class="total_left">合计</div>
                <ul class="total_right">
                  <li>{{totalGoal}}</li>
                  <li>{{totalProduce}}</li>
                  <li :class="totalDiffer>0?'greenTxt':(totalDiffer<0?'redTxt':'')">{{totalDiffer}}</li>
              </ul>-->
              <ul class="tablebottom">
                <li>
                  <div>计划产量</div>
                </li>
                <li>
                  <div>报废</div>
                </li>
                <li>
                  <div :style="{'background':'red'}">{{Scrapnum}}</div>
                </li>
                <li>
                  <div>目标值</div>
                </li>
                <li>
                  <div>实际值</div>
                </li>
                <li>
                  <div>差额</div>
                </li>
              </ul>
              <ul class="tablebottom">
                <li>
                  <div>{{plannum}}</div>
                </li>
                <li>
                  <div>返工</div>
                </li>
                <li>
                  <div :style="{'background':'orange'}">{{Reworknum}}</div>
                </li>
                <li>
                  <div>{{targetvalue}}</div>
                </li>
                <li>
                  <div>{{actualvalue}}</div>
                </li>
                <li>
                  <div :style="{'background':Differencevalue<0?'red':'green'}">{{Differencevalue}}</div>
                </li>
              </ul>
            </div>
          </div>
        </div>

        <!-- oee损失详情 -->
        <Modal
          v-model="detailmodal"
          :closable="false"
          footer-hide
          :styles="{top: '200px',width:'800px'}"
        >
          <div class="modal_body dashTable" style="width:800px!important;margin:-16px;">
            <Table border :data="tableData2" :columns="tableColumns2" max-height="250"></Table>
          </div>
        </Modal>

        <!-- oee损失详情 -->
        <Modal
          v-model="detailtwomodal"
          :closable="false"
          footer-hide
          :styles="{top: '300px',width:'1000px'}"
        >
          <div class="modal_body dashTable" style="width:1000px!important;margin:-16px;">
            <Table
              highlight-row
              border
              :data="tableData3"
              :columns="tableColumns3"
              max-height="250"
            ></Table>
            <Table
              v-show="showTable"
              highlight-row
              border
              :data="tableData4"
              :columns="tableColumns4"
              max-height="250"
            ></Table>
          </div>
        </Modal>
        <!-- 各通道OEE分布 end -->
      </div>
      <!-- 左边看板 end -->

      <!-- 中间看板 -->
      <div class="formBox_middle">
        <!-- 顶部 -->
        <div class="middle_top">
          <div class="gaugeFormTotle">
            <div class="gaugeFormTitle">员工总数</div>
            <div class="num_bg">{{staff}}</div>
          </div>
          <div class="gaugeFormTotle">
            <div class="gaugeFormTitle">一次合格率</div>
            <div class="num_bg" :style="{'color':okcolor}">{{passRate}}</div>
          </div>
          <div class="gaugeFormTotle">
            <div class="gaugeFormTitle">OEE</div>
            <div class="days_time num_bg" :style="{'color':oeecolor}">{{oeeNum > 0?oeeNum+'%':''}}</div>
          </div>
        </div>
        <!-- 顶部 end -->

        <!-- 通道图像 -->
        <div class="middle_map">
          <div class="factoryPassageway">
            <img :src="img_src" alt class="passagewayImg" :style="{width:'891px',height:'532px'}" />
            <div
              class="tagDialog mid_tag"
              v-for="(item,key) in tagDialogList"
              v-show="item.show"
              :key="key"
              :style="{left:item.left+'px',top:item.top+'px'}"
            >
              <img src="../../../static/images/u735.svg" alt class="dialogImg" />
              <div class="tag_main">
                <div class="tag_title">{{item.title}}</div>
                <div class="tag_content">
                  <div class="content_left">
                    <div>异常类型：{{item.type}}</div>
                    <div>持续时长：{{Math.floor(item.timeRang/60)+'分钟'}}</div>
                  </div>
                </div>
              </div>
              <i class="dot"></i>
              <span class="minDot"></span>
            </div>
            <!-- <div class="tag_left tagDialog mid_tag">
                    <img src="../../../static/images/u735.svg" alt="" class="dialogImg">
                    <div class="tag_main">
                        <div class="tag_title">OP 150  Hardness Inspection</div>
                        <div class="tag_content">
                            <div class="content_left">
                                <div>异常类型：{{normalType}}</div>
                                <div>持续时长：{{timeLegth}}</div>
                            </div>
                            <img src="../../../static/images/u693.svg" alt="">
                        </div>
                    </div>
                    <i class="dot"></i>
                    <span class="minDot"></span>
            </div>-->
            <!-- <div class="tag_right tagDialog ">
                    <img src="../../../static/images/u735.svg" alt="" class="dialogImg">
                    <div class="tag_main">
                        <div class="tag_title">OP 470  Washing</div>
                        <div class="tag_content">
                            <div class="content_left">
                                <div>异常类型：{{normalType2}}</div>
                                <div>持续时长：{{timeLegth2}}</div>
                            </div>
                            <img src="../../../static/images/Q.png" alt="">
                        </div>
                    </div>
                    <i class="dot"></i>
                    <span class="minDot"></span>
            </div>-->
          </div>
        </div>
        <!-- 通道图像 end -->

        <!-- 实时安灯TOP10 -->
        <div class="formBox">
          <div class="form_title">安灯TOP10</div>
          <div class="formMain table_bg">
            <div class="barForm_P" id="barForm1"></div>
          </div>
        </div>
        <!-- 实时安灯TOP10 end -->
      </div>
      <!-- 中间看板 end -->

      <!-- 右边看板 -->
      <div class="formBox_left formBox_right">
        <!-- 今日安灯信息 -->
        <div class="formBox compre_analysis">
          <div class="form_title">实时安灯信息</div>
          <div class="formMain tableForm">
            <ul class="table_title_bg">
              <li>设备编号</li>
              <li>异常类型</li>
              <li>当前状态</li>
              <li>持续时长</li>
              <!-- <li>安灯次数</li> -->
            </ul>
            <vue-seamless-scroll
              :data="messageList"
              :class-option="optionSetting"
              class="seamless-warp tbaleSlide"
            >
              <ul class="tableDetail">
                <!-- <tbody> -->
                <li v-if="messageList.length == 0"></li>
                <li v-for="(item,index) in messageList" :key="index" :data-id="item.id" v-else>
                  <div>{{item.machine}}</div>
                  <div>{{item.expection}}</div>
                  <div>{{item.status}}</div>
                  <div>{{Math.floor((item.cost)/60)}}分钟</div>
                  <!-- <div>{{item.count}}</div> -->
                </li>
                <!-- </tbody> -->
              </ul>
            </vue-seamless-scroll>
          </div>
        </div>
        <!-- 今日安灯信息 end -->

        <!-- OEE七大损失分布 -->
        <div class="formBox">
          <div class="form_title">OEE损失分布</div>
          <div class="formMain table_bg pieBox">
            <div class="stackingBar" id="pieForm_P" ref="pieForm_P"></div>
          </div>
        </div>
        <!-- OEE七大损失分布 end -->
      </div>
      <!-- 右边看板 end -->
    </div>
    <!-- 看板内容 end -->

    <!-- <embed src="" type=""> -->
  </div>
</template>
<script>
import axios from "@/libs/api.request";
import echarts from "echarts";
import vueSeamlessScroll from "vue-seamless-scroll";
import moment from "moment";
import Cookies from "js-cookie";
import { setInterval, clearInterval } from "timers";

import { initRouter } from "@/libs/router-util"; // 新增  引入动态菜单渲染
import { localSave } from "@/libs/util";

export default {
  components: {
    // 组件
    vueSeamlessScroll,
  },
  data() {
    return {
      imgLogo: require("../../../static/images/siger.png"), // logo
      img_src: require("../../../static/images/pass_1.png"),
      settingmodal: false, // 设置弹出框
      datetime: moment(new Date().getTime()).format("YYYY-MM-DD"),
      nowTime: moment(new Date().getTime()).format("YYYY-MM-DD"), // 当前时间
      totaldiv: false, // 每小时看板统计数据默认不显示，有数据才显示
      maxheight: 0, // 切片高度
      // 每小时产出统计表
      produceHourList: [],
      shifttype: 0,
      peoplenum: 0, // 员工总数
      plannum: 0, // 当班计划产量
      shiftList: [], // 班次开始时间
      shiftid: 0, // 选中班次
      passList: [], // 通道列表
      topassid: 0, // 从工厂页面传过来的通道id
      passtitle: "", // 通道名称
      tagDialogList: [], // 中间通道图，安灯异常显示
      Scrapnum: 0, // 报废
      Reworknum: 0, // 返工
      targetvalue: 0, // 目标值
      actualvalue: 0, // 实际值
      Differencevalue: 0, // 差值

      produceList: [
        {
          state: 0,
          produceName: "JSSWGL-2019001-01",
          produceGoal: "345",
          produceAmount: "345",
          produceDiffer: "0",
          produceNum: "6",
          produceScrap: "",
          produceRework: "",
        },
      ],

      // 状态表
      stateList: [
        {
          state: 3,
          time: "8:30",
          stateHeight: "",
        },
      ],
      stateHeight: "50",
      staff: 0, // 工厂员工总数
      passRate: "", // 合格率
      oeeNum: 0, // 综合OEE
      normalType: "设备故障", // 异常类型
      timeLegth: "7分钟", // 持续时长
      normalType2: "质量安灯", // 异常类型
      timeLegth2: "17分钟", // 持续时长
      // 今日安灯信息表格
      messageList: [],
      hourlength: 0, // 左边每小时看板小时数
      timer: 0, // 整个页面20分钟定时请求数据
      timeException: 0, // 安灯异常定时请求
      timeAll: 0, // 页面定时刷新2小时
      detailmodal: false, // 详情模态框
      timerx: "", // 动态控制显示
      index_timer: 0, // 当前显示的安灯
      tableColumns2: [
        {
          type: "index",
          title: this.$t("1008"), // 序号
          key: "xuhao",
          align: "center",
          width: 60,
        },
        {
          title: this.$t("5000011"), // 异常类别
          key: "expection",
          align: "center",
        },
        {
          title: "损失时长", // 持续时间
          align: "center",
          width: 100,
          key: "andon_cost_time",
        },
        {
          title: "操作", // 持续时间
          align: "center",
          width: 100,
          key: "action",
          render: (h, params) => {
            return h("div", [
              h(
                "Button",
                {
                  props: {
                    type: "primary",
                    size: "small",
                  },
                  style: {
                    marginRight: "5px",
                  },
                  on: {
                    click: () => {
                      this.show_oee(params.row);
                    },
                  },
                },
                "查看详情"
              ),
            ]);
          },
        },
      ],
      tableData2: [], // 差额详情表
      imageCode: 0, // 切换通道后保存图片数据
      searchtitle: "",
      detailtwomodal: false,
      tableData3: [],
      tableColumns3: [
        {
          type: "index",
          title: this.$t("1008"), // 序号
          key: "xuhao",
          align: "center",
          width: 60,
        },
        {
          title: "异常明细", // 异常明细
          key: "expection",
          align: "center",
          width: 150,
        },
        {
          title: "损失时长", // 损失时长
          key: "cost_time",
          align: "center",
          width: 100,
        },
        {
          title: "开始时间", // 开始时间
          key: "start",
          align: "center",
          width: 150,
        },
        {
          title: "结束时间", // 结束时间
          key: "end",
          align: "center",
          width: 150,
        },
        {
          title: "安灯工单号", // 工单号
          key: "ordernum",
          align: "center",
          render: (h, params) => {
            if (params.row.ordernum != "") {
              return h("div", [
                h(
                  "Button",
                  {
                    props: {
                      type: "primary",
                      size: "small",
                    },
                    style: {
                      marginRight: "5px",
                    },
                    on: {
                      click: () => {
                        this.JumpPage(params.row.ordernum);
                      },
                    },
                  },
                  params.row.ordernum
                ),
              ]);
            }
          },
        },
        {
          title: "责任岗位", // 责任岗位
          key: "responsibility",
          align: "center",
        },
      ],
      showTable: true,
      tableData4: [],
      tableColumns4: [
        {
          type: "index",
          title: this.$t("1008"), // 序号
          key: "xuhao",
          align: "center",
          width: 60,
        },
        {
          title: "产品名称", // 异常明细
          key: "ProductName",
          align: "center",
          width: 140,
        },
        {
          title: "报废/返工时间", // 损失时长
          key: "ReworkTime",
          align: "center",
          width: 150,
        },
        {
          title: "报废/返工工位", // 开始时间
          key: "SectionName",
          align: "center",
          width: 130,
        },
        {
          title: "报废原因", // 结束时间
          key: "Reason",
          align: "center",
          width: 150,
        },
        {
          title: "报废数量", // 工单号
          key: "Count",
          align: "center",
        },
        {
          title: "损失时长", // 责任岗位
          key: "Loss",
          align: "center",
        },
        {
          title: "处理人", // 责任岗位
          key: "Operator",
          align: "center",
        },
      ],
      pass_ok: 0,
      pass_oee: 0,
      okcolor: "#33ff33",
      oeecolor: "#33ff33",
    };
  },
  created() {},
  computed: {
    optionSetting: function () {
      return {
        step: 0.2, // 数值越大速度滚动越快
        // limitMoveNum: 2, // 开始无缝滚动的数据量 this.dataList.length
        hoverStop: true, // 是否开启鼠标悬停stop
        // direction: 0, // 0向下 1向上 2向左 3向右
        // openWatch: true, // 开启数据实时监控刷新dom
        // singleHeight: 740, // 单步运动停止的高度(默认值0是无缝不停止的滚动) direction => 0/1
        // singleWidth: 0, // 单步运动停止的宽度(默认值0是无缝不停止的滚动) direction => 2/3
        // waitTime: 6000 // 单步运动停止的时间(默认值1000ms)
      };
    },
  },
  mounted() {
    if (
      this.$store.state.user.logo !== "" &&
      this.$store.state.user.logo !== null &&
      this.$store.state.user.logo !== undefined
    ) {
      this.imgLogo = this.$store.state.user.logo;
    }
    // 判断是不是工厂跳转过来的
    if (
      this.$route.query.passid !== "" &&
      this.$route.query.passid !== null &&
      this.$route.query.passid !== undefined
    ) {
      this.topassid = this.$route.query.passid;
      Cookies.set("passid", this.$route.query.passid);
    }
    this.topassid = Cookies.get("passid"); // => undefined
    // 整个页面数据定时刷新，定时20分钟执行一次
    if (this.timer) {
      clearInterval(this.timer);
    } else {
      this.datetime = moment(this.datetime).format("YYYY-MM-DD");
      this.getline(); // 获取通道
      this.getSetting(); // 获取配置信息
      this.getColorset();
      this.timer = setInterval(() => {
        this.datetime = moment(this.datetime).format("YYYY-MM-DD");
        this.getline(); // 获取通道
        this.getSetting(); // 获取配置信息
        this.getColorset();
      }, 600000);
    }

    // 刷新安灯异常信息,定时1分钟执行一次
    if (this.timeException) {
      clearInterval(this.timeException);
    } else {
      this.timeException = setInterval(() => {
        this.getAndonExceptions(); // 获取实时安灯top10
        this.toTodayInfo(); // 今日安灯信息
      }, 120000);
    }

    // 两小时，整个页面刷新一次
    if (this.timeAll) {
      clearInterval(this.timeAll);
    } else {
      // 两小时后刷新,刷回当前时间
      this.timeAll = setInterval(() => {
        location.reload();
      }, 1000 * 60 * 60 * 2);
    }
  },
  methods: {
    // 一次合格率和oee颜色配置
    getColorset() {
      axios
        .request({
          url: "/dashboard/DashboardCnConfig/GetTotalSet",
          method: "get",
        })
        .then((res) => {
          if (res.data.ret === 1) {
            var item = res.data.data;
            this.pass_ok = item.passway_ftq;
            this.pass_oee = item.passway_oee;
          }
        });
    },
    // 跳转页面
    JumpPage: function (e) {
      if (e === "" || e === 0) {
        return false;
      }

      this.changemenu("andon").then((val) => {
        let routeUrl = this.$router.resolve({
          path: "/andon/abnormalrecords",
          query: { work_order: e },
        });
        window.open(routeUrl.href, "_blank");
      });
      // 先生成菜单路由再跳转
      // this.changemenu('andon',e)
      // this.$router.push({ path: '/realtime/passageway', query: { passid: e } })
      // let routeUrl = this.$router.resolve({
      //   path: "/andon/abnormalrecords",
      //   query: {work_order:e}
      // });
      // window.open(routeUrl.href, '_blank');
    },
    changemenu: function (value) {
      this.$store.commit("setmenuitem", value);
      var data = {
        block: this.$store.state.user.blockitem,
      };
      initRouter(this.$store.state.user.blockitem, false); // 新增 调用方法,动态生成路由,
      localSave("sigerdatablockitem", JSON.stringify(data));
      return Promise.resolve("success");
    },
    search() {
      if (
        this.topassid === 0 ||
        this.topassid === undefined ||
        this.shifttype === undefined ||
        this.shifttype === 0 ||
        this.datetime == "" ||
        this.datetime == undefined
      ) {
        alert("请选择通道、日期及班次信息");
        return false;
      }
      // 查看按钮
      if (this.imageCode && this.imageCode != 0) {
        this.img_src = require("../../../static/images/pass_" +
          this.imageCode +
          ".png");
      }
      if (this.searchtitle && this.searchtitle != "") {
        this.passtitle = this.searchtitle;
      }
      this.datetime = moment(this.datetime).format("YYYY-MM-DD");
      // 数据初始化
      this.settingmodal = false;
      Cookies.set("passid", this.topassid);
      this.loadProduce();
      this.init_toBar();
    },
    // 获取配置
    setting() {
      this.settingmodal = true;
      let option = [];
      for (var i = 0; i < 24; i++) {
        let arr = {};
        arr.id = i;
        arr.name = i;
        option.push(arr);
      }
      this.shiftList = option;
      this.getSetting();
    },
    getSetting() {
      if (this.topassid == undefined) {
        this.topassid = 0;
      }
      axios
        .request({
          url:
            "dashboard/Dashboardlevel/GetlevelCfg?type=2&section=" +
            this.topassid,
          method: "get",
        })
        .then((res) => {
          // 获取配置
          if (res.data.ret === 1 && res.data.data != null) {
            let info = res.data.data;
            this.peoplenum = info.emplCount;
            this.shifttype = info.schedu;
            this.shiftid = info.startime;
            this.plannum = info.column4;

            this.topassid = info.section;
            this.passtitle = info.section_name;
            if (info.pic) {
              this.img_src = require("../../../static/images/pass_" +
                info.pic +
                ".png");
            }
            this.datetime = moment(info.currentDate).format("YYYY-MM-DD"); // 当前时间
            // 数据初始化
            Cookies.set("passid", this.topassid);
            this.loadProduce();
            this.init_toBar();
          }
        });
    },
    // 切换通道
    changeSection() {
      axios
        .request({
          url:
            "dashboard/Dashboardlevel/GetlevelCfg?type=2&section=" +
            this.topassid,
          method: "get",
        })
        .then((res) => {
          // 获取配置
          if (res.data.ret === 1 && res.data.data != null) {
            let info = res.data.data;
            this.peoplenum = info.emplCount;
            this.shifttype = info.schedu;
            this.shiftid = info.startime;
            this.plannum = info.column4;
            this.datetime = moment(info.currentDate).format("YYYY-MM-DD"); // 当前时间
            this.imageCode = info.pic;
            this.searchtitle = info.section_name;
          }
        });
    },
    settingadd() {
      if (
        this.topassid === 0 ||
        this.topassid === undefined ||
        this.shifttype === undefined ||
        this.shifttype === 0 ||
        this.datetime == "" ||
        this.datetime == undefined
      ) {
        alert("请选择通道、日期及班次信息");
        return false;
      }
      var data = {
        section: this.topassid,
        EmplCount: this.peoplenum, // 员工总数
        Schedu: this.shifttype,
        StartTime: this.shiftid,
        Column4: this.plannum,
        Date: moment(this.datetime).format("YYYY-MM-DD"),
      };
      axios
        .request({
          url: "/dashboard/DashboardLevel/SaveChanelConfig",
          data,
          method: "post",
        })
        .then((res) => {
          if (res.data.ret === 1) {
            this.settingmodal = false;
            Cookies.set("passid", this.topassid);
            this.getSetting(); // 保存成功，获取配置
          }
        });
    },
    getline() {
      // 获取动态产线
      axios
        .request({
          url: "dashboard/Dashboardlevel/getline",
          method: "get",
        })
        .then((res) => {
          if (res.data.ret === 1 && res.data.data.length > 0) {
            this.passList = res.data.data;
          } else {
            this.passList = [];
          }
        });
    },
    init_toBar() {
      // 获取合格率
      this.datetime = moment(this.datetime).format("YYYY-MM-DD"); // 当前时间
      if (this.topassid == 0 || this.topassid == undefined) {
        return false;
      }
      this.axios
        .request({
          url:
            "dashboard/DashboardQms/GetChannelFtq?date=" +
            this.datetime +
            "&section=" +
            this.topassid,
          method: "get",
        })
        .then((res) => {
          if (res.data.ret == 1) {
            this.passRate = res.data.data.totalFtq;

            if (this.passRate < 0) {
              this.passRate = 0;
            }
            if (this.passRate > 100) {
              this.passRate = 100;
            }
            if (this.passRate == 0) {
              this.passRate = "";
            } else {
              if (this.passRate >= this.pass_ok) {
                this.okcolor = "#33ff33";
              } else {
                this.okcolor = "red";
              }
              // 强制两位小数
              let value_str = this.passRate;
              value_str = (value_str + "").split(".");
              if (value_str.length < 2) {
                value_str.push("00");
              }
              this.passRate =
                value_str[0] + "." + (value_str[1] + "00").slice(0, 2) + "%";
            }
          }
        });
    },
    // 获取切片数据
    getSectionslice() {
      this.datetime = moment(this.datetime).format("YYYY-MM-DD"); // 当前时间
      if (this.topassid == 0 || this.topassid == undefined) {
        return false;
      }
      axios
        .request({
          url:
            "dashboard/DashboardAndon/AndonSlice?section=" +
            this.topassid +
            "&date=" +
            this.datetime +
            "&start=" +
            this.shiftid,
          method: "get",
        })
        .then((res) => {
          var num = this.hourlength;
          var lineHeight = num > 8 ? 55 : 76; // 行高
          this.maxheight = lineHeight * num;
          if (res.data.ret === 1 && res.data.data.length > 0) {
            var arr = [];
            res.data.data.forEach(function (item, index) {
              arr.push({
                state: item.status,
                stateHeight: item.percentage * lineHeight * num, // 百分百*每格高的*格数
                color: item.color,
              });
            });
            this.stateList = arr;
          } else {
            this.stateList = [
              {
                state: 2,
                stateHeight: 1 * lineHeight * num, // 百分百*每格高的*格数
                color: gray,
              },
            ];
          }
        });
    },
    // 获取通道安灯异常信息
    getAndonExceptions() {
      this.datetime = moment(this.datetime).format("YYYY-MM-DD"); // 当前时间
      if (this.topassid == 0 || this.topassid == undefined) {
        return false;
      }
      axios
        .request({
          url:
            "/dashboard/DashboardAndon/AndonMachinForChannel?section=" +
            this.topassid +
            "&date=" +
            this.datetime,
          method: "get",
        })
        .then((res) => {
          if (res.data.ret === 1 && res.data.data.length > 0) {
            var info = res.data.data;
            var arr = [];
            info.forEach(function (item, index) {
              var arr1 = {};
              arr1.left = item.left - 45;
              arr1.top = item.top - 117;
              arr1.title = item.title;
              arr1.type = item.type;
              arr1.timeRang = item.timeRang;
              arr1.show = false;
              arr.push(arr1);
            });
            clearInterval(this.timerx);
            this.tagDialogList = arr;
            this.index_timer = 0;
            this.tagDialog_showchange();
          } else {
            this.tagDialogList = [];
          }
        });
    },
    tagDialog_showchange() {
      this.timerx = setInterval(() => {
        if (
          this.index_timer === 0 &&
          this.tagDialogList[this.tagDialogList.length - 1].show === false
        ) {
          this.tagDialogList[this.index_timer].show = true;
        } else if (this.index_timer === this.tagDialogList.length) {
          this.index_timer = -1;
          this.tagDialogList[this.tagDialogList.length - 1].show = false;
        } else {
          this.tagDialogList[this.index_timer - 1].show = false;
          this.tagDialogList[this.index_timer].show = true;
        }
        if (this.index_timer === this.tagDialogList.length) {
          this.index_timer = 0;
        } else {
          this.index_timer = this.index_timer + 1;
        }
      }, 5000);
    },
    // 每小时产出看板详情
    show_andon(time) {
      var params = {
        starttime: time,
        endtime: time + 3600,
        section: this.topassid,
      };
      this.axios
        .request({
          url: "dashboard/DashboardAndon/GetAdnonSliceSum",
          params,
          method: "get",
        })
        .then((res) => {
          if (res.data.ret === 1) {
            let arr = [];
            if (res.data.data.length > 0) {
              this.mockTableData1(res.data.data, time);
              this.detailmodal = true;
            } else {
              // window_warning('该时间段暂无数据')
              this.detailmodal = true;
              this.tableData2 = [];
            }
          }
        });
    },
    mockTableData1(tablelist, time) {
      let data = [];
      tablelist.forEach((item) => {
        data.push({
          // expection: item.expection1 + (item.expection2?(' — ' + item.expection2):'') +(item.expection3?(' — ' + item.expection3):'') ,
          expection:
            item.expection != undefined && item.expection != null
              ? item.expection
              : "",
          starttime: time,
          expection_id: item.expection_id,
          endtime: time + 3600,
          andon_cost_time: item.cost_time
            ? Math.floor(item.cost_time / 60) + "分钟"
            : "",
        });
      });
      this.tableData2 = data;
    },
    // 显示安灯详情
    show_oee(rowData) {
      var params = {
        starttime: rowData.starttime,
        endtime: rowData.endtime,
        section: this.topassid,
        expectiontype: rowData.expection_id,
      };
      this.axios
        .request({
          url: "dashboard/DashboardAndon/GetAdnonSliceDetail",
          params,
          method: "get",
        })
        .then((res) => {
          if (res.data.ret === 1) {
            let arr = [];
            this.mockTableData2(res.data.data);
            this.detailtwomodal = true;
          } else {
            // window_warning('该时间段暂无数据')
            this.showTable = false;
            this.detailtwomodal = true;
            this.tableData3 = [];
            this.tableData4 = [];
          }
        });
    },
    mockTableData2(tablelist) {
      let data = [];
      if (tablelist.andonDetail.length > 0) {
        tablelist.andonDetail.forEach((item) => {
          data.push({
            expection:
              item.expection != undefined && item.expection != null
                ? item.expection
                : "",
            start: moment(item.start * 1000).format("YYYY-MM-DD HH:mm:ss"),
            responsibility: item.responsibility,
            end:
              item.end === 0
                ? ""
                : moment(item.end * 1000).format("YYYY-MM-DD HH:mm:ss"),
            cost_time: item.cost_time
              ? Math.round((item.cost_time / 60) * 100) / 100 + "分钟"
              : 0 + "分钟",
            ordernum: item.work_order,
          });
        });
      }
      this.tableData3 = data;

      let data1 = [];
      if (tablelist.andonDetailEx.length > 0) {
        tablelist.andonDetailEx.forEach((item) => {
          data1.push({
            ProductName: item.productName,
            ProductCode: item.productCode,
            ReworkTime: item.reworkTime,
            SectionName: item.sectionName,
            Reason: item.reason,
            Count: item.count,
            Loss: item.loss
              ? Math.round((item.loss / 60) * 100) / 100 + "分钟"
              : 0 + "分钟",
            Operator: item.operator,
          });
        });
        this.showTable = true;
      } else {
        this.showTable = false;
      }
      this.tableData4 = data1;
    },
    // 今日安灯信息
    toTodayInfo() {
      this.datetime = moment(this.datetime).format("YYYY-MM-DD"); // 当前时间
      if (this.topassid == 0 || this.topassid == undefined) {
        return false;
      }
      this.axios
        .request({
          url:
            "/dashboard/DashboardAndon/AndonInfo?section=" +
            this.topassid +
            "&date=" +
            this.datetime,
          method: "get",
        })
        .then((res) => {
          if (res.data.ret === 1) {
            let arr = [];
            if (res.data.data.length > 0) {
              res.data.data.forEach(function (item, index) {
                let arr1 = {};
                arr1.machine =
                  item.machine && item.machine.length > 10
                    ? item.machine.substring(0, 10) + "..."
                    : item.machine;
                // arr1.status = item.status
                if (item.status_value == 2) {
                  arr1.status = "待签到";
                } else if (item.status_value == 3) {
                  arr1.status = "处理中";
                } else if (item.status_value == 4) {
                  arr1.status = "待确认";
                } else {
                  arr1.status = item.status;
                }
                arr1.expection =
                  item.expection && item.expection.length > 10
                    ? item.expection.substring(0, 10) + "..."
                    : item.expection;
                arr1.cost = item.cost;
                arr1.count = item.count;
                arr.push(arr1);
              });
              this.messageList = arr;
            } else {
              this.messageList = arr;
            }
          }
        });
    },
    // 根据秒求天小时分钟
    showTimeStr: function (val) {
      if (val < 60) {
        return 0 + "分钟"; // 秒
      } else {
        var min_total = Math.floor(val / 60); // 分钟
        var sec = Math.floor(val % 60); // 余秒
        // var sec_str = sec == 0 ? '' : sec + '秒'
        if (min_total < 60) {
          return min_total + "分钟";
        } else {
          var hour_total = Math.floor(min_total / 60); // 小时数
          var min = Math.floor(min_total % 60); // 余分钟
          var min_str = min == 0 ? "" : min + "分钟";
          if (hour_total < 24) {
            return hour_total + "小时" + min_str;
          } else {
            var day_total = Math.floor(hour_total / 24); // 天数
            var hour = Math.floor(hour_total % 24); // 余小时
            var hour_str = hour == 0 ? "" : hour + "小时";
            return day_total + "天" + hour_str + min_str;
          }
        }
      }
    },
    // 实时安灯TOP10
    toBar() {
      this.datetime = moment(this.datetime).format("YYYY-MM-DD"); // 当前时间
      if (this.topassid == 0 || this.topassid == undefined) {
        return false;
      }
      this.axios
        .request({
          url:
            "/dashboard/DashboardAndon/Top10Andon?section=" +
            this.topassid +
            "&date=" +
            this.datetime,
          method: "get",
        })
        .then((res) => {
          var arr = {};
          var name = [];
          var data = [];
          if (res.data.ret === 1 && res.data.data.length > 0) {
            if (res.data.data.length > 0) {
              res.data.data.forEach((item) => {
                name.push(item.work_order);
                data.push(Math.floor(item.cost / 60));
              });
            }
            arr.name = name;
            arr.data = data;
            this.toBarData(arr, "分钟", "异常类别");
          } else {
            arr.name = name;
            arr.data = data;
            this.toBarData(arr, "", "");
          }
        });
    },
    toBarData(data, y, x) {
      // console.log(data.name)
      var myChart = echarts.init(document.getElementById("barForm1"));
      var option = {
        // color: ['#3398DB'],
        tooltip: {
          trigger: "axis",
          axisPointer: {
            // 坐标轴指示器，坐标轴触发有效
            type: "shadow", // 默认为直线，可选为：'line' | 'shadow'
          },
        },
        textStyle: {
          // ----图例内容样式
          color: "#fff", // ---所有图例的字体颜色
          // backgroundColor:'black',  //---所有图例的字体背景色
        },
        // grid: {
        //   left: '5%',
        //   right: '4%',
        //   top: '10%',
        //   bottom: '10%',
        //   containLabel: true
        // },
        xAxis: [
          {
            name: x,
            type: "category",
            data: data.name,
            axisTick: {
              alignWithLabel: true,
            },
            nameTextStyle: {
              // ---坐标轴名称样式
              color: "#fff",
              // padding: [5, 0, 0, -5] // ---坐标轴名称相对位置
            },
            axisLine: {
              show: false,
            },
            axisLabel: {
              interval: 0,
              rotate: 15,
            },
          },
        ],
        yAxis: [
          {
            name: y,
            type: "value",
            max: function (value) {
              return value.max + 5;
            },
            min: 0,
            splitNumber: 4,
            axisLine: {
              show: false,
            },
          },
        ],
        series: [
          {
            name: "",
            type: "bar",
            barWidth: "16",
            barCategoryGap: "48",
            data: data.data,
            itemStyle: {
              normal: {
                label: {
                  show: true, // 开启显示
                  position: "top", // 在上方显示
                  textStyle: {
                    // 数值样式
                    color: "#fff",
                    // fontSize: 16
                  },
                },
                color: function (params) {
                  var colorList = [
                    "#DF9B55",
                    "#DF9B55",
                    "#DF9B55",
                    "#28B9FF",
                    "#28B9FF",
                    "#28B9FF",
                    "#28B9FF",
                    "#28B9FF",
                    "#28B9FF",
                    "#28B9FF",
                  ];
                  return colorList[params.dataIndex];
                },
              }, // ---图形形状
            },
          },
        ],
      };
      myChart.setOption(option);
      window.onresize = function () {
        myChart.resize();
      };
    },
    // OEE七大损失分布
    init_toPie() {
      this.datetime = moment(this.datetime).format("YYYY-MM-DD"); // 当前时间
      if (this.topassid == 0 || this.topassid == undefined) {
        return false;
      }
      this.axios
        .request({
          url:
            "dashboard/DashboardAndon/AndonExpectionPercentage?type=2&date=" +
            this.datetime +
            "&section=" +
            this.topassid +
            "&start=" +
            this.shiftid,
          method: "get",
        })
        .then((res) => {
          if (res.data.ret == 1) {
            var total = res.data.data.total;
            var arr = [];
            var colorlist = [];
            res.data.data.arr.forEach((item) => {
              var obj = {};
              obj.value = item.time;
              obj.starttime = item.start;
              obj.endtime = item.end;
              obj.expection_id = item.expection_id;
              obj.name =
                item.expection_name +
                "\n" +
                Math.floor(item.time / 60) +
                "分钟," +
                ((item.time / total) * 100).toFixed(2) +
                "%";
              arr.push(obj);
              colorlist.push(item.color);
            });
            this.toPie(arr, colorlist);
          }
        });
    },
    toPie(arr, colorlist) {
      let div =
        '<div id="divEchartcon" style="width:100%;height:386px;"></div>';
      let dom = this.$refs.pieForm_P;
      dom.innerHTML = div;
      var myChart = echarts.init(document.getElementById("divEchartcon"));
      var oee = 100 - this.oeeNum <= 0 ? 0 : (100 - this.oeeNum).toFixed(2);

      if (oee < 0) {
        oee = 0;
      }
      if (oee > 100) {
        oee = 100;
      }
      // 强制两位小数
      let value_str = oee;
      value_str = (value_str + "").split(".");
      if (value_str.length < 2) {
        value_str.push("00");
      }
      oee = value_str[0] + "." + (value_str[1] + "00").slice(0, 2);

      var option = {
        title: {
          // 中间文字定义
          text: "总损失",
          subtext: oee + "%",
          x: "center",
          y: "center",
          textStyle: {
            fontSize: 16,
            color: "#fff",
          },
          subtextStyle: {
            fontSize: 16,
            color: "#fff",
          },
        },
        tooltip: {
          // 鼠标hover覆盖提示框
          show: false, // 可视
          trigger: "item", // 根据item提示信息
          formatter: "{a} <br/>{b}: {c} ({d}%)", // 提示内容
        },
        // //设置饼状图每个颜色块的颜色
        color: colorlist,
        // 提色板显示
        series: [
          {
            name: "",
            type: "pie",
            radius: ["35%", "50%"],
            avoidLabelOverlap: true, // 防止标签重叠
            label: {
              color: "#fff",
              fontSize: "16",
            },
            labelLine: {
              lineStyle: {
                color: "#fff",
              },
            },
            data: arr,
          },
        ],
      };
      myChart.setOption(option);
      window.onresize = function () {
        myChart.resize();
      };

      var that = this;
      myChart.on("click", function eConsole(param) {
        // 这个params可以获取你要的饼图中的当前点击的项的参数
        that.show_oee(param.data);
      });
    },

    // 返回上一页
    back() {
      this.$router.go(-1); // 返回上一层
    },
    // 加载数据
    loadProduce() {
      var params = {
        section: this.topassid,
        date: this.datetime,
        starttime: this.shiftid,
      };
      if (this.topassid == 0 || this.topassid == undefined) {
        return false;
      }
      axios
        .request({
          url: "dashboard/DashboardChanel/GetProduceHour",
          params,
          method: "get",
        })
        .then((res) => {
          if (res.data.ret === 1) {
            let info = res.data.data.data;
            this.produceHourList = res.data.data.data;
            // 处理换型产品换行
            if (info.length > 0) {
              let producedata = [];
              info.forEach(function (item, index) {
                let producearr = {};
                producearr.hour = item.hour;
                producearr.target = item.target;
                producearr.produce = item.produce;
                producearr.balance = item.balance;
                producearr.hourTimeStamp = item.hourTimeStamp;
                if (item.product != "" && item.product.indexOf(",") != -1) {
                  let reg = new RegExp(",", "g");
                  let newstr = item.product.replace(reg, "\n");
                  producearr.product = newstr;
                } else {
                  producearr.product = item.product;
                }
                producedata.push(producearr);
              });
              this.produceHourList = producedata;
            }

            this.staff = res.data.data.emplCount;
            // this.passRate = res.data.data.PassRated
            this.Reworknum = res.data.data.total.rework;
            this.oeeNum = res.data.data.oee;

            // 强制两位小数
            if (this.oeeNum > 0) {
              if (this.oeeNum >= this.pass_oee) {
                this.oeecolor = "#33ff33";
              } else {
                this.oeecolor = "red";
              }

              // 强制两位小数
              let value_str = this.oeeNum;
              value_str = (value_str + "").split(".");
              if (value_str.length < 2) {
                value_str.push("00");
              }
              this.oeeNum =
                value_str[0] + "." + (value_str[1] + "00").slice(0, 2);
            }

            // 求stateList
            this.hourlength = info.length;
            let arr = [];
            if (info.length > 0) {
              this.totaldiv = true; // 每小时看板统计显示
              info.forEach(function (item, index) {
                let arr1 = {};
                arr1.state = 0;
                arr1.time = item.Hour + ":00";
                arr1.stateHeight = "";
                arr.push(arr1);
              });
            } else {
              this.totaldiv = false; // 每小时看板统计不显示
            }
            this.stateList = arr;

            this.toBar();
            this.init_toPie();
            this.toTodayInfo();
            // 获取切片数据
            this.getSectionslice();
            // 获取通道安灯异常信息
            this.getAndonExceptions();

            // 获取实际值目标值
            var totalNum = res.data.data.total;
            this.Scrapnum = totalNum.waste; // 报废
            this.Rework = totalNum.rework; // 返工
            this.targetvalue = totalNum.targetTotal; // 目标值
            this.actualvalue = totalNum.produceTotal; // 实际值
            this.Differencevalue = totalNum.balanceTotal; // 差值
          }
        });
    },
  },
  destroyed() {
    clearInterval(this.timer); // 清除页面刷新定时器20分钟
    clearInterval(this.timeException); // 安灯异常定时刷新1分钟
    clearInterval(this.timeAll); // 整个页面定时刷新2小时
    Cookies.remove("passid"); // fail!
    clearInterval(this.timerx);
  },
};
</script>

<style lang="less" scoped>
@import "./comprehensive.less";
/* v-enter 【这是一个时间点】 是进入之前，元素的起始状态，此时还没有开始进入 */
/* v-leave-to 【这是一个时间点】 是动画离开之后，离开的终止状态，此时，元素 动画已经结束了 */
.v-enter,
.v-leave-to {
  opacity: 0;
  // transform: translateX(150px);
}

/* v-enter-active 【入场动画的时间段】 */
/* v-leave-active 【离场动画的时间段】 */
.v-enter-active,
.v-leave-active {
  transition: all 0.8s ease;
}
.chart_dadar {
  height: 315px;
}
.gaugeForm {
  height: 100px;
}
.pieForm_P {
  height: 160px;
  width: 160px;
}
.barForm_P {
  width: 100%;
  // height: 205px;
  height: 180px;
  margin: 0 auto;
}
.stackingBar {
  width: 100%;
  // height: 300px;
  height: 386px;
  // margin: 40px auto;
}
.IconSetting {
  display: inline-block;
  position: fixed;
  right: 10px;
  top: -20px;
}
.IconSetting img {
  width: 40px;
  cursor: pointer;
}
.settingmodal {
  .out_row {
    margin-left: 15px;
    line-height: 40px;
    display: block;
    label {
      float: left;
      width: 90px;
    }
    input {
      margin-left: 9px;
      width: 200px;
    }
    select {
      display: inline-block;
      margin-left: 9px;
      width: 200px;
    }
  }
}
</style>

<style lang="less">
.dashTable {
  .ivu-table-wrapper {
    border: 1px solid #91c3ff !important;
    border-bottom: 0 !important;
    border-right: 0 !important;
  }
  th {
    background-color: rgb(0, 69, 132, 0.78) !important;
    border-right: 1px solid #91c3ff !important;
    border-bottom: 1px solid #91c3ff !important;
  }
  td {
    background-color: rgb(2, 29, 53, 0.9) !important;
    border-right: 1px solid #91c3ff !important;
    color: #fff !important;
    border-bottom: 1px solid #91c3ff !important;
  }
  .ivu-table:before,
  .ivu-table:after {
    background-color: #91c3ff !important;
  }
}
</style>
