<template>
  <div class="t_admg">
    <div class="btnGroup">
      <Button
        v-for="(v, i) in exception1"
        :key="i"
        size="large"
        type="warning"
        @click="toAndon(v, i)"
        >{{ v.title }}</Button
      >
    </div>
    <div class="andonGroup" v-if="andonList.length">
      <div
        class="andon"
        v-for="(v, i) in andonList"
        :key="i"
        @click="trigger(v)"
      >
        <div v-if="v.status == 2" class="andon_title red">待签到</div>
        <div v-if="v.status == 3" class="andon_title orange">处理中</div>
        <div v-if="v.status == 4" class="andon_title cyan">待复线</div>
        <div class="andon_body">
          <div class="andon_body_row">
            <span class="label">工单编号：</span>
            <span class="text">{{ v.work_order }}</span>
          </div>
          <div class="andon_body_row">
            <span class="label">异常类型：</span>
            <span class="text">{{ v.expection1 }}</span>
          </div>
          <div class="andon_body_row">
            <span class="label">持续时间：</span>
            <span class="text">{{ v.duration }}</span>
          </div>
        </div>
      </div>
    </div>
    <div class="empty andonGroup" v-else></div>
    <Modal v-model="isAndon" title="触发安灯" class="newModalClass">
      <div class="modal_body" v-if="reset">
        <div class="row">
          <div class="filter">
            <label><i>*</i> 一级异常：</label>
            <span class="err_title">{{ err_title }}</span>
          </div>
        </div>
        <div class="row" v-if="exception1[exception1_i]">
          <div class="filter">
            <label><i>*</i>二级异常：</label>
            <Select
              size="large"
              class="searchSelect"
              @on-change="handleException2"
            >
              <Option
                v-for="(v, i) in exception1[exception1_i].children"
                :value="v.id"
                :key="i"
                >{{ v.title }}</Option
              >
            </Select>
          </div>
        </div>
        <div
          class="row"
          v-if="
            exception1[exception1_i] &&
            exception1[exception1_i].children[exception2_i]
          "
        >
          <div class="filter">
            <label>三级异常：</label>
            <Select
              size="large"
              class="searchSelect"
              @on-change="handleException3"
            >
              <Option
                v-for="(v, i) in exception1[exception1_i].children[exception2_i]
                  .children"
                :key="i"
                :value="v.id"
                >{{ v.title }}</Option
              >
            </Select>
          </div>
        </div>
        <div class="row">
          <div class="filter">
            <label>备注：</label>
            <Input
              type="textarea"
              class="searchInput"
              :autosize="{ minRows: 2, maxRows: 2 }"
              v-model="remark"
            />
          </div>
        </div>
      </div>
      <div slot="footer">
        <Button size="large" @click="isAndon = false">取消</Button>
        <Button size="large" type="primary" @click="confirmAndon()">
          确认
        </Button>
      </div>
    </Modal>
    <Modal v-model="isActive" title="处理安灯" class="newModalClass">
      <div class="modal_body">
        <div class="row">
          <div class="filter">
            <label>一级异常：</label>
            <span class="err_title">{{ andon.expection1 }}</span>
          </div>
        </div>
        <div class="row">
          <div class="filter">
            <label>二级异常：</label>
            <span class="err_title">{{ andon.expection2 }}</span>
          </div>
        </div>
        <div class="row">
          <div class="filter">
            <label>三级异常：</label>
            <span class="err_title">{{ andon.expection3 }}</span>
          </div>
        </div>
        <div class="row">
          <div class="filter">
            <label>触发人员：</label>
            <span class="err_title">{{ andon.creator_name }}</span>
          </div>
        </div>
        <div class="row">
          <div class="filter">
            <label>触发时间：</label>
            <span class="err_title">{{ andon.activeTime }}</span>
          </div>
        </div>
        <div class="row">
          <div class="filter">
            <label>持续时长：</label>
            <span class="err_title">{{ andon.duration }}</span>
          </div>
        </div>
      </div>
      <div slot="footer">
        <Button v-if="andon.status == 2" size="large" @click="cancelAndon()">
          取消安灯
        </Button>
        <Button
          v-if="andon.status == 2"
          size="large"
          type="primary"
          @click="triggerAndon(3)"
        >
          异常签到
        </Button>
        <Button
          v-if="andon.status == 3"
          size="large"
          type="error"
          @click="triggerAndon(4)"
        >
          异常解除
        </Button>
        <Button
          v-if="andon.status == 4"
          size="large"
          type="info"
          @click="triggerAndon(8)"
        >
          拒绝复线
        </Button>
        <Button
          v-if="andon.status == 4"
          size="large"
          type="warning"
          @click="triggerAndon(7)"
        >
          让步复线
        </Button>
        <Button
          v-if="andon.status == 4"
          size="large"
          type="success"
          @click="triggerAndon(6)"
        >
          复线
        </Button>
      </div>
    </Modal>
  </div>
</template>
<script>
import moment from "moment";

export default {
  name: "t_admg",
  inject: ["reload"],
  props: {
    curLevel: {
      type: Array,
    },
    levelNums: {
      type: Number,
    },
    signDetail: {
      type: Object,
    },
  },
  data() {
    return {
      // 触发安灯弹框是否显示
      isAndon: false,
      // 处理安灯弹框是否显示
      isActive: false,
      // 一级异常列表
      exception1: [],
      // 一级异常索引
      exception1_i: -1,
      // 二级异常索引
      exception2_i: -1,
      // 三级异常索引
      exception3_i: -1,
      // 触发安灯一级异常文本
      err_title: "",
      // 触发安灯备注
      remark: "",
      // 设备 ID
      machineId: 0,
      // 安灯列表
      andonList: [],
      // 当前要处理的安灯
      andon: {},
      // 刷新
      reset: false,
      // 全屏好看的 Loading
      loading: null,
    };
  },
  mounted() {
    const _this = this;
    // 若当前页面不是从签到签出页面跳转过来的，就返回签到签出页面
    if (!_this.curLevel.length) {
      _this.$router.replace({
        name: "t_sign",
      });
      return false;
    }
    // 获取一级异常
    _this.getException1();
    // 获取当前工位对应的设备 ID
    _this.getWkodBySection();
  },
  methods: {
    // 根据工位 ID 查询该工位下是否有已绑定的工单
    getWkodBySection() {
      const _this = this;
      let params = {
        sectionId: _this.curLevel[_this.curLevel.length - 1],
      };
      _this.axios
        .request({
          url: "/CNC/ProductPlanDispatch/WebScanMachine",
          params,
          method: "get",
        })
        .then((res) => {
          let result = res.data;
          if (result.ret == 1) {
            let data = result.data;
            _this.machineId = data.machineId;
            // 获取安灯列表
            _this.getAndonList();
          }
        });
    },
    // 获取一级异常
    getException1() {
      const _this = this;
      _this.axios
        .request({
          url: "/tpm/AndonBaseSetting/GetExpectionTypeTree",
          method: "get",
        })
        .then((res) => {
          let result = res.data;
          if (result.ret == 1) {
            let data = result.data;
            _this.exception1 = [];
            if (data && Array.isArray(data) && data.length) {
              _this.exception1 = data;
            }
          }
        });
    },
    // 触发安灯
    toAndon(v, i) {
      const _this = this;
      // 复位
      _this.exception1_i = -1;
      _this.exception2_i = -1;
      _this.exception3_i = -1;
      _this.err_title = "";
      _this.remark = "";

      _this.err_title = v.title;
      _this.exception1_i = i;
      _this.isAndon = true;
      // 刷新一下下拉选择框
      _this.reset = false;
      _this.$nextTick(() => {
        _this.reset = true;
      });
    },
    // 监听二级异常
    handleException2(q) {
      const _this = this;
      _this.exception1[_this.exception1_i].children.forEach((v, i) => {
        if (q == v.id) {
          _this.exception2_i = i;
        }
      });
    },
    // 监听三级异常
    handleException3(q) {
      const _this = this;
      _this.exception1[this.exception1_i].children[
        this.exception2_i
      ].children.forEach((v, i) => {
        if (v.id == q) {
          _this.exception3_i = i;
        }
      });
    },
    // 确认安灯
    confirmAndon() {
      const _this = this;
      if (_this.exception1[_this.exception1_i].is_passprocess != 1) {
        if (
          !_this.exception1[_this.exception1_i].children[_this.exception2_i]
        ) {
          _this.$Message.error("请选择二级异常类型！");
          return false;
        }
      }
      let execodid =
        _this.exception1[_this.exception1_i].children[_this.exception2_i].id;
      if (
        _this.exception1[_this.exception1_i].children[_this.exception2_i]
          .children[_this.exception3_i]
      ) {
        execodid =
          _this.exception1[_this.exception1_i].children[_this.exception2_i]
            .children[_this.exception3_i].id;
      }
      if (_this.exception1[_this.exception1_i].is_passprocess == 1) {
        execodid = _this.exception1[_this.exception1_i].id;
      }
      let data = {
        machine: _this.machineId ? _this.machineId : 0,
        expection: execodid,
        is_shutdown: 0,
        remark: _this.remark,
        start: 0,
        end: 0,
      };
      _this.loading = _this.$loading();
      _this.axios
        .request({
          url: "/tpm/andon/AndonTrigger",
          data,
          method: "post",
        })
        .then((res) => {
          let result = res.data;
          if (result.ret == 1) {
            _this.loading.close();
            _this.$Message.success("触发安灯成功！");
            _this.isAndon = false;
            _this.getAndonList();
          } else {
            _this.loading.close();
            _this.$Message.error(_this.$t(result.msg));
          }
        })
        .catch((err) => {
          _this.loading.close();
          _this.$Message.error("系统异常，请联系管理员！");
        });
    },
    // 获取安灯列表
    getAndonList() {
      const _this = this;
      let data = {
        machine: _this.machineId,
        page: 1,
        pagesize: 999999999,
        states: [2, 3, 4],
      };
      _this.loading = _this.$loading();
      _this.axios
        .request({
          url: "/tpm/andon/GetAndonInfo",
          data,
          method: "post",
        })
        .then((res) => {
          _this.loading.close();
          let result = res.data;
          _this.andonList = [];
          if (result.ret == 1) {
            let data = result.data;
            if (data && Array.isArray(data) && data.length) {
              let now = Date.parse(new Date()) / 1000;
              _this.andonList = data.map((v) => {
                let num;
                if (v.status == 1) {
                  num = now - v.abnormal_time <= 0 ? 0 : now - v.abnormal_time;
                } else {
                  num = now - v.create_time <= 0 ? 0 : now - v.create_time;
                }
                v.duration = _this.showTimeStr(num);
                return v;
              });
            }
          }
        })
        .catch((err) => {
          _this.loading.close();
          _this.$Message.error("系统异常，请联系管理员！");
        });
    },
    // 解决安灯
    trigger(v) {
      const _this = this;
      // 复位
      _this.andon = {};
      _this.andon = v;
      _this.andon.activeTime = moment(_this.andon.create_time * 1000).format(
        "YYYY年MM月DD日 HH时mm分ss秒"
      );
      _this.isActive = true;
    },
    // 取消安灯
    cancelAndon() {
      const _this = this;
      let data = {
        id: _this.andon.id,
        status: 9998,
        machine: _this.machineId,
      };
      _this.loading = _this.$loading();
      _this.axios
        .request({
          url: "/tpm/andon/AndonTrigger",
          data,
          method: "post",
        })
        .then((res) => {
          _this.loading.close();
          let result = res.data;
          if (result.ret == 1) {
            _this.$Message.success("取消安灯成功！");
            _this.isActive = false;
            _this.getAndonList();
          } else {
            _this.$Message.error(_this.$t(result.msg));
          }
        })
        .catch((err) => {
          _this.loading.close();
          _this.$Message.error("系统异常，请联系管理员！");
        });
    },
    // 触发安灯状态变化
    triggerAndon(pproctype) {
      const _this = this;
      let data = {
        id: _this.andon.id,
        type: pproctype,
        expection: _this.andon.expection_type,
        remark: "",
        product_code: "",
        start: 0,
        end: 0,
        is_shutdown: 0,
      };
      _this.loading = _this.$loading();
      _this.axios
        .request({
          url: "/tpm/Andon/HandleAndon",
          data,
          method: "post",
        })
        .then((res) => {
          _this.loading.close();
          let result = res.data;
          if (result.ret == 1) {
            _this.$Message.success(_this.$t(result.msg));
            _this.isActive = false;
            _this.getAndonList();
          } else {
            _this.$Message.error(_this.$t(result.msg));
          }
        })
        .catch((err) => {
          _this.loading.close();
          _this.$Message.error("系统异常，请联系管理员！");
        });
    },
    //根据秒求天小时分钟
    showTimeStr(val) {
      if (val < 60) {
        return val + "秒"; //秒
      } 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 + "分" + sec_str;
        } 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 + sec_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 + sec_str;
          }
        }
      }
    },
  },
};
</script>
<style lang="less" scoped>
.t_admg {
  height: 100%;
}
.btnGroup {
  background-color: #ffffff;
  padding: 0 16px;
  border-radius: 8px;
  margin-bottom: 12px;
  height: 110px;
  overflow-y: auto;
  button {
    margin: 8px 24px 8px 0;
    width: 135px;
    font-size: 16px;
  }
}
.andonGroup {
  height: ~"calc(80vh - 125px)";
  overflow-y: auto;
  .andon {
    width: 31%;
    margin: 10px 8px;
    display: inline-block;
    cursor: pointer;
    .andon_title {
      color: #ffffff;
      font-size: 16px;
      padding: 5px 0 5px 14px;
      border-top-left-radius: 8px;
      border-top-right-radius: 8px;
    }
    .andon_body {
      background-color: #ffffff;
      padding: 12px 0 12px 14px;
      border-bottom-left-radius: 8px;
      border-bottom-right-radius: 8px;
      .andon_body_row {
        margin: 10px 0;
        .label {
          color: #b7b7b7;
          font-size: 16px;
        }
        .text {
          color: #5b6577;
          font-size: 16px;
        }
      }
    }
    .green {
      background-color: #19be6b;
    }
    .red {
      background-color: #ed4014;
    }
    .orange {
      background-color: #ff7a45;
    }
    .yellow {
      background-color: #ff9900;
    }
    .cyan {
      background-color: #36cfc9;
    }
    .blue {
      background-color: #2d8cf0;
    }
  }
}
.modal_body {
  .row {
    label {
      font-weight: bold;
      font-size: 16px;
    }
    .err_title {
      font-weight: bold;
      font-size: 16px;
    }
  }
}
.newModalClass .filter {
  height: 44px;
}
.newModalClass .searchSelect {
  width: 200px;
}
.newModalClass .searchInput {
  width: 200px;
}
.empty {
  background: url("../../static/images/empty.png");
  background-repeat: no-repeat;
  background-position: 50% 50%;
}
</style>