<template>
  <div class="t_sign">
    <div v-if="!isLogin || signDetail.type == 0" class="sign">
      <Form :model="signIn" class="w50" @submit.native.prevent>
        <FormItem>
          <Input
            v-focus
            size="large"
            v-if="!isLogin"
            v-model="signIn.qrCode"
            placeholder="请扫描登录二维码"
            @on-change="handleQrCode"
          >
          </Input>
        </FormItem>
        <FormItem>
          <Button
            long
            size="large"
            v-if="!isLogin"
            type="primary"
            @click="clearInput()"
          >
            清空
          </Button>
        </FormItem>
        <FormItem>
          <Button
            long
            size="large"
            type="primary"
            @click="confirmSignIn()"
            v-if="isLogin && isSign == 0 && curLevel.length == levelNums"
          >
            上班签到
          </Button>
        </FormItem>
      </Form>
    </div>
    <div v-else class="sign">
      <Form :model="signDetail" class="w50">
        <FormItem>
          <Input :value="signDetail.name" size="large" readonly></Input>
        </FormItem>
        <FormItem>
          <Input :value="signDetail.time" size="large" readonly></Input>
        </FormItem>
        <FormItem>
          <Button
            long
            size="large"
            type="primary"
            @click="confirmSignOut()"
            v-if="signDetail.type == 1"
            :disabled="curLevel.length != levelNums"
          >
            下班签出
          </Button>
          <Button
            long
            size="large"
            type="primary"
            @click="confirmSignIn()"
            v-if="signDetail.type == 2"
            :disabled="curLevel.length != levelNums"
          >
            上班签到
          </Button>
        </FormItem>
      </Form>
    </div>
  </div>
</template>
<script>
import { getToken, setToken } from "@/libs/util";
import { getsToken, login } from "@/api/user";
import md5 from "js-md5";
import { mapMutations, mapActions } from "vuex";
import { Decrypt, Encrypt } from "./cryptoJs";

export default {
  name: "t_sign",
  inject: ["reload"],
  props: {
    curLevel: {
      type: Array,
    },
    levelNums: {
      type: Number,
    },
    signDetail: {
      type: Object,
    },
  },
  data() {
    return {
      signIn: {
        qrCode: "",
      },
      // 全屏好看的 Loading
      loading: null,
    };
  },
  computed: {
    isLogin() {
      return getToken();
    },
    isSign() {
      return this.signDetail.type;
    },
  },
  directives: {
    focus: {
      inserted: function (el, binding) {
        el.children[1].focus();
      },
    },
  },
  methods: {
    ...mapMutations([
      "setToken",
      "timestamp",
      "nonce",
      "sign",
      "changetimestamp",
      "changeLogin",
      "changenonce",
      "changesign",
    ]),
    ...mapActions(["getUserInfo"]),
    // 监听扫描二维码
    handleQrCode() {
      const _this = this;
      let lgData;
      let isErr = false;
      try {
        lgData = JSON.parse(Decrypt(_this.signIn.qrCode));
      } catch (e) {
        isErr = true;
      }
      if (!isErr) {
        _this.handleSubmit(lgData);
      } else {
        // console.log("解析错误！");
      }
    },
    // 初始化登录
    handleSubmit({ userName, password }) {
      const _this = this;
      userName = userName.trim();
      _this.loading = _this.$loading();
      getsToken()
        .then((res) => {
          if (res.data.ret == 1) {
            let data = res.data.data;
            let timestamp = new Date().getTime();
            let nonce = "";
            for (let i = 0; i < 8; i++) {
              nonce += Math.floor(Math.random() * 10);
            }
            let sign = md5("timestamp=" + timestamp + "&nonce=" + nonce);
            // 存储在 vuex 和 cookie 中
            _this.setToken(data);
            _this.timestamp(timestamp);
            _this.nonce(nonce);
            _this.sign(sign);
            // 存储在 vuex 和 localStorage 中
            _this.changetimestamp({ timestamp: timestamp });
            _this.changeLogin({ token: data });
            _this.changenonce({ nonce: nonce });
            _this.changesign({ sign: sign });
            // 系统架构上感觉有点问题，又存 Cookie 又存 localStorage，完全隔离开来
            // 路由守卫时判断权限用 Cookie
            // 调用接口请求头中用 localStorage
            // 有点混乱了
          } else {
            _this.loading.close();
            _this.$Message.error(_this.$t(result.msg));
            return false;
          }
        })
        .then((res) => {
          login({
            userName,
            password,
          })
            .then((res) => {
              if (res.data.ret == 1) {
                _this
                  .getUserInfo()
                  .then((res) => {
                    _this.loading.close();
                    _this.reload();
                  })
                  .catch((err) => {
                    _this.loading.close();
                    _this.$Message.error("系统异常，请联系管理员！");
                  });
              } else {
                _this.loading.close();
                _this.$Message.error(_this.$t(res.data.msg));
              }
            })
            .catch((err) => {
              _this.loading.close();
              _this.$Message.error("系统异常，请联系管理员！");
            });
        })
        .catch((err) => {
          _this.loading.close();
          _this.$Message.error("系统异常，请联系管理员！");
        });
    },
    // 上班签到
    confirmSignIn() {
      const _this = this;
      if (_this.curLevel.length != _this.levelNums) {
        _this.$Message.error("请选择到具体工位！");
        return false;
      }
      let params = {
        section: _this.curLevel[_this.curLevel.length - 1],
      };
      _this.loading = _this.$loading();
      _this.axios
        .request({
          url: "/CNC/ProduceWorking/ClockWorkings",
          params,
          method: "get",
        })
        .then((res) => {
          _this.loading.close();
          let result = res.data;
          if (result.ret == 1) {
            _this.$Message.success("签到成功！");
            localStorage.setItem(
              "sign_curlevel",
              JSON.stringify(_this.curLevel)
            );
            _this.reload();
          } else {
            if (result.msg == 1000041) {
              _this.$Message.error("抱歉，您没有上机权限！");
            } else if (result.msg == 4000024) {
              _this.$Message.error("该设备已经签到！");
            } else if (result.msg == 9000039) {
              _this.$Message.error("该工位下没有设备，签到失败！");
            } else {
              _this.$Message.error("抱歉，签到失败！");
            }
          }
        })
        .catch((err) => {
          _this.loading.close();
          _this.$Message.error("系统异常，请联系管理员！");
        });
    },
    // 下班签出
    confirmSignOut() {
      const _this = this;
      if (_this.curLevel.length != _this.levelNums) {
        _this.$Message.error("请选择到具体工位！");
        return false;
      }
      let params = {
        section: _this.curLevel[_this.curLevel.length - 1],
      };
      _this.loading = _this.$loading();
      _this.axios
        .request({
          url: "/CNC/ProduceWorking/EndWorkings",
          params,
          method: "get",
        })
        .then((res) => {
          _this.loading.close();
          let result = res.data;
          if (result.ret == 1) {
            _this.$Message.success("签出成功！");
            localStorage.setItem(
              "sign_curlevel",
              JSON.stringify(_this.curLevel)
            );
            _this.reload();
          } else {
            _this.$Message.error(_this.$t(result.msg));
          }
        })
        .catch((err) => {
          _this.loading.close();
          _this.$Message.error("系统异常，请联系管理员！");
        });
    },
    // 清空输入
    clearInput() {
      const _this = this;
      _this.$set(_this.signIn, "qrCode", "");
    },
  },
};
</script>
<style lang="less" scoped>
.t_sign {
  height: 100%;
  background-color: #f5f7f9;
  position: relative;
}
.sign {
  width: 50%;
  height: 50%;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  // transform: translateX(-50%);
  display: flex;
  justify-content: center;
  align-items: center;
}
.w50 {
  width: 66%;
}
</style>
