<template>
  <div class="login-other">
    <div class="left"></div>
    <div class="right">
      <div class="content">
        <p class="title"><img src="../assets/image/logo.svg" alt="">云鹊医工作站</p>
        <div class="input-info" v-if="loginFlag">
          <div class="title-div">
            <p class="title-input">账号登录</p>
            <img src="../assets/image/underline.svg" alt="">
          </div>
          <el-form ref="loginForm" :model="loginData">
            <el-form-item label="" prop="mobile">
              <el-input v-model="loginData.mobile" placeholder="手机号" maxlength="11" :class="{errColor: loginMobileErr}">
                <i slot="prefix" class="el-input__icon my-icon mobile-icon"></i>
              </el-input>
              <p class="err-text" v-show="loginMobileErr"><img src="../assets/image/err-icon.svg" alt="">{{loginMobileErrText}}</p>
            </el-form-item>
            <el-form-item label="" prop="password">
              <el-input v-model="loginData.password" placeholder="密码" type="password" v-if="!showPSW" :class="{errColor: loginPWDErr}">
                <i slot="prefix" class="el-input__icon my-icon password-icon"></i>
                <i @click="showPWSBtn"  slot="suffix" class="el-input__icon my-icon open-eyes-icon"></i>
              </el-input>
              <el-input v-model="loginData.password" placeholder="密码" v-else :class="{errColor: loginPWDErr}">
                <i slot="prefix" class="el-input__icon my-icon password-icon"></i>
                <i @click="hidePWSBtn" slot="suffix" class="el-input__icon my-icon close-eyes-icon"></i>
              </el-input>
              <p class="err-text" v-show="loginPWDErr"><img src="../assets/image/err-icon.svg" alt="">{{loginPWDErrText}}</p>
            </el-form-item>
          </el-form>
          <div class="button-div">
            <div class="forget-password">
              <p @click="goToResetPassword">忘记密码？</p>
            </div>
            <button @click="login">登 录</button>
          </div>
        </div>

        <div class="input-info" v-else>
          <div class="title-div">
            <p class="title-input">重设密码</p>
            <img src="../assets/image/underline.svg" alt="">
          </div>
          <el-form ref="loginForm" :model="resetPassword" >
            <el-form-item label="">
              <el-input v-model="resetPassword.mobile" placeholder="手机号" maxlength="11" :class="{errColor: resetMobileErr}">
                <i slot="prefix" class="el-input__icon my-icon mobile-icon"></i>
              </el-input>
              <p class="err-text" v-show="resetMobileErr"><img src="../assets/image/err-icon.svg" alt="">{{resetMobileErrText}}</p>
            </el-form-item>
            <el-form-item label="">
              <el-input v-model="resetPassword.captchaAnswer" placeholder="图形验证码" :class="{errColor: resetCaptchaErr}" maxlength="5">
                <i slot="prefix" class="el-input__icon my-icon auth-code-icon"></i>
                <img slot="suffix" style="width:90px;height:36px; border:0;" class="image-check-code" :src="captchaImg" @click="getCaptcha" />
              </el-input>
              <p class="err-text" v-show="resetCaptchaErr"><img src="../assets/image/err-icon.svg" alt="">{{resetCaptchaErrText}}</p>
            </el-form-item>
            <el-form-item label="">
              <el-input v-model="resetPassword.authCode" placeholder="短信验证码" :class="{errColor: resetCodeErr}">
                <i slot="prefix" class="el-input__icon my-icon auth-code-icon"></i>
                <i v-if="countDown == 0" @click="getAuthCode" slot="suffix" class="el-input__icon get-auth-code">获取验证码</i>
                <i v-else slot="suffix" class="el-input__icon get-auth-warning">{{countDown}}s后重发</i>
              </el-input>
              <p class="err-text" v-show="resetCodeErr"><img src="../assets/image/err-icon.svg" alt="">{{resetCodeErrText}}</p>
            </el-form-item>
            <el-form-item label="">
              <el-input v-model.lazy="resetPassword.password" placeholder="新密码" type="password" v-if="!showPSW" :class="{errColor: resetPWDErr}">
                <i slot="prefix" class="el-input__icon my-icon password-icon"></i>
                <i @click="showPWSBtn"  slot="suffix" class="el-input__icon my-icon open-eyes-icon"></i>
              </el-input>
              <el-input v-model.lazy="resetPassword.password" placeholder="新密码" v-else :class="{errColor: resetPWDErr}">
                <i slot="prefix" class="el-input__icon my-icon password-icon"></i>
                <i @click="hidePWSBtn" slot="suffix" class="el-input__icon my-icon close-eyes-icon"></i>
              </el-input>
              <p class="err-text" v-show="resetPWDErr"><img src="../assets/image/err-icon.svg" alt="">{{resetPWDErrText}}</p>
            </el-form-item>
          </el-form>
          <div class="button-div">
            <!--<div class="forget-password">
              <p>忘记密码？</p>
            </div>-->
            <button @click="resetPWD">重设密码</button>
            <div class="login-now">
              <p @click="goToLogin">立即登录</p>
            </div>
          </div>
        </div>

      </div>
      <div class="vrcode">
        <img v-show="showVRCode" src="../assets/image/VR-code.svg" alt="">
        <p slot="reference" @mouseenter="showVR"  @mouseleave="closeVR"><img src="../assets/image/VR-mobile.svg" alt="">下载云鹊医app</p>
      </div>
    </div>
  </div>
</template>

<script>
  let vm = null
  import { ssoLogin2, getDeviceInfo } from '@/utils/utils';
  import { getSaasDomain } from '@/utils/index';
  import { mapActions } from 'vuex';
  import md5 from 'js-md5';
  import { handleLogin, handleGetCaptcha, handleGetAuthCode, handleResetPWD, handleAgreement, handleLogout } from '@/utils/account/accountApi';


  export default {
    name: "login",
    data() {
      return {
        loginFlag: true,
        loginData: {},
        resetPassword: {},
        showVRCode: false,
        showPSW: false,
        countDown: 0,
        timer: null,
        loginMobileErr: false,
        loginMobileErrText: '',
        loginPWDErr: false,
        loginPWDErrText: '',
        resetMobileErr: '',
        resetMobileErrText: '',
        resetCodeErr: '',
        resetCodeErrText: '',
        resetPWDErr: '',
        resetPWDErrText: '',
        resetCaptchaErr: '',
        resetCaptchaErrText: '',
        captchaImg: '',
        captchaToken: '',
        // captchaAnswer: '',

      }
    },
    created() {
      ssoLogin2(); //初始化登录信息
      vm = this;
      this.getCaptcha();  // 获取图形验证码

    },
    methods: {
      // 修改token
      ...mapActions([
        'changeToken',
      ]),
      checkPhone(val) {
        if(!(/^1[3456789]\d{9}$/.test(val))) {
          return false;
        } else {
          return true;
        }
      },
      checkPwdVal(val) {
        if(!/(?=.*\d)/.test(val)){
          return false
        }
        if(!/(?=.*[A-Za-z])/.test(val)){
          return false
        }
        if(!/[`~!@#$%^&*()=|{}_+':]/.test(val)){
          return false
        }
        return true
      },
      checkPassword(val) {
        if(val.length < 8 || val.length > 16){
          return false;
        } else {
          return true;
        }
      },
      goToLogin() {
        this.loginFlag = true
        this.resetMobileErr = false;
        this.resetCodeErr = false;
        this.resetPWDErr = false
        this.resetPassword = {}
      },
      goToResetPassword() {
        this.loginFlag = false;
        this.loginMobileErr = false;
        this.loginPWDErr = false
        this.loginData = {}
      },
      showVR() {
        this.showVRCode = true;
      },
      closeVR() {
        this.showVRCode = false;
      },
      showPWSBtn() {
        this.showPSW = true
      },
      hidePWSBtn() {
        this.showPSW = false
      },
      // 获取图形验证码
      getCaptcha(){
        const { config } = this;
        // 发送图形验证码 ajax
        handleGetCaptcha().then(res => {
          // console.log('>>>>>>图形验证码获取  res ', res)
          if(res.code==='000000'){
            this.captchaImg = `data:image/png;base64,${res.data.content}`
            this.captchaToken = res.data.token
          }else{
            this.$message({
              message: res.message,
              type: 'error'
            });
          }
        }).catch(err => {
          this.$message({
            message: '图形验证码获取错误！',
            type: 'error'
          });
        })

      },
      // 忘记密码时 获取短信验证码
      getAuthCode() {
        // debugger;

        if(!this.resetPassword.mobile) {
          this.resetMobileErr = true;
          this.resetMobileErrText = '请输入手机号';
          return;
        } else if(!this.checkPhone(this.resetPassword.mobile)) {
          this.resetMobileErr = true;
          this.resetMobileErrText = '请输入正确的手机号';
          return;
        } else {
          this.resetMobileErr = false;
          this.resetMobileErrText = '';
        }

        if( !this.resetPassword.captchaAnswer ){
          this.resetCaptchaErr = true;
          this.resetCaptchaErrText = '请输入图形验证码';
          return;
        } else {
          this.resetCaptchaErr = false;
          this.resetCaptchaErrText = '';
        }

        // ------------------------  Old  Start-------------------------------
        // let params = {
        //   receiver: this.resetPassword.mobile,
        //   token: localStorage.getItem("token"),
        //   flag:  2, //1表示注册 2表示忘记密码
        //   gaoFlag: 1 ,//1表示saas 2表示高血压项目
        //   deviceInfo: getDeviceInfo()
        // };
        // this.saasPOST('/mobiles/sendCaptchaNew',params, 'application/x-www-form-urlencoded;charset=UTF-8').then(data => {
        //   if (data.mobileFlag == 2) {
        //     this.resetMobileErr = true;
        //     this.resetMobileErrText = '该手机号尚未注册！';
        //     return;
        //   } else {
        //     const TIME_COUNT = 60;
        //     if (!this.timer) {
        //       this.countDown = TIME_COUNT;
        //       this.timer = setInterval(() => {
        //         if (this.countDown > 0 && this.countDown <= TIME_COUNT) {
        //           this.countDown--;
        //         } else {
        //           this.countDown = 0;
        //           clearInterval(this.timer);
        //           this.timer = null;
        //         }
        //       }, 1000)
        //     }
        //   }

        // }).catch( err => {
        //   this.$message({
        //     message: '系统错误！',
        //     type: 'error'
        //   });
        // })
        // ------------------------  Old  End-------------------------------

        // ------------------------  New  Start-------------------------------
        let paramsObj = {
          mobile: this.resetPassword.mobile,
          flag:  4,  // 4 重置密码
          captchaAnswer: this.resetPassword.captchaAnswer,   // 填写的图形验证码
          captchaToken: this.captchaToken,
        };

        let getAuthCodeCB = params => {
          // debugger;
          handleGetAuthCode(params).then(res => {
            // console.log('>>>>>>login  res ', res)
            if (res.code != '000000') {
              this.resetCaptchaErr = true;
              this.resetCaptchaErrText = res.message;
              this.getCaptcha();  // 获取图形验证码
              return;
            } else {
              const TIME_COUNT = 60;
              if (!this.timer) {
                this.countDown = TIME_COUNT;
                this.timer = setInterval(() => {
                  if (this.countDown > 0 && this.countDown <= TIME_COUNT) {
                    this.countDown--;
                  } else {
                    this.countDown = 0;
                    clearInterval(this.timer);
                    this.timer = null;
                  }
                }, 1000)
              }
            }

          }).catch(err => {
            this.$message({
              message: '系统错误！',
              type: 'error'
            });
          })
        };
        this.sendEncryptRequest( paramsObj, getAuthCodeCB)
        // ------------------------  New  End-------------------------------

      },

      login() {
        if(!this.loginData.mobile) {
          this.loginMobileErr = true;
          this.loginMobileErrText = '请输入手机号';
        } else if(!this.checkPhone(this.loginData.mobile)) {
          this.loginMobileErr = true;
          this.loginMobileErrText = '请输入正确的手机号';
        } else {
          this.loginMobileErr = false;
          this.loginMobileErrText = '';
        }
        if(!this.loginData.password) {
          this.loginPWDErr = true;
          this.loginPWDErrText = '请输入密码';
        } else {
          this.loginPWDErr = false;
          this.loginPWDErrText = '';
        }

        if(!this.loginData.mobile||!this.checkPhone(this.loginData.mobile)||!this.loginData.password) {
          return;
        }

        // ------------------------  Old  Start-------------------------------
        // let params = {
        //   mobile: this.loginData.mobile,
        //   OS: localStorage.getItem("OS"),
        //   browser: localStorage.getItem("browser"),
        //   terminalType: localStorage.getItem("terminalType"),
        //   ipAddress: localStorage.getItem("ipAddress"),
        //   password: md5(this.loginData.password).toUpperCase(),
        //   token: localStorage.getItem("token"),
        // };
        // this.saasGET('/registers/saasLogin',params).then(data => {
        //   if (data.mobileFlag == 1) {
        //     /*this.$message({
        //       message: '手机号或密码不正确！',
        //       type: 'error'
        //     });*/
        //     this.loginPWDErr = true;
        //     this.loginPWDErrText = '手机号或密码不正确！';
        //     return;
        //   }
        //   if (data.isExist == 2) {
        //     /*this.$message({
        //       message: '该手机号尚未注册！',
        //       type: 'error'
        //     });*/
        //     this.loginMobileErr = true;
        //     this.loginMobileErrText = '该手机号尚未注册！';
        //     return;
        //   }
        //   localStorage.setItem("token", data.token);
        //   vm.changeToken(data.token)
        //   localStorage.setItem("storageToken", data.token);
        //   localStorage.setItem('doctorId',data.picapDoctor.id);

        //   localStorage.setItem("mobilePhone", params.mobile);
        //   localStorage.setItem("pass", params.password);
        //   sessionStorage.setItem("mobile",params.mobile);
        //   sessionStorage.setItem("pass",params.password);
        //   this.$router.push('/');
        // }).catch( err => {
        //   this.$message({
        //     message: '系统错误！',
        //     type: 'error'
        //   });
        // })
        // ------------------------  Old  End-------------------------------

        // ------------------------  New  Start-------------------------------

        let paramsObj = {
          mobile: this.loginData.mobile,
          password: md5(this.loginData.password).toUpperCase(),
        };
        let loginCB = params => {
          handleLogin(params).then(res => {
            // console.log('>>>>>>login  res ', res)
            if (res.code == '216509' || res.code == '216502' || res.code == '100001' ) {
              this.loginPWDErr = true;
              this.loginPWDErrText = '手机号或密码不正确！';
              return;
            }
            if (res.code == '216508') {
              this.loginMobileErr = true;
              this.loginMobileErrText = '该手机号尚未注册！';
              return;
            }
            // debugger;
            localStorage.setItem("token", res.data.token);
            vm.changeToken(res.data.token)
            localStorage.setItem("storageToken", res.data.token);
            localStorage.setItem('doctorId',res.data.userId);
            localStorage.setItem("mobilePhone", paramsObj.mobile);
            sessionStorage.setItem("mobile",paramsObj.mobile);
            // this.$router.push('/');
            console.log('token',localStorage.getItem('token'))
            console.log('storageToken',localStorage.getItem('storageToken'))
            // alert('登录成功')
            //新增协议校验
            this.checkAgreement();
          }).catch(err => {
            this.$message({
              message: '系统错误！',
              type: 'error'
            });
          })
        };
        this.sendEncryptRequest( paramsObj, loginCB)
        // ------------------------  New  End-------------------------------
      },
      resetPWD() {
        if(!this.resetPassword.mobile) {
          this.resetMobileErr = true;
          this.resetMobileErrText = '请输入手机号';
        } else if(!this.checkPhone(this.resetPassword.mobile)) {
          this.resetMobileErr = true;
          this.resetMobileErrText = '请输入正确的手机号';
        } else {
          this.resetMobileErr = false;
          this.resetMobileErrText = '';
        }

        if( !this.resetPassword.captchaAnswer ){
          this.resetCaptchaErr = true;
          this.resetCaptchaErrText = '请输入图形验证码';
        } else {
          this.resetCaptchaErr = false;
          this.resetCaptchaErrText = '';
        }

        if(!this.resetPassword.authCode) {
          this.resetCodeErr = true;
          this.resetCodeErrText = '请输入验证码';
        } else {
          this.resetCodeErr = false;
          this.resetCodeErrText = '';
        }
        if(!this.resetPassword.password) {
          this.resetPWDErr = true;
          this.resetPWDErrText = '请输入密码';
        } else if(!this.checkPassword(this.resetPassword.password)) {
          this.resetPWDErr = true;
          this.resetPWDErrText = '请输入8-16位的密码';
        } else if(!this.checkPwdVal(this.resetPassword.password)) {
          this.resetPWDErr = true;
          this.resetPWDErrText = '密码须同时包含数字，字母和字符';
        } else {
          this.resetPWDErr = false;
          this.resetPWDErrText = '';
        }
        if(!this.resetPassword.mobile
          ||!this.checkPhone(this.resetPassword.mobile)
          ||!this.resetPassword.captchaAnswer
          ||!this.resetPassword.authCode
          ||!this.resetPassword.password
          ||!this.checkPassword(this.resetPassword.password)
          ||!this.checkPwdVal(this.resetPassword.password)) {
          return;
        }

        // ------------------------  Old  Start-------------------------------

        // let para = {
        //   mobile: this.resetPassword.mobile,
        //   authCode: this.resetPassword.authCode
        // }
        // this.saasGET('/mobiles/checkCaptcha',para).then(data => {
        //   let req = {
        //     mobile: this.resetPassword.mobile,
        //     password: md5(this.resetPassword.password).toUpperCase()
        //   }
        //   this.saasPUT('/login/password',req).then(data => {
        //     this.$message({
        //       message: '重设密码成功，请重新登录！',
        //       type: 'success'
        //     });
        //    setTimeout(function () {
        //      window.location.reload();
        //    }, 2000)
        //   }).catch( err => {
        //     this.$message({
        //       message: '系统错误！',
        //       type: 'error'
        //     });
        //   })

        // }).catch( err => {
        //   /*this.$message({
        //     message: '验证码已过期或不存在！',
        //     type: 'error'
        //   });*/
        //   this.resetCodeErr = true;
        //   this.resetCodeErrText = '验证码已过期或不存在';
        //   return;
        // })
        // ------------------------  Old  End-------------------------------

        // ------------------------  New  Start-------------------------------
        let paramsObj = {
          mobile: this.resetPassword.mobile,
          authCode: this.resetPassword.authCode,
          password: md5(this.resetPassword.password).toUpperCase()
        };
        let resetPWDCB = params => {
          handleResetPWD(params).then(res => {
            // console.log('>>>>>>login  res ', res)
            if(res && res.code == '000000'){
              this.$message({
                message: '重设密码成功，请重新登录！',
                type: 'success'
              });
              setTimeout(function () {
                window.location.reload();
              }, 2000)
            }else{
              this.$message({
                message: (res && res.message) || '系统错误！',
                type: 'error'
              });
            }

          }).catch(err => {
            this.$message({
              message: '系统错误！',
              type: 'error'
            });
          })
        };
        this.sendEncryptRequest( paramsObj, resetPWDCB)

        // ------------------------  New  End-------------------------------
      },
      //新增协议校验
      async checkAgreement() {
        let mobilePhone = localStorage.getItem("mobilePhone");
        if (mobilePhone) {
          let para = {
            mobilePhone:mobilePhone,
            agreementType:1
          };
          await handleAgreement(para).then(res => {
            if (res.code == '000000') {
              const arr = res.data;
              if (arr.length && arr.length == 1) {
                window.location.href = getSaasDomain(`pica-base/pica_do_agree.html?agreementType=${arr[0]}&token=${localStorage.getItem("storageToken")}`);
              } else if (arr.length && arr.length == 2) {
                window.location.href = getSaasDomain(`pica-base/pica_do_agree.html?agreementType=${arr[0]}&agreementType2=${arr[1]}&token=${localStorage.getItem("storageToken")}`);
              } else {
                this.$router.push('/');
              }
            } else {
              // 新增 调用后端退出登录接口
              handleLogout();
              localStorage.removeItem('storageToken')
            }
          }).catch(err => {
            this.$message({
              message: '系统错误！',
              type: 'error'
            });
          })
        }
      },
    }
  }
</script>

<style  lang="scss">

  .login-other {
    .my-icon {
      display: inline-block;
      height: 20px;
      margin-top: 9px;
    }
    .mobile-icon {
      background: url("../assets/image/mobile.svg") no-repeat;
    }
    .password-icon {
      background: url("../assets/image/password.svg") no-repeat;
    }
    .auth-code-icon {
      background: url("../assets/image/auth-code.svg") no-repeat;
    }
    .open-eyes-icon {
      background: url("../assets/image/open-eyes.svg") no-repeat;
      cursor: pointer;
    }
    .close-eyes-icon {
      background: url("../assets/image/close-eyes.svg") no-repeat;
      cursor: pointer;
    }
    .err-text {
      color: #FB5B52;
      height: 20px;
      line-height: 20px;
      margin-top: 4px;
      img {
        width: 14px;
        height: 14px;
        margin-right: 3px;
        vertical-align: middle;
      }
    }
    display: flex;
    height: 100%;
    flex-direction: row;
    .left {
      flex-grow: 1;
      /*大于1441*/
      @media only screen and (min-width: 1441px) {
        background: url("../assets/image/bg-big.png") no-repeat;
        background-size: cover;
      }
      /*小于1440*/
      @media only screen and (max-width: 1441px) {
        background: url("../assets/image/bg-small.png") no-repeat;
        background-size: cover;
      }
    }
    .right {
      position: relative;
      /*大于1441*/
      @media only screen and (min-width: 1441px) {
        width: 570px;
      }
      /*小于1440*/
      @media only screen and (max-width: 1441px) {
        width: 500px;
      }
      .content {
        /*大于1441*/
        @media only screen and (min-width: 1441px) {
          padding: 140px 50px 20px 50px;
        }
        /*小于1440*/
        @media only screen and (max-width: 1441px) {
          padding: 40px 50px 20px 50px;
        }
        .title {
          text-align: center;
          font-weight: 500;
          font-size: 34px;
          color: #333333;
          img {
            width: 54px;
            height: 54px;
            vertical-align: middle;
          }
        }
        .input-info {
          margin-top: 60px;
          .title-div {
            position: relative;
            margin-bottom: 30px;
            .title-input {
              font-size: 28px;
            }
            img {
              display: block;
              position: absolute;
              bottom: 3px;
            }
          }
          .el-form {
            .el-form-item {
              .el-form-item__content {
                position: relative;
                .el-input {
                  .el-input__inner {
                    border-radius: 0;
                    border: none;
                    border-bottom: 1px solid #D9D9D9;
                  }
                  .get-auth-code {
                    color: #666666;
                    cursor: pointer;
                  }
                  .get-auth-warning {
                    color: #666666;
                  }
                }
                .err-text{
                  position: absolute;
                }
                .errColor {
                  .el-input__inner {
                    border-color: #FB5B52;
                  }

                }

              }
            }

          }
          .button-div {
            button {
              width: 100%;
              height: 70px;
              background: #449284;
              color: #ffffff;
              font-size: 24px;
              margin-top: 20px;
              cursor: pointer;
              box-shadow: 0px 10px 8px 0px rgba(59,132,119,0.2);
            }
            .forget-password {
              margin-top: 52px;
              color:red;
              p {
                cursor: pointer;
                width: 80px;
                float: right;
                font-size: 16px;
                color: #449284;
              }
            }
            .login-now {
              margin-top: 24px;
              p {
                width: 80px;
                margin: 0 auto;
                font-size:20px;
                color: #449284;
                cursor: pointer;
              }
            }
          }
        }

      }
      .vrcode {
        position: absolute;
        bottom: 20px;
        width: 100%;
        text-align: center;
        p {
          text-align: center;
          font-size: 20px;
          color: #999999;
          cursor: pointer;
          img {
            vertical-align: middle;
            margin-right: 4px;
          }
        }
      }
    }

  }
</style>
