<template>
  <div
    id="login"
    class="login-page"
  >
    <div
      class="login-container"
      :class="this.isLogin?'login-container-height':'forget-container-height'"
    >
      <div class="header">进项发票管理系统</div>
      <div
        class="login-content"
        v-if="this.isLogin"
      >
        <div class="login-type is-login">
          <span>登录</span>
        </div>
        <ai-form
          :key="formLoginKey"
          ref="loginForm"
          :rules="rules"
          :model="formLogin"
          @submit.native.prevent
        >
          <ai-form-item prop="username">
            <ai-input
              placeholder="请输入账号"
              v-model.trim="formLogin.username"
              auto-complete="off"
              prefix-icon="ai-iconfont-zhanghao"
            ></ai-input>
          </ai-form-item>
          <ai-form-item prop="password">
            <ai-input
              placeholder="请输入密码"
              type="password"
              v-model.trim="formLogin.password"
              auto-complete="off"
              prefix-icon="ai-iconfont-mima"
            ></ai-input>
          </ai-form-item>
          <ai-form-item prop="code">
            <ai-input
              @keyup.enter.native="submitLogin"
              :maxlength="code.len"
              v-model="formLogin.code"
              auto-complete="off"
              placeholder="请输入验证码"
              prefix-icon="ai-iconfont-yanzhengma"
            >
              <template
                slot="append"
                class="ai-input-identify"
              >
                <span
                  @click="refreshCode"
                  v-if="code.type == 'text'"
                >{{code.value}}</span>
                <span
                  @click="refreshCode"
                  v-else
                >
                  <ai-identify
                    :identifyCode="code.value"
                    :contentWidth="96"
                    :contentHeight="52"
                  ></ai-identify>
                </span>
              </template>
            </ai-input>
          </ai-form-item>
          <ai-form-item>
            <ai-button
              type="primary"
              @click="submitLogin"
            >登录</ai-button>
          </ai-form-item>
          <div
            class="forget-psd"
            @click="forgetPassword"
          >忘记密码</div>
        </ai-form>
      </div>
      <div
        class="forget-content"
        v-if="this.isForget"
      >
        <div
          class="login-type is-forget"
          @click="toLogin"
        >
          <span>&lt; 已有账号，马上登录</span>
        </div>
        <ai-form
          :key="formForgetKey"
          ref="forgetForm"
          :rules="rules"
          :model="formForget"
          @submit.native.prevent
        >
          <ai-form-item prop="tel">
            <ai-input
              v-model.trim="formForget.tel"
              clearable
              placeholder="请输入手机号"
              prefix-icon="ai-icon-mobile-phone"
            ></ai-input>
          </ai-form-item>
          <ai-form-item prop="validCode">
            <ai-row :gutter="30">
              <ai-col :span="16">
                <ai-input
                  v-model="formForget.validCode"
                  clearable
                  maxlength="4"
                  placeholder="请输入验证码"
                  prefix-icon="ai-iconfont-yanzhengma"
                ></ai-input>
              </ai-col>
              <ai-col :span="8">
                <ai-button
                  type="primary"
                  class="forget-code"
                  @click="getValidCode"
                >{{buttonName}}</ai-button>
              </ai-col>
            </ai-row>

          </ai-form-item>
          <ai-form-item prop="newPassword">
            <ai-input
              v-model.trim="formForget.newPassword"
              clearable
              type="password"
              placeholder="请输入新密码"
              autocomplete="off"
              prefix-icon="ai-iconfont-mima"
            ></ai-input>
          </ai-form-item>
          <ai-form-item prop="newPassword2">
            <ai-input
              @keyup.enter.native="submitForget"
              v-model.trim="formForget.newPassword2"
              clearable
              type="password"
              placeholder="请确认新密码"
              autocomplete="off"
              prefix-icon="ai-iconfont-mima"
            ></ai-input>
          </ai-form-item>
          <ai-form-item>
            <ai-button
              class="submit-btn"
              type="primary"
              @click="submitForget"
            >确认</ai-button>
          </ai-form-item>
        </ai-form>
      </div>
    </div>
  </div>
</template>

<script>
/* eslint-disable */
require("particles.js");
import config from "./config/default";
import util from "@/libs/util";
import { getValidCode, forgetPassword } from "@/api/sys/login";
import { mapActions } from "vuex";
import AiIdentify from "./components/identify/Identify.vue";
export default {
  components: {
    AiIdentify
  },
  data() {
    const validateCode = (rule, value, callback) => {
      if (value !== this.code.value) {
        callback(new Error("验证码输入错误"));
      } else {
        callback();
      }
    };
    const validateNewPwd = (rule, value, callback) => {
      let pwdRule = /^(?![a-zA-z]+$)(?!\d+$)(?![!@#$%^&*]+$)[a-zA-Z\d!@#$%^&*]+$/;
      if (value === "") {
        callback(new Error("请输入新密码"));
      } else if (value.length < 8 || value.length > 20) {
        callback(new Error("密码长度在8~20位之间"));
      } else if (!pwdRule.test(value)) {
        callback(new Error("密码至少要包含数字、字母及字符中的两种"));
      } else {
        if (this.formForget.newPassword2 !== "") {
          this.$refs.forgetForm.validateField("newPassword2");
        }
        callback();
      }
    };
    const validateNewPwd2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请确认新密码"));
      } else if (value !== this.formForget.newPassword) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    const validateTel = (rule, value, callback) => {
      let telRule = /^[1](([3][0-9])|([4][5-9])|([5][0-3,5-9])|([6][5,6])|([7][0-8])|([8][0-9])|([9][1,8,9]))[0-9]{8}$/;
      if (value === "") {
        callback(new Error("请输入手机号"));
      } else if (!telRule.test(value)) {
        callback(new Error("请输入正确的手机号"));
      } else {
        callback();
      }
    };
    return {
      // 快速选择用户
      dialogVisible: false,
      //登录key
      formLoginKey: "formLoginKey",
      //忘记密码key
      formForgetKey: "formForgetKey",
      //忘记密码
      isForget: false,
      //button
      buttonName: "获取验证码",
      //发送短信间隔时间（秒）
      time: 60,
      //是否可用
      isDisabled: false,
      //登录
      isLogin: true,
      passwordType: "password",
      users: [
        {
          name: "管理员",
          username: "admin",
          password: "admin"
        }
      ],
      // 表单
      formLogin: {
        username: "",
        password: "",
        code: "",
        randomStr: ""
      },
      //  忘记密码
      formForget: {
        tel: "",
        validCode: "",
        newPassword: "",
        newPassword2: ""
      },
      code: {
        src: process.env.VUE_APP_API + "/upms/validate/code",
        value: "",
        len: 4,
        type: "image",
        url: process.env.VUE_APP_API + "/upms/validate/code"
      },
      // 校验
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 8, message: "密码长度最少为8位", trigger: "blur" }
        ],
        code: [
          { required: true, message: "请输入验证码", trigger: "blur" },
          { min: 4, max: 4, message: "验证码长度为4位", trigger: "blur" },
          { validator: validateCode, trigger: "blur" }
        ],
        tel: [{ validator: validateTel, trigger: "blur" }],
        validCode: [
          { required: true, message: "请输入验证码", trigger: "blur" },
          { min: 4, max: 4, message: "验证码长度为4位", trigger: "blur" }
        ],
        newPassword: [{ validator: validateNewPwd, trigger: "blur" }],
        newPassword2: [{ validator: validateNewPwd2, trigger: "blur" }]
      }
    };
  },
  created() {
    this.refreshCode();
  },
  mounted() {
    // 初始化例子插件
    //particlesJS('login', config)
  },
  beforeDestroy() {
    // 销毁 particlesJS
    // thanks https://github.com/d2-projects/d2-admin/issues/65
    // ref https://github.com/VincentGarreau/particles.js/issues/63
    if (pJSDom && pJSDom.length > 0) {
      pJSDom[0].pJS.fn.vendors.destroypJS();
      pJSDom = [];
    }
  },
  methods: {
    ...mapActions("d2admin/account", ["login"]),
    //刷新验证码
    refreshCode() {
      this.formLogin.code = "";
      //生成验证码
      this.code.value = util.makeCode(4);
    },
    showPassword() {
      this.passwordType === ""
        ? (this.passwordType = "password")
        : (this.passwordType = "");
    },
    /**
     * @description 提交登录表单
     */
    submitLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          // 登录
          this.formLogin.vm = this;
          this.login(this.formLogin).then(
            res => {
              // 判断是否已经注册
              //this.$router.push({ path: this.tagWel.value });
              //this.$router.push({ path: "/registerverify" });
            },
            error => {
              this.refreshCode();
            }
          );
        }
      });
    },
    submitForget() {
      this.$refs.forgetForm.validate(valid => {
        if (valid) {
          forgetPassword(
            "sms",
            this.formForget.tel,
            this.formForget.validCode,
            this.formForget.newPassword,
            this.formForget.tel
          ).then(ref => {
            if (ref) {
              this.$message.success(ref);
              //重新登录
              this.toLogin();
            }
          });
        }
      });
    },
    getValidCode() {
      if (!this.checkTel(this.formForget.tel)) {
        this.$message.error("请输入正确的手机号");
        return false;
      }
      let type = "sms";
      let use = "forget";
      let me = this;
      getValidCode(type, me.formForget.tel, use).then(ref => {
        console.info(ref);
        if (ref) {
          me.isDisabled = true;
          let interval = window.setInterval(function() {
            me.buttonName = "" + me.time + "s重新发送";
            --me.time;
            if (me.time < 0) {
              me.buttonName = "重新发送";
              me.time = 60;
              me.isDisabled = false;
              window.clearInterval(interval);
            }
          }, 1000);
        }
      });
    },
    forgetPassword() {
      this.isForget = true;
      this.isLogin = false;
      this.resetForm("forgetForm");
      this.formForget = {
        tel: "",
        validCode: "",
        newPassword: "",
        newPassword2: ""
      };
    },
    toLogin() {
      this.isForget = false;
      this.isLogin = true;
      this.resetForm("loginForm");
      this.formLogin = {
        username: "",
        password: "",
        code: "",
        randomStr: ""
      };
    },
    checkTel(tel) {
      var telRule = /^[1](([3][0-9])|([4][5-9])|([5][0-3,5-9])|([6][5,6])|([7][0-8])|([8][0-9])|([9][1,8,9]))[0-9]{8}$/;
      return telRule.test(tel);
    },
    //    重置
    resetForm(formName) {
      this.$nextTick(() => {
        this.$refs[formName].resetFields();
      });
    }
  }
};
</script>

<style lang="scss" scoped>
@import "./style.scss";

$input-height: 52px;

.i-input-identify {
  border: none;
}
/deep/.ai-input--prefix .ai-input__inner {
  padding-left: 56px;
}
/deep/.ai-input__prefix {
  color: #66b1ff;
  font-weight: bold;
  margin-left: 12px;
}
/deep/.ai-input__inner {
  height: $input-height !important;
  font-size: 14px;
  color: #999999;
}
/deep/.ai-input__icon {
  height: 100%;
  font-size: 16px;
  text-align: center;
  line-height: $input-height;
}
/deep/.ai-button {
  height: $input-height !important;
  width: 100%;
  font-size: 18px;
}
/deep/.ai-input-group__append {
  border: none;
  background: transparent;
  padding: 0px 0px 0px 18px;
}
/deep/.ai-form-item {
  margin-bottom: 24px !important;
}
.ai-input-identify {
  cursor: pointer;
  span {
    height: 100%;
  }
}
.submit-btn {
  margin-top: 12px !important;
}
</style>
