<!-- 登录页面 -->
<template>
  <el-container class="bgStyle">
    <el-main class="main">
      <el-row
        ><el-col :span="24">
          <h1 class="title">
            <img :src="imgSrc" />
          </h1>
        </el-col>
      </el-row>
      <el-row class="content">
        <el-col :span="10" class="contentChild" :offset="7">
          <el-row>
            <el-col :span="24">
              <h2>账号登录</h2>
              <el-form
                label-position="top"
                :model="ruleForm"
                status-icon
                :rules="rules"
                ref="ruleForm"
                label-width="100px"
                class="demo-ruleForm"
              >
                <el-form-item prop="telephone">
                  <el-input
                    prefix-icon="el-icon-phone"
                    type="text"
                    v-model.trim="ruleForm.telephone"
                    maxlength="11"
                    placeholder="请输入手机号"
                  ></el-input>
                </el-form-item>
                <el-form-item prop="password">
                  <el-input
                    prefix-icon="el-icon-menu"
                    type="password"
                    v-model="ruleForm.password"
                    placeholder="请输入密码"
                  ></el-input>
                </el-form-item>
                <el-form-item prop="randYZM">
                  <el-input
                    prefix-icon="el-icon-picture"
                    v-model="ruleForm.randYZM"
                    class="randFirst"
                    placeholder="请输入验证码"
                  ></el-input>
                  <input
                    type="button"
                    v-model="ruleForm.imageCode"
                    class="rand"
                    @click="createCode"
                  />
                </el-form-item>
                <el-form-item class="noMarginBottom">
                  <el-button
                    class="btnSty"
                    type="primary"
                    @click="submitForm('ruleForm')"
                    >登录</el-button
                  >
                </el-form-item>
                <!-- <el-form-item class="textLeft">
                  <el-checkbox v-model="ruleForm.checked"
                    >下次自动登录</el-checkbox
                  >
                </el-form-item> -->
              </el-form>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
    </el-main>
  </el-container>
</template>

<script>
import md5 from "js-md5";
import { JSEncrypt } from "jsencrypt";
import { login } from "../../api/api";
import axios from 'axios'
import qs from "qs";
export default {
  name: "SignIn",
  data() {
    const validatePhone = (rule, value, callback) => {
      let patter = new RegExp("^1[3|4|5|7|8][0-9]\\d{8}$");
      if (!patter.test(value)) {
        return callback(new Error("请输入正确联系人手机号！"));
      } else {
        callback();
      }
    };
    const validateYZM = (rule, value, callback) => {
      if (value.toUpperCase() != this.ruleForm.imageCode.toUpperCase()) {
        return callback(new Error("请输入正确验证码！"));
      } else {
        callback();
      }
    };
    return {
      imgSrc: require("../../assets/logo.png"), // logo
      ruleForm: {
        telephone: '13000000002', // 手机号
        password: '123456', // 密码
        randYZM: "", // 验证码
        // checked: false, // 下次自动登录
        imageCode: "", // 图片验证码
      },
      secretKey: "6w3lacP9gmjbMgor",
      rules: {
        telephone: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: validatePhone, trigger: "blur" },
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        randYZM: [
          { required: true, message: "请输入验证码", trigger: "blur" },
          { validator: validateYZM, trigger: "blur" },
        ],
      },
      id: 1,
    };
  },
  methods: {
    //  加密
    encryptedData(publicKey, data) {
      // 新建JSEncrypt对象+
      var val = "";
      data = encodeURIComponent(data);
      let arr = Array.apply(null, { length: data.length }).map(
        (item, index) => {
          return index;
        }
      );
      for (var i = 0, j = 0; i < data.length, j < data.length; i++, j++) {
        if (j == publicKey.length) {
          j = 0;
        }
        arr[i] = data.charCodeAt(i) ^ publicKey.charCodeAt(j);
        var strCipher = arr[i].toString(16);
        if (strCipher.length == 1) {
          val += "0" + strCipher;
        } else {
          val += strCipher;
        }
      }
      return val;
    },
    // 解密
    decryptData(privateKey, data) {
      // 新建JSEncrypt对象
      let decrypt = new JSEncrypt();
      // 设置私钥
      decrypt.setPrivateKey(privateKey);
      // 解密数据
      return decrypt.decrypt(secretWord);
    },
    //登录
    submitForm(formName) {
      // var a = this.encryptedData("6w3lacP9gmjbMgor", "13312341234");
      // console.log(a);
      // 验证
      var _this = this;
      _this.$refs[formName].validate((valid) => {
        if (valid) {
          var newsForm = {
            telephone: _this.encryptedData(
              _this.secretKey,
              _this.ruleForm.telephone
            ),
            // telephone: _this.ruleForm.telephone,
            password: md5(_this.ruleForm.password),
            // password: _this.ruleForm.password,
            // pushToken:"6e1c1be58ab4c75f4322963b4b40b7f73bb6c56eea2f0a9fcfdc406e78efbbeb",
            pushToken: _this.encryptedData(
              _this.secretKey,
              _this.ruleForm.telephon
            ),
            phoneType: "1",
            phonemodel: "iPhone12,1",
            code:_this.ruleForm.randYZM
          };
          login(qs.stringify(newsForm)).then(
            function (data) {
              if (data.code == 200) {
                sessionStorage.setItem("token", data.data.token);
                // 记住密码/不记住密码
                // _this.$cookies.set("id", data.data.id);
                // _this.$cookies.set("telephone", _this.ruleForm.telephone);
                // _this.$cookies.set("password", _this.ruleForm.password);
                // _this.$cookies.set("userName", data.data.userName);
                // if (_this.ruleForm.checked) {
                //   //_this.$cookies.set('remPassword',true,{expires:7});
                //   _this.$cookies.set("remPassword", true);
                // } else {
                //   _this.$cookies.set("remPassword", false, { expires: -1 });
                // }
                // 提示信息
                _this.$message({
                  message: "登录成功！",
                  type: "success",
                });
                if (_this.id != null || _this.id != undefined) {
                  let token = data.data.token;
                  sessionStorage.setItem("token", token);
                  sessionStorage.setItem("userinfo", JSON.stringify(data.data));
                  // _this.$cookies.set("factoryList", data.data);
                  // localStorage.setItem("factoryId", data.data.factoryId);
                  // roleId 1:超级管理员 19:厂家管理员
                  if (
                    data.data.roleId == 3 ||
                    data.data.roleId == 4 ||
                    data.data.roleId == 2
                  ) {
                    _this.$router.push({
                      path: "/cardHome",
                      // query: { roleId: data.data.roleId },
                    });
                  } else {
                    _this.$message({
                      message: "请确定该用户是否有登录系统权限！",
                      type: "error",
                    });
                  }
                }
              } else {
                _this.$message({
                  message: data.body.msg,
                  type: "error",
                });
              }
            },
            function () {
              _this.$alert("请求失败，请稍后再试", "提示", {
                confirmButtonText: "确定",
              });
            }
          );
        } else {
          return false;
        }
      });
    },
    createCode() {
      let code = "";
      let codeLength = 4;
      let random = new Array(
        0,
        1,
        2,
        3,
        4,
        5,
        6,
        7,
        8,
        9,
        "A",
        "B",
        "C",
        "D",
        "E",
        "F",
        "G",
        "H",
        "I",
        "J",
        "K",
        "L",
        "M",
        "N",
        "O",
        "P",
        "Q",
        "R",
        "S",
        "T",
        "U",
        "V",
        "W",
        "X",
        "Y",
        "Z"
      ); //随机数
      for (let i = 0; i < codeLength; i++) {
        let index = Math.floor(Math.random() * 36);
        code += random[index];
      }
      this.ruleForm.imageCode = code;
    },
  },
  mounted() {
    // 获取图片验证码
    this.createCode();
    // 判断初始化时cookies时有效的
    let telephone = this.$cookies.get("telephone");
    let password = this.$cookies.get("password");
    if (telephone != "" && this.$cookies.get("remPassword") == "true") {
      this.ruleForm.telephone = telephone;
      this.ruleForm.password = password;
      this.ruleForm.checked = true;
      this.ruleForm.randYZM = this.ruleForm.imageCode;
      this.submitForm("ruleForm"); // 执行登录
    } else {
      this.ruleForm.telephone = "";
      this.ruleForm.password = "";
      this.ruleForm.randYZM = "";
      //this.ruleForm.telephone = '13682152685';
      //this.ruleForm.password = '123456';
      this.ruleForm.checked = false;
    }
    // window.addEventListener('pywebviewready',function(){
      
    // },)
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.bgStyle {
  background: #3b3b3b;
  position: fixed;
  width: 100%;
  height: 100%;
}
.title {
  color: #ffffff;
  font-size: 40px;
  margin: 90px 0 60px 0;
  text-align:center;
}
.title img {
  display: inline-block;
  vertical-align: middle;
  height: 70px;
}
.contentChild {
  background: #e6e6e6;
  border-radius: 3px;
  padding: 60px 50px;
}
.contentChild h2{
  padding: 10px 0;
}
.btnSty {
  width: 100%;
}
.noMarginBottom {
  margin-bottom: 0;
}
.textLeft {
  text-align: left;
}
.randFirst {
  float: left;
  width: 70%;
}
.rand {
  float: left;
  width: 30%;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  line-height: 40px;
  height: 40px;
  background: #ffffff;
  letter-spacing: 4px;
}
</style>
