<template>
    <login-content>
        <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" style="margin-top: 75px;">
            <template v-if="!scanningLogin">
                <el-tabs v-model="activeName" class="zap-tabs" @tab-click="changeLoginType">
                    <el-tab-pane label="账号注册" name="login_shortMessage">
                        <el-form-item prop="company">
                            <el-input v-model="loginForm.company" type="text" auto-complete="off" placeholder="企业名称" maxlength="15">
                                <img slot="prefix" class="zap-login__icon" src="../assets/images/register/icon_business.png" alt="">
                            </el-input>
                        </el-form-item>
                        <el-form-item prop="username">
                            <el-input v-model="loginForm.username" type="text" auto-complete="off" placeholder="联系人" maxlength="15">
                                <img slot="prefix" class="zap-login__icon" src="../assets/images/register/icon_account.png" alt="">
                            </el-input>
                        </el-form-item>
                        <el-form-item prop="phone">
                            <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">
                            <el-input v-model="loginForm.shortMessageCode" type="text"  maxlength="" auto-complete="off" placeholder="请输入验证码" id="" class="login-code-msg"  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 prop="password">
                            <el-input v-model="loginForm.password" type="password" auto-complete="off" placeholder="密码" maxlength="12">
                                <img slot="prefix" class="zap-login__icon" src="../assets/images/register/icon_pwd.png" alt="">
                            </el-input>
                        </el-form-item>
                        <el-form-item prop="again">
                            <el-input v-model="loginForm.again" type="password" auto-complete="off" placeholder="确认密码" maxlength="12">
                                <img slot="prefix" class="zap-login__icon" src="../assets/images/register/icon_pwd.png" alt="">
                            </el-input>
                        </el-form-item>
                        <el-form-item>
                            <el-checkbox v-model="loginForm.checked" style="margin-bottom: 10px;margin-right: 10px;">
                            </el-checkbox>
                            <div class="zap-agreement">
                                <span class="zap-agreement__text">我已阅读</span>
                                <div class="zap-agreement__link">
                                    <span>《招采云链服务平台会员注册协议》</span>
                                    <span>《招采云链服务平台隐私政策》</span>
                                </div>
                            </div>
                        </el-form-item>
                        <el-form-item style="width:100%;">
                            <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-tab-pane>
                </el-tabs>
            </template>
        </el-form>
        <el-dialog
            title="选择企业"
            :visible.sync="dialogVisible"
            width="30%">
            <el-select v-model="chooseCompanyId" placeholder="请选择">
            <el-option
                v-for="item in companyList"
                :key="item.scyId"
                :label="item.scyName"
                :value="item.scyId">
            </el-option>
            </el-select>
            <span slot="footer" class="dialog-footer">
            <el-button type="primary" @click="chooseLogin()">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 密码登录验证码 -->
        <el-dialog
            title="验证码"
            :close-on-click-modal="false"
            :visible.sync="codeDialogVisible"
            width="30%">
            <div style="display:flex;">
                <el-input v-model="loginForm.code" auto-complete="off" placeholder="验证码" @keyup.enter.native="handleLogin">
                    <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />
                </el-input>
                <div class="login-code">
                    <img :src="codeUrl" @click="getCode" class="login-code-img" />
                </div>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button type="primary" @click="handleImgCodeSubmit">确 定</el-button>
            </span>
        </el-dialog>
    </login-content>
</template>
<script>
import { getCodeImg, sendShortMessage, chooseCompanyLogin, registerUser} 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() {
        const equalToPassword = (rule, value, callback) => {
            if (this.loginForm.password !== value) {
                callback(new Error("两次输入的密码不一致"));
            } else {
                callback();
            }
        };
        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", "change"],
                        message: "企业名称不能为空",
                    },
                ],
                username: [
                    {
                        required: true,
                        trigger:["blur", "change"],
                        message: "联系人不能为空",
                    },
                    {
                        pattern:/^[\u4e00-\u9fa5_a-zA-Z]+$/,
                        trigger: ["blur", "change"],
                        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", "change"],
                        message: "请输入正确的手机号",
                    },
                ],
                shortMessageCode: [
                    {
                        required: true,
                        trigger:["blur", "change"],
                        message: "验证码不能为空",
                    },
                ],
                password: [
                    {
                        required: true,
                        pattern: /^(?=.*[a-zA-Z])(?=.*[0-9])[A-Za-z0-9]{6,12}$/,
                        trigger: ["blur", "change"],
                        message: "密码必须由字母、数字组成，区分大小写",
                    },
                ],
                again: [
                    {
                        required: true,
                        trigger: "blur",
                        message: "确认密码不能为空",
                    },
                    { required: true, validator: equalToPassword, trigger: "blur" }
                ],
            },
            loading: false,
            redirect: undefined,
            wxSrc: require("../assets/images/wx1.png"),
            sendShortMessageBtn : false,
            dialogVisible : false,
            companyList : [],
            chooseCompanyId : '',
            codeDialogVisible: 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() {
          //先清空
          this.$set(this.loginForm, "code","");
          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;
                  }
                  if (!this.loginForm.checked) {
                    this.msgError("请阅读平台协议并确认");
                    this.loading = false;
                    return;
                  }
                  this.loginForm.type = "2";
                  registerUser(this.loginForm).then((res) => {
                    this.loading = false;
                    this.msgSuccess("注册成功");
                    if (res.data.code == "0") {
                         setTimeout(() => {
                              this.$router.push({ path: "/login" });
                        }, 5000);
                    }
                  }).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>
