<template>
    <login-content>
        <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form">
            <template v-if="!scanningLogin">
                <div class="zap-2dcode">
                    <!-- <img class="zap-2dcode__text" src="../assets/images/code1_1.png" alt=""> -->
                    <!-- <img class="zap-2dcode__img" src="../assets/images/code1_2.gif" alt="" @click="scanningLogin=true"> -->
                </div>
                <el-tabs v-model="activeName" class="zap-tabs" @tab-click="changeLoginType">
                    <el-tab-pane label="找回密码" name="login_shortMessage">
                        <el-form-item prop="phone" v-if="!passwordUpdate">
                            <el-input v-model="loginForm.phone" type="text" auto-complete="off" placeholder="手机号" maxlength="11">
                                <img slot="prefix" class="zap-login__icon" src="../assets/images/register/icon_mobile.png" alt="">
                            </el-input>
                        </el-form-item>
                        <el-form-item prop="shortMessageCode" v-if="!passwordUpdate">
                            <el-input v-model="loginForm.shortMessageCode" type="text"  maxlength="" auto-complete="off" placeholder="请输入验证码" class="login-code-msg" id="" onkeydown="enterHandler(event)">
                                <img slot="prefix" class="zap-login__icon" src="../assets/images/register/icon_verify.png" alt="">
                                <el-button class="zap-code-button" slot="suffix" @click="sendMessage" :disabled="sendShortMessageBtn">{{codeBtnWord}}</el-button>
                            </el-input>
                        </el-form-item>
                        <el-form-item style="width:100%;" v-if="!passwordUpdate">
                            <el-button :loading="loading"  class="zap-button" size="medium" type="primary" @click.native.prevent="handleLogin">
                                <span v-if="!loading">下 一 步</span>
                                <span v-else>请 稍 后...</span>
                            </el-button>
                        </el-form-item>
                        <el-form-item prop="password" v-if="passwordUpdate">
                            <el-input v-model="loginForm.password" type="text" auto-complete="off" placeholder="密码" maxlength="20">
                                <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
                            </el-input>
                        </el-form-item>
                        <el-form-item prop="again" v-if="passwordUpdate">
                            <el-input v-model="loginForm.again" type="text" auto-complete="off" placeholder="确认密码" maxlength="20">
                                <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
                            </el-input>
                        </el-form-item>
                        <el-form-item style="width:100%;" v-if="passwordUpdate">
                            <el-button :loading="loading"  class="zap-button" size="medium" type="primary" @click.native.prevent="handleUpdate">
                                <span v-if="!loading">下 一 步</span>
                                <span v-else>请 稍 后...</span>
                            </el-button>
                        </el-form-item>
                    </el-tab-pane>
                </el-tabs>
            </template>
        </el-form>

        <!-- 密码登录验证码 -->
        <el-dialog
            title="验证码"
            :close-on-click-modal="false"
            :visible.sync="codeDialogVisible"
            width="30%">
            <el-row type="flex" style="padding: 20px;">
                <el-input v-model="loginForm.code" auto-complete="off" placeholder="验证码" style="width: 53%;" @keyup.enter.native="handleLogin">
                    <img slot="prefix" class="zap-login__icon" src="../assets/images/login/icon_verify.png" alt="">
                </el-input>
                <div class="login-code">
                    <img :src="codeUrl" @click="getCode" class="login-code-img" />
                </div>
            </el-row>
            <el-row slot="footer" class="zap-dialog-footer zap-dialog-footer--small">
                <el-button type="primary" @click="handleImgCodeSubmit">确 定</el-button>
            </el-row>
        </el-dialog>
    </login-content>
</template>
<script>
import { getCodeImg, sendShortMessage, chooseCompanyLogin, forgetUser, updateUser} from "@/api/login";
import { wxImg } from "@/api/system/weChat";
import Cookies from "js-cookie";
import { encrypt, decrypt } from "@/utils/jsencrypt";
import wxlogin from 'vue-wxlogin'
import LoginContent from "@/components/LoginContent/index.vue"
export default {
  components: {
    wxlogin : wxlogin,
    LoginContent: LoginContent
  },
    name: "Login",
    data() {
        return {
            //默认背景图
            activeName: "login_shortMessage",
            baseImg: require('../assets/images/login/login_illustration.png'),
            BackgroundImg : require('../assets/images/login/login_illustration.png'),
            scanningLogin: false, // 是否扫码登陆
            logo: '',
            // baseLogo: require('../assets/images/lgo.png'),
            codeUrl: "",
            cookiePassword: "",
            loginForm: {
                shortMessageCode: '',
                username: "",
                password: "",
                rememberMe: false,
                code: "",
                uuid: "",
                unionId : "",
                type : "2"
            },
            codeBtnWord: '获取验证码', // 获取验证码按钮文字
            waitTime:2, // 获取验证码按钮失效时间
            loginRules: {
                company: [
                    {
                        required: true,
                        trigger: "blur",
                        message: "企业名称不能为空",
                    },
                ],
                username: [
                    {
                        required: true,
                        trigger: "blur",
                        message: "联系人不能为空",
                    },
                ],
                phone: [
                    {
                        required: true,
                        pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
                        trigger: "blur",
                        message: "请输入正确的手机号",
                    },
                ],
                shortMessageCode: [
                    {
                        required: true,
                        trigger: "blur",
                        message: "验证码不能为空",
                    },
                ],
                password: [
                    {
                        required: true,
                        trigger: "blur",
                        message: "密码不能为空",
                    },
                ],
                again: [
                    {
                        required: true,
                        trigger: "blur",
                        message: "确认密码不能为空",
                    },
                ],
            },
            loading: false,
            redirect: undefined,
            wxSrc: require("../assets/images/wx1.png"),
            sendShortMessageBtn : false,
            dialogVisible : false,
            companyList : [],
            chooseCompanyId : '',
            codeDialogVisible: false,
            passwordUpdate: false
        };
    },
    watch: {
        $route: {
            handler: function (route) {
                this.redirect = route.query && route.query.redirect;
            },
            immediate: true,
        },
    },
    created() {
        this.getCode();
        // this.getlistDomain();
    },
    methods: {
      changeImg(){
          this.wxSrc = require("../assets/images/wx.png")
      },
      returnImg(){
          this.wxSrc = require("../assets/images/wx1.png")
      },
      getCode() {
          getCodeImg().then((res) => {
              this.codeUrl = "data:image/gif;base64," + res.img;
              this.loginForm.uuid = res.uuid;
          });
      },
      handleImgCodeSubmit () {
          if (this.activeName === 'login_password') {
              this.handleLogin()
          } else {
              this.sendMessage()
          }
      },
      handleLogin() {
          this.$refs.loginForm.validate((valid) => {
              if (valid) {
                  this.loading = true;
                  // 验证码不能为空
                  if (this.loginForm.shortMessageCode == null || this.loginForm.shortMessageCode == "") {
                    this.msgError("请输入短信验证码!");
                    this.loading = false;
                    return;
                  }
                  forgetUser(this.loginForm).then((res) => {
                    this.loading = false;
                    this.passwordUpdate = true
                    if (res.data.code == "0") {
                        console.log("未认证!")
                        this.$router.push({ path: "/login" });
                    }
                  }).catch(() => {
                    this.loading = false;
                  });
              }
          });
      },
      handleUpdate() {
          this.$refs.loginForm.validate((valid) => {
              if (valid) {
                  this.loading = true;
                  // 验证码不能为空
                  if (this.loginForm.shortMessageCode == null || this.loginForm.shortMessageCode == "") {
                    this.msgError("请输入短信验证码!");
                    this.loading = false;
                    return;
                  }
                  updateUser(this.loginForm).then((res) => {
                    this.loading = false;
                    this.msgSuccess("重置密码成功!");
                    this.$router.push({ path: "/login" });
                  }).catch(() => {
                    this.loading = false;
                  });
              }
          });
      },
      getUrlKey(name) {
          return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ""])[1].replace(/\+/g, '%20')) || null
      },
      changeLoginType(e){

          if (this.activeName === 'login_password') {
              this.loginRules.code = [
                    {
                        required: true,
                        trigger: "change",
                        message: "验证码不能为空",
                    },
                ]
          } else {
              delete this.loginRules.code
          }
        this.getCode();
      },
      sendMessage(){
                  // 验证码不能为空
                  if (this.loginForm.phone == null || this.loginForm.phone == "") {
                    this.msgError("请输入手机号!");
                    this.loading = false;
                    return;
                  }
                  if (this.codeDialogVisible) {
                    if (!this.loginForm.code) {
                        this.loading = false
                        return this.msgError("请输入验证码!");
                    } else {
                        this.codeDialogVisible = false
                    }
                  } else {
                      return this.codeDialogVisible = true
                  }
                  // 调用获取短信验证码接口
                  sendShortMessage(this.loginForm.phone, this.loginForm.code, this.loginForm.uuid).then(response => {
                    this.sendShortMessageBtn = true;
                    this.msgSuccess("发送成功!");

                    // 因为下面用到了定时器，需要保存this指向
                    let that = this
                    that.waitTime = 60;
                    this.codeBtnWord = `${this.waitTime}s 后重新获取`
                    let timer = setInterval(function(){
                        if(that.waitTime>1){
                            that.waitTime--
                            that.codeBtnWord = `${that.waitTime}s 后重新获取`
                        }else{
                            clearInterval(timer)
                            that.codeBtnWord = '获取验证码'
                            that.waitTime = 60
                            that.getCode();
                            that.sendShortMessageBtn = false;
                        }
                    },1000)

                  }).catch((response)=>{
                    this.getCode();
                  });

      },
      chooseLogin(){
        chooseCompanyLogin(this.chooseCompanyId).then(response => {
          if (response.code == "200") {
            // 认证通过
            if (response.data.sysUser.companyStatus == "00") {
                if(this.redirect == '/home'){
                    this.$router.push({ path: "/homePage"+this.redirect || "/" });
                }else{
                    this.$router.push({ path: this.redirect || "/" });
                }
            //   this.$router.push({ path: this.redirect || "/" });
            // 认证未通过
            } else {
              console.log("未认证通过!")
              this.$router.push({ path: "/certification" });
            }
          }
        }).catch((response)=>{

        });
      }
    }
};
</script>
<style rel="stylesheet/scss" lang="scss">
  @import "~@/assets/styles/login.scss";
</style>
