<template>
  <div class="t_woex">
    <div class="no_wkod h100" v-if="noWkod">
      <div class="center">
        <h1>设备暂无工单，请扫描工单开始生产。</h1>
        <Input
          v-focus
          size="large"
          v-model="wkodNo"
          icon="md-return-left"
          @on-click="getWkodByQrCode"
          @on-enter="getWkodByQrCode"
          placeholder="请扫描工单二维码"
        ></Input>
      </div>
    </div>
    <div class="wkod h100" v-else>
      <Row class="h100">
        <Col span="16" class="h100">
          <iframe
            id="pic_iframe"
            v-if="wkodDetail.draw_url"
            :src="`${wkodDetail.draw_url}#toolbar=0`"
            frameborder="0"
            width="100%"
            height="100%"
          ></iframe>
          <div class="empty h100" v-else></div>
        </Col>
        <Col span="8" class="h100">
          <div class="wkodDetail">
            <h1 v-if="wkodDetail.status == 1">
              <Avatar size="large" class="sts_1"></Avatar>
              未下发
            </h1>
            <h1 v-if="wkodDetail.status == 2">
              <Avatar size="large" class="sts_2"></Avatar>
              未排产
            </h1>
            <h1 v-if="wkodDetail.status == 3">
              <Avatar size="large" class="sts_3"></Avatar>
              已派工
            </h1>
            <h1 v-if="wkodDetail.status == 4">
              <Avatar size="large" class="sts_4"></Avatar>
              生产中
            </h1>
            <h1 v-if="wkodDetail.status == 5">
              <Avatar size="large" class="sts_5"></Avatar>
              已完工
            </h1>
            <h1 v-if="wkodDetail.status == 6">
              <Avatar size="large" class="sts_6"></Avatar>
              已终止
            </h1>
            <h1 v-if="wkodDetail.status == 7">
              <Avatar size="large" class="sts_7"></Avatar>
              逾期
            </h1>
            <h1 v-if="wkodDetail.status == 8">
              <Avatar size="large" class="sts_8"></Avatar>
              调机中
            </h1>
            <h1 v-if="wkodDetail.status == 9">
              <Avatar size="large" class="sts_9"></Avatar>
              暂停中
            </h1>
            <div class="detail">
              <div class="detail_row">
                <label>工令单号：</label>
                <div>{{ wkodDetail.circulation }}</div>
              </div>
              <div class="detail_row">
                <label>产品名称：</label>
                <div style="color: #2d8cf0; cursor: pointer" @click="preview()">
                  {{ wkodDetail.producename }}
                </div>
              </div>
              <div class="detail_row">
                <label>加工工序：</label>
                <div>{{ wkodDetail.route_name }}</div>
              </div>
              <div class="detail_row">
                <label>计划数量：</label>
                <div>{{ wkodDetail.quantity }}件</div>
              </div>
              <div class="detail_row">
                <label>已报工数：</label>
                <div>{{ wkodDetail.number }}件</div>
              </div>
              <div class="detail_row">
                <label>计划日期：</label>
                <div>{{ wkodDetail.deliverytime | deliveryFormat }}</div>
              </div>
            </div>
            <div class="btnGroup" v-if="btnGroupShow">
              <Button
                size="large"
                type="primary"
                @click="startDebug()"
                :disabled="wkodDetail.status != 3"
              >
                开始调机
              </Button>
              <Button
                size="large"
                type="primary"
                @click="startProduct()"
                :disabled="wkodDetail.status != 8"
              >
                开始生产
              </Button>
              <Button
                size="large"
                type="primary"
                @click="continueProduct()"
                v-if="wkodDetail.status == 9"
              >
                继续生产
              </Button>
              <Button
                v-else
                size="large"
                type="primary"
                @click="pauseProduct()"
                :disabled="wkodDetail.status != 4"
              >
                暂停生产
              </Button>
              <Button
                size="large"
                type="primary"
                @click="productReport()"
                :disabled="wkodDetail.status != 4"
              >
                生产报工
              </Button>
            </div>
          </div>
        </Col>
      </Row>
    </div>
    <Modal v-model="isShow" class="newModalClass" title="生产报工">
      <div class="modal_body">
        <div class="filter">
          <label>程序号：</label>
          <Select
            size="large"
            class="searchSelect"
            v-model="programCode"
            @on-change="handlePgCode"
          >
            <Option
              :key="i"
              :value="v.programCode"
              v-for="(v, i) in programList"
              >{{ v.programCode }}</Option
            >
          </Select>
        </div>
        <div class="filter">
          <label>开始时间：</label>
          <Input disabled size="large" class="searchInput" :value="startTime" />
        </div>
        <div class="filter">
          <label>结束时间：</label>
          <Input disabled size="large" class="searchInput" :value="endTime" />
        </div>
        <div class="filter">
          <label>生产数量：</label>
          <Input disabled size="large" class="searchInput" :value="number" />
        </div>
        <div class="filter">
          <label> <i>*</i>合格数量： </label>
          <InputNumber
            :min="0"
            size="large"
            v-model="okNum"
            style="width: 140px"
            onkeypress="return /[\d]/.test(String.fromCharCode(event.keyCode))"
          />
        </div>
        <div class="filter">
          <label> <i>*</i>不合格数： </label>
          <InputNumber
            :min="0"
            size="large"
            v-model="noOkNum"
            style="width: 140px"
            onkeypress="return /[\d]/.test(String.fromCharCode(event.keyCode))"
          />
        </div>
      </div>
      <div slot="footer">
        <Button size="large" @click="confirmCancel">取消</Button>
        <Button size="large" type="error" @click="doSubmit(2)">
          确认终止
        </Button>
        <Button size="large" type="warning" @click="doSubmit(1)">
          确认完工
        </Button>
        <Button size="large" type="primary" @click="doSubmit(0)">
          报工提交
        </Button>
      </div>
    </Modal>
    <Modal v-model="isPreview" footer-hide fullscreen title="预览">
      <div class="modal_body">
        <iframe
          :src="`${curFileUrl}#toolbar=0`"
          v-if="reset"
          frameborder="0"
          width="100%"
          height="100%"
        ></iframe>
      </div>
    </Modal>
  </div>
</template>
<script>
import { getToken } from "@/libs/util";
import { mapState } from "vuex";

export default {
  name: "t_woex",
  inject: ["reload"],
  props: {
    curLevel: {
      type: Array,
    },
    levelNums: {
      type: Number,
    },
    signDetail: {
      type: Object,
    },
  },
  data() {
    return {
      // 当前工位下是否没有工单
      noWkod: true,
      // 工单二维码 --> 工令单号|工序 ID
      wkodNo: "",
      // 工单详情
      wkodDetail: {},
      // 设备 ID
      machineId: 0,
      // 报工弹框是否显示
      isShow: false,
      // 程序号与产量列表
      programList: [],
      // 程序号
      programCode: "",
      // 开始时间
      startTime: "",
      // 结束时间
      endTime: "",
      // 生产数量
      number: "",
      // 合格数量
      okNum: null,
      // 不合格数
      noOkNum: null,
      // 预览弹框是否展示
      isPreview: false,
      // 当前预览的工艺图纸文件路径
      curFileUrl: "",
      // 复位标志位
      reset: false,
      // 防抖
      flag: false,
      // 全屏好看的 Loading
      loading: null,
    };
  },
  mounted() {
    const _this = this;
    // 若当前页面不是从签到签出页面跳转过来的，就返回签到签出页面
    if (!_this.curLevel.length) {
      _this.$router.replace({
        name: "t_sign",
      });
      return false;
    }
    _this.getWkodBySection();
  },
  filters: {
    deliveryFormat(v) {
      return v.slice(0, 10);
    },
  },
  computed: {
    ...mapState({
      userId: (state) => state.user.userId,
    }),
    curSection() {
      return this.curLevel[this.curLevel.length - 1];
    },
    btnGroupShow() {
      let flag =
        this.wkodDetail.section == this.curSection ||
        this.wkodDetail.section == 0;
      return flag;
    },
  },
  directives: {
    focus: {
      inserted: function (el, binding) {
        el.children[1].focus();
      },
    },
  },
  methods: {
    // 根据工位 ID 查询该工位下是否有已绑定的工单
    getWkodBySection() {
      const _this = this;
      let params = {
        sectionId: _this.curLevel[_this.curLevel.length - 1],
      };
      _this.loading = _this.$loading();
      _this.axios
        .request({
          url: "/CNC/ProductPlanDispatch/WebScanMachine",
          params,
          method: "get",
        })
        .then((res) => {
          _this.loading.close();
          let result = res.data;
          if (result.ret == 1) {
            let data = result.data;
            let state = data.state;
            _this.noWkod = !state;
            _this.machineId = data.machineId;
            if (data.draw_url) {
              data.draw_url = _this.axios.publicPath + data.draw_url;
              _this.setIframe();
            }
            _this.wkodDetail = data;
          }
        })
        .catch((err) => {
          _this.loading.close();
          _this.$Message.error("系统异常，请联系管理员！");
        });
    },
    // 根据工序码查询工单
    getWkodByQrCode() {
      const _this = this;
      if (!_this.wkodNo) {
        _this.$Message.error("请输入工序码或扫描工序码！");
        return false;
      }
      let params = {
        code: _this.wkodNo,
      };
      _this.loading = _this.$loading();
      _this.axios
        .request({
          url: "/CNC/ProductPlanDispatch/WebScanMachines",
          params,
          method: "get",
        })
        .then((res) => {
          _this.loading.close();
          let result = res.data;
          if (result.ret == 1) {
            _this.noWkod = false;
            let data = result.data;
            if (data.draw_url) {
              data.draw_url = _this.axios.publicPath + data.draw_url;
              _this.setIframe();
            }
            _this.wkodDetail = data;
          } else {
            _this.$Message.error(_this.$t(result.msg));
          }
        })
        .catch((err) => {
          _this.loading.close();
          _this.$Message.error("系统异常，请联系管理员！");
        });
    },
    // 开始调机
    startDebug() {
      const _this = this;
      // 将工单与工位绑定
      _this.bindWkodAndSection();
    },
    // 将工单与工位绑定
    bindWkodAndSection() {
      const _this = this;
      let data = {
        route_code: _this.wkodDetail.route_ordernumber,
        machineId: _this.machineId,
        sectionId: _this.curLevel[_this.curLevel.length - 1],
      };
      _this.loading = _this.$loading();
      _this.axios
        .request({
          url: "/CNC/ProductPlanDispatch/WebStartProduct",
          data,
          method: "post",
        })
        .then((res) => {
          _this.loading.close();
          let result = res.data;
          if (result.ret == 1) {
            _this.$Message.success("当前工位与该工单绑定，请开始生产报工！");
            // 重新刷新一下工单详情
            // _this.wkodNo = _this.wkodDetail.route_ordernumber;
            // _this.getWkodByQrCode();
            _this.getWkodBySection();
          } else {
            _this.$Message.error(_this.$t(result.msg));
          }
        })
        .catch((err) => {
          _this.loading.close();
          _this.$Message.error("系统异常，请联系管理员！");
        });
    },
    // 开始生产
    startProduct() {
      const _this = this;
      let params = {
        route_code: _this.wkodDetail.route_ordernumber,
        status: 4,
      };
      _this.loading = _this.$loading();
      _this.axios
        .request({
          url: "/CNC/ProductPlanDispatch/WebStart",
          params,
          method: "get",
        })
        .then((res) => {
          _this.loading.close();
          let result = res.data;
          if (result.ret == 1) {
            _this.$Message.success("请开始生产！");
            // 重新刷新一下工单详情
            _this.wkodNo = _this.wkodDetail.route_ordernumber;
            _this.getWkodByQrCode();
          } else {
            _this.$Message.error(_this.$t(result.msg));
          }
        })
        .catch((err) => {
          _this.loading.close();
          _this.$Message.error("系统异常，请联系管理员！");
        });
    },
    // 暂停生产
    pauseProduct() {
      const _this = this;
      let params = {
        route_code: _this.wkodDetail.route_ordernumber,
        status: 9,
      };
      _this.loading = _this.$loading();
      _this.axios
        .request({
          url: "/CNC/ProductPlanDispatch/WebStart",
          params,
          method: "get",
        })
        .then((res) => {
          _this.loading.close();
          let result = res.data;
          if (result.ret == 1) {
            _this.$Message.success("已暂停生产！");
            // 重新刷新一下工单详情
            _this.wkodNo = _this.wkodDetail.route_ordernumber;
            _this.getWkodByQrCode();
          } else {
            _this.$Message.error(_this.$t(result.msg));
          }
        })
        .catch((err) => {
          _this.loading.close();
          _this.$Message.error("系统异常，请联系管理员！");
        });
    },
    // 继续生产
    continueProduct() {
      const _this = this;
      let params = {
        route_code: _this.wkodDetail.route_ordernumber,
        status: 4,
      };
      _this.loading = _this.$loading();
      _this.axios
        .request({
          url: "/CNC/ProductPlanDispatch/WebStart",
          params,
          method: "get",
        })
        .then((res) => {
          _this.loading.close();
          let result = res.data;
          if (result.ret == 1) {
            _this.$Message.success("请继续生产！");
            // 重新刷新一下工单详情
            _this.wkodNo = _this.wkodDetail.route_ordernumber;
            _this.getWkodByQrCode();
          } else {
            _this.$Message.error(_this.$t(result.msg));
          }
        })
        .catch((err) => {
          _this.loading.close();
          _this.$Message.error("系统异常，请联系管理员！");
        });
    },
    // 生产报工
    productReport() {
      const _this = this;
      // 获取程序号与产量下拉列表
      _this.getProgramAndNum();
      _this.programCode = "";
      _this.startTime = "";
      _this.endTime = "";
      _this.number = "";
      _this.okNum = 0;
      _this.noOkNum = 0;
      _this.isShow = true;
    },
    // 获取程序号与产量下拉列表
    getProgramAndNum() {
      const _this = this;
      let data = {
        route_id: _this.wkodDetail.route_id,
        machineId: _this.machineId,
      };
      _this.axios
        .request({
          url: "/CNC/ProductPlanDispatch/GetProgram",
          data,
          method: "post",
        })
        .then((res) => {
          let result = res.data;
          if (result.ret == 1) {
            let data = result.data;
            _this.programList = [];
            if (data && Array.isArray(data) && data.length) {
              _this.programList = data;
            }
          }
        });
    },
    // 监听程序号变化
    handlePgCode(code) {
      const _this = this;
      _this.programList.forEach((v) => {
        if (v.programCode == code) {
          _this.startTime = v.startTime;
          _this.endTime = v.endTime;
          _this.number = v.number;
        }
      });
    },
    // 报工，完工，终止之前
    doSubmit(IsComplete) {
      const _this = this;
      if (_this.flag) {
        return false;
      }
      _this.flag = true;
      setTimeout(() => {
        _this.flag = false;
      }, 2500);
      let { okNum, noOkNum, wkodDetail } = this;
      if (okNum == null) {
        _this.$Message.error("请输入合格数量！");
        return false;
      }
      if (noOkNum == null) {
        _this.$Message.error("请输入不合格数！");
        return false;
      }
      let pNum = okNum + noOkNum + wkodDetail.number;
      let qNum = wkodDetail.quantity;
      // 报工，完工，终止三种情况判断
      if (IsComplete == 0) {
        // 报工
        if (pNum < qNum) {
          if (okNum == 0 && noOkNum == 0) {
            _this.$Message.error("合格数量与不合格数不能同时为0！");
          } else {
            _this.submit(IsComplete);
          }
        } else if (pNum == qNum) {
          IsComplete = 1;
          _this.submit(IsComplete);
        } else if (pNum > qNum) {
          _this.$Message.error("当前报工数已超过计划数量！");
        }
      } else if (IsComplete == 1) {
        // 完工
        _this.$Modal.confirm({
          title: "请确定是否要进行完工操作？",
          content: "",
          width: 320,
          closable: true,
          okText: "确定",
          onOk: () => {
            if (pNum < qNum) {
              if (okNum == 0 && noOkNum == 0) {
                _this.$Message.error("合格数量与不合格数不能同时为0！");
              } else {
                _this.submit(IsComplete);
              }
            } else if (pNum == qNum) {
              _this.submit(IsComplete);
            } else if (pNum > qNum) {
              _this.$Message.error("当前报工数已超过计划数量！");
            }
          },
        });
      } else if (IsComplete == 2) {
        // 终止
        _this.$Modal.confirm({
          title: "请确定是否要进行终止操作？",
          content: "",
          width: 320,
          closable: true,
          okText: "确定",
          onOk: () => {
            if (pNum < qNum) {
              _this.submit(IsComplete);
            } else if (pNum == qNum) {
              IsComplete = 1;
              _this.submit(IsComplete);
            } else if (pNum > qNum) {
              _this.$Message.error("当前报工数已超过计划数量！");
            }
          },
        });
      }
    },
    // 报工，完工，终止
    submit(IsComplete) {
      const _this = this;
      _this.loading = _this.$loading();
      let data = {
        id: _this.wkodDetail.id,
        ok_number: _this.okNum,
        nok_number: _this.noOkNum,
        machineId: _this.machineId,
        IsComplete: IsComplete,
        uid: _this.userId,
        route_ordernumber: _this.wkodDetail.route_ordernumber,
        route_name: _this.wkodDetail.route_name,
        ProgramCode: _this.programCode ? _this.programCode : "",
        startTime: _this.startTime ? _this.startTime : "",
        endTime: _this.endTime ? _this.endTime : "",
        product_number: _this.number ? _this.number : 0,
      };
      _this.axios
        .request({
          url: "/CNC/ProductPlanDispatch/WebProductReportPreservation",
          data,
          method: "post",
        })
        .then((res) => {
          _this.loading.close();
          let result = res.data;
          if (result.ret == 1) {
            _this.$Message.success(_this.$t(result.msg));
            _this.isShow = false;
            // 重新刷新一下工单详情
            _this.wkodNo = _this.wkodDetail.route_ordernumber;
            _this.getWkodByQrCode();
          } else {
            _this.$Message.error(_this.$t(result.msg));
          }
        })
        .catch((err) => {
          _this.loading.close();
          _this.$Message.error("系统异常，请联系管理员！");
        });
    },
    // 取消
    confirmCancel() {
      this.okNum = null;
      this.noOkNum = null;
      this.isShow = false;
    },
    // 预览
    preview() {
      const _this = this;
      let fileUrl = _this.wkodDetail.draw_url;
      let suffix = fileUrl.replace(_this.axios.publicPath, "").split(".")[1];
      if (suffix != "jpg" && suffix != "png" && suffix != "pdf") {
        _this.$Message.error("文件类型不支持预览！");
        return false;
      }
      _this.isPreview = true;
      _this.curFileUrl = fileUrl;
      _this.reset = false;
      _this.$nextTick(() => {
        _this.reset = true;
      });
    },
    // 动态设置 iframe 中样式
    setIframe() {
      const _this = this;
      setTimeout(() => {
        let pic = document.getElementById("pic_iframe");
        if (pic) {
          pic.onload = () => {
            let idoc = pic.contentWindow.document;
            let img = idoc.getElementsByTagName("img")[0];
            console.log(img);
            if (img) {
              img.style.width = "100%";
            }
          };
        }
      }, 0);
    },
  },
};
</script>
<style lang="less" scoped>
.h100 {
  height: 100%;
}
.t_woex {
  height: 100%;
  background-color: #f5f7f9;
  position: relative;
  .no_wkod {
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    .center {
      width: 50%;
      height: 50%;
      text-align: center;
      h1 {
        margin-bottom: 16px;
      }
    }
  }
  .wkod {
    background-color: #fff;
    .wkodDetail {
      padding: 12px 32px;
      h1 {
        font-size: 32px;
        margin-bottom: 16px;
        display: flex;
        align-items: center;
        .sts_1 {
          background-color: #ffb539;
        }
        .sts_2 {
          background-color: #ff9900;
        }
        .sts_3 {
          background-color: #ff5e31;
        }
        .sts_4 {
          background-color: #2d8cf0;
        }
        .sts_5 {
          background-color: #2cc377;
        }
        .sts_6 {
          background-color: #ed4014;
        }
        .sts_7 {
          background-color: #0000ff;
        }
        .sts_8 {
          background-color: #ff7a45;
        }
        .sts_9 {
          background-color: #808695;
        }
      }
      .detail {
        font-size: 24px;
        font-weight: bold;
        .detail_row {
          margin-bottom: 24px;
          label {
            display: inline-block;
          }
          div {
            display: inline-block;
          }
        }
      }
      .btnGroup {
        margin-top: 24px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        flex-wrap: wrap;
        button {
          margin-bottom: 16px;
        }
      }
    }
    .empty {
      background: url("../../static/images/empty.png");
      background-repeat: no-repeat;
      background-position: 50% 50%;
    }
  }
}
.newModalClass label {
  font-size: 18px;
  font-weight: bold;
  width: 135px;
}
.newModalClass .filter {
  display: block;
  height: 50px;
}
.modal_body {
  height: 100%;
}
</style>
