<template>
  <div class="login-container">
    <div class="login-header">
      <div v-if="appCode === 'jyfw'" class="login-header-brand">
        <img src="@/assets/images/login/logo_1.png" >
        <div class="login-header-brand-separator"></div>
        <div class="login-header-title">积余服务平台</div>
      </div>
      <div v-else class="login-header-brand">
        <div class="login-header-title">{{ appName }}</div>
        <div class="login-header-brand-separator"></div>
        <div class="login-header-title">平台</div>
      </div>
      <div class="login-header-download" v-show="showCode">
        <img class="icon-download" src="@/assets/images/login/icon_download.png" >
        <el-popover placement="bottom" trigger="hover">
          <div class="login-header-download-preview">
            <img class="login-header-download-preview-qrcode" :src="androidCode" >
            <div class="login-header-download-preview-tip">请使用手机浏览器或相机扫码下载</div>
          </div>
          <div class="login-header-download-link" slot="reference">Android 管理 APP 下载</div>
        </el-popover>
        <div class="login-header-download-separator"></div>
        <el-popover placement="bottom" trigger="hover">
          <div class="login-header-download-preview">
            <img class="login-header-download-preview-qrcode" :src="iosCode" >
            <div class="login-header-download-preview-tip">请使用手机浏览器或相机扫码下载</div>
          </div>
          <div class="login-header-download-link" slot="reference">IOS 管理 APP 下载</div>
        </el-popover>
      </div>
    </div>
    <div class="login-content">
      <div class="login-con-left">
        <img class="login-con-left-img" src="@/assets/images/login/img_1.png" >
      </div>
      <div class="login-con-right">
        <el-form v-if="!captchaVisible" method="post" :action="actionUrl" target="myIframe" ref="loginForm" id="form" :model="loginForm" :rules="loginRules" class="login-form" autocomplete="off"
          label-position="left" @keyup.enter.native="handleLogin()">
          <div class="con-right-title">
            <!--{{ $t('login.title') }}-->
            你好，欢迎登录
            <div class="btm-icon"></div>
          </div>

          <el-form-item prop="j_username" style="margin-bottom: 20px;">
            <span class="svg-container">
              <svg-icon icon-class="user"/>
            </span>
            <el-input
              v-model.trim="loginForm.j_username"
              placeholder="请输入用户名"
              name="j_username"
              type="text"
              autocomplete="off"
            />
          </el-form-item>

          <el-form-item prop="j_password">
            <span class="svg-container">
              <svg-icon icon-class="password"/>
            </span>
            <el-input
              v-model="loginForm.j_password"
              :type="passwordType"
              placeholder="请输入密码"
              name="j_password"
              autocomplete="new-password"
              @keyup.enter.native="handleLogin"
              class="account user-info"
            />
            <span class="show-pwd" @click="showPwd">
              <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'"/>
            </span>
          </el-form-item>
          <div style="display: flex;align-items: center;">
            <el-input v-model="loginForm.vfCode" placeholder="验证码" class="vcode-input" />
            <img :src="codeSrc"  @click="refreshCode" style="width: 120px;height: 45px;cursor: pointer;">
          </div>
          <el-button :loading="loading" class="login-btn" style="margin-top: 50px;"
            @click.native.prevent="handleLogin">
            登录
          </el-button>
        </el-form>
        <!-- <CaptchaSmsCode v-if="captchaVisible" @back="captchaVisible = false" /> -->
        <div v-if="captchaVisible" class="captcha-container">
          <el-form ref="captchaFormRef" id="captcha-form" :model="captchaForm" :rules="captchaFormRules" class="captcha-form login-form" autocomplete="off" @keyup.enter.native="handleSubmit()">
            <div class="captcha-hd">
              <div class="captcha-hd-title">短信验证</div>
              <div class="captcha-hd-back"><span @click="onAgainLogin"><返回</span></div>
            </div>
            <el-form-item style="margin-bottom: 20px;">
              <span class="svg-container">
                <svg-icon icon-class="user"/>
              </span>
              <el-input
                v-model.trim="captchaForm.mobile"
                placeholder="请输入账号名"
                type="text"
                readonly
                autocomplete="off"
              />
            </el-form-item>
            <div style="display: flex; align-items: center; justify-content: space-between;">
              <el-form-item prop="smsCode" style="margin-bottom: 0; margin-right: 0; border: none; width: auto;">
                <el-input v-model="captchaForm.smsCode" placeholder="短信验证码" class="vcode-input" clearable maxlength="6" />
              </el-form-item>
              <el-button class="captcha-code-btn" type="primary" :disabled="!!isRunning" @click="sendCode">
                {{ isRunning ? `${second}秒后再试` : "获取验证码" }}
              </el-button>
            </div>
            <el-button :loading="loading" class="captcha-login-btn login-btn" @click.native.prevent="handleSubmit">
              登录
            </el-button>
        </el-form>
        </div>
        <iframe name="myIframe" width="500px" height="600" v-show="false"></iframe>
        <!-- <div class="company-tip">Copyright © 2021 SuperDesk</div> -->

      </div>
    </div>
    <div v-if="appCode === 'jyfw'" class="copyright">
      Copyright © 招商积余产业运营股份有限公司版权所有
    </div>
    <el-dialog title="修改密码" :close-on-click-modal="false"  :visible.sync="dialogFormVisible" :show-close=false @close="closeDialog()">
      <el-form :model="form">
        <el-form-item label-width="120px">
          <div class="fz-20 b c-g3 tc">您的密码过于简单，请修改密码后在登录使用!</div>
        </el-form-item>
        <el-form-item label="用户名" label-width="120px">
          <el-input v-model="loginForm.j_username" disabled autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="原密码" label-width="120px">
          <el-input v-model="form.oldPassword" type="password" autocomplete="off" placeholder="请输入原始密码"></el-input>
        </el-form-item>
        <el-form-item label="密码" label-width="120px">
          <el-input v-model="form.password" autocomplete="off" type="password" placeholder="请输入新密码"></el-input>
          <span class="c-g9 fz-12">必须包含大小写字母, 数字</span>
        </el-form-item>
        <el-form-item label="请重复密码" label-width="120px">
          <el-input v-model="form.checkPassword" type="password" autocomplete="off" placeholder="请确认密码" @change="handlePassword"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="surePassword">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import ApiMixin from '../../assets/js/api/index.js'
  import {validUsername} from '@/utils/validate'
  import LangSelect from '@/components/LangSelect'
  import SocialSign from './socialsignin'
  import { setToken } from '@/utils/auth'
  import JSEncrypt from 'jsencrypt'

  export default {
    name: 'Login',
    inject: ['reload'],
    mixins: [ApiMixin],
    components: {LangSelect, SocialSign},
    data() {
      const validateUsername = (rule, value, callback) => {
        // if (!validUsername(value)) {
        //   //callback(new Error('Please enter the correct user name'))
        // } else {
        //   callback()
        // }
        callback()
      }
      const validatePassword = (rule, value, callback) => {
        // if (value.length < 6) {
        //   //callback(new Error('The password can not be less than 6 digits'))
        // } else {
        //   callback()
        // }
        callback()
      }
      return {
        appCode: process.env.APP_CODE,
        appName: process.env.APP_NAME,
        actionUrl: this.axiosURL + `${process.env.BASE_LINk}j_security_check`,
        loginForm: {
          j_username: '',
          j_password: '',
          vfCode: ''
        },
        dialogFormVisible: false,
        codeSrc: '',
        loginRules: {
          username: [{required: true, trigger: 'blur', validator: validateUsername}],
          password: [{required: true, trigger: 'blur', validator: validatePassword}]
        },
        form: {
          id: '',
          oldPassword: '',
          password:'',
          checkPassword: ''
        },
        passwordType: 'password',
        loading: false,
        showDialog: false,
        redirect: undefined,
        qrCodeList: [],
        androidCode: '',
        iosCode: '',
        showCode: true,
        // 短信验证
        token2fa: '',
        captchaVisible: false,
        captchaForm: {
          mobile: '',
          smsCode: ''
        },
        captchaFormRules: {
          smsCode: [
            {
              required: true,
              message: '请输入短信验证码',
            },
          ]
        },
        second: 59,
        isRunning: false,
      }
    },
    watch: {
      $route: {
        handler: function (route) {
          this.redirect = route.query && route.query.redirect
        },
        immediate: true
      }
    },
    created() {
      console.log('当前域名', window.location)
      if (window.location.hostname !== 'localhost' && window.location.protocol === 'http:') {
        location.href = window.location.href.replace('http://', 'https://');
        return;
      }
      this.handleImageCode()
      this.getDictionaryItemByGroupCode()
      // window.addEventListener('hashchange', this.afterQRScan)
    },
    destroyed() {
      // window.removeEventListener('hashchange', this.afterQRScan)
    },
    methods: {
      handleSubmit() {
        this.$refs.captchaFormRef.validate(async (valid) => {
          if (valid) {
            this.signRequest()
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      sendCode() {
        this.isRunning = true;
        this.smsCodeTimer = setInterval(() => {
          if (this.second > 0) {
            this.second--;
          } else {
            this.second = 59;
            this.isRunning = false;
            clearInterval(this.smsCodeTimer);
            this.smsCodeTimer = null;
          }
        }, 1000);

        const params = {
          token2fa: this.token2fa
        };
        this.apiUserSendVerifyCode({
          params
        }).then(res =>{
          if (res && res.code === 200) {
            console.log('验证码发送成功')
          } else if(res.code === 501) {
            // 验证超时
           this.onAgainLogin()
            this.$message({
              type: 'warning',
              message: res.msg,
              duration: 2000
            })
          } else {
            this.$message({
              type: 'warning',
              message: res.msg,
              duration: 2000
            })
          }
        })
      },
      onAgainLogin() {
        this.captchaForm.smsCode = ''
        this.captchaVisible = false
        this.loginForm.vfCode = ''
        this.handleImageCode()
      },
      showPwd() {
        if (this.passwordType === 'password') {
          this.passwordType = ''
        } else {
          this.passwordType = 'password'
        }
      },
      // 刷新图形验证码
      refreshCode() {
        this.handleImageCode()
      },
      async handleImageCode() {
        const res = await axios({
          method: 'post',
          responseType: 'arraybuffer',
          url: '/user/imageCode',
        })
        this.codeSrc = 'data:image/png;base64,' + btoa(new Uint8Array(res.data).reduce((data, byte) => data + String.fromCharCode(byte), ''))
      },
      // 获取二维码展示
      async getDictionaryItemByGroupCode() {
        const res = await this.$store.dispatch('getDictionaryItemByGroupCode',{
          groupCode: 'DOWNLOAD_MANAGER_APP'
        })
        if (res && res.code === 200) {
          this.qrCodeList = res.data;
          this.androidCode = this.qrCodeList[0].url
          this.iosCode = this.qrCodeList[1].url
          if(this.androidCode){
            this.showCode = true
          }else{
            this.showCode = false
          }
        }
      },
      // 关闭弹窗
      closeDialog() {
        this.loading = false
        this.form =  {
          oldPassword: '',
          password:'',
          checkPassword: ''
        }
      },
      handlePassword() {
        if (this.form.password !== this.form.checkPassword) {
          return this.$message({
            type: 'warning',
            message: '两次输入的密码不一致',
            duration: 2000
          })
        }
      },
      logout() {
        this.$store.dispatch('LogOut').then(() => {
          location.reload()// In order to re-instantiate the vue-router object to avoid bugs
        })
      },
      async surePassword() {
        this.handlePassword()
        const params = {
          userId: this.form.id,
          oldPassword: this.form.oldPassword,
          password: this.form.password
        }
        const res = await this.apiEditPassword({
          params
        })
        if (res && res.code === 200) {
          this.dialogFormVisible = false
          this.$message({
            type: 'success',
            message: '修改成功',
            duration: 2000
          })
          this.logout()
        } else {
          this.$message({
            type: 'warning',
            message: res.msg,
            duration: 2000
          })
        }
      },
      stringBase64(str) {
        return window.btoa(unescape(encodeURIComponent(str)));
      },
      async oldLign (strToken, id) {
        const params = {
          j_username: 'token!' + strToken,
          j_password:  strToken
        }
        const res = await this.userLogin({
          params
        })
        this.getOfficeUrlData(id);
        this.loadRoleUser()
        this.loadMenuTree()
        this.$message({
          type: 'success',
          message: '登录成功',
          duration: 2000
        })
        this.loading = false
        this.$router.push({path:'/'})
      },
      async loadRoleUser() {
        const url = this.axiosURL + `${process.env.BASE_LINk}admin/ajax/loadRoleUser`
        axios.post(url).then(function(res){
          console.log("loadRoleUser",res.data.passType)
          sessionStorage.setItem("passType",res.data.passType)
          localStorage.setItem('passType',res.data.passType)
        })
      },
      async loadMenuTree() {
        const url = this.axiosURL + `${process.env.BASE_LINk}admin/ajax/loadMenuTree`
        const res = await axios.post(url)
        console.log('res', res)
        if (res && res.length) {
          this.$router.push({path:'/'})
        }
      },
      async save() {
        // const url ='http://wx.palmnest.com/super_service/j_security_check'
        // axios.post(`${url}`, {
        //   loginName: this.loginForm.j_username,
        //   password:  this.loginForm.j_password,
        // })
        const loginForm = document.getElementById('form')
        loginForm.submit()
        // this.signRequest()
      },
      async getOfficeUrlData(id){
        const res = await this.getOfficeUrl({
          params: {
                userId: id
              }
        })
          if (res && res.code === '200') {
            localStorage.setItem('meetingUrl', res.data.meetingUrl)
            localStorage.setItem('postUrl', res.data.postUrl)
            localStorage.setItem('tsbyHeadUrl', res.data.tsbyHeadUrl)
            localStorage.setItem('wjdcHeadUrl', res.data.wjdcHeadUrl)
          } else {
            localStorage.setItem('meetingUrl', null)
            localStorage.setItem('postUrl', null)
            localStorage.setItem('tsbyHeadUrl', null)
            localStorage.setItem('wjdcHeadUrl', null)
          }
      },
      async getKey() {
        let encrypt = new JSEncrypt();
        const res = await this.getPublicKey({})
        if (res && res.code === 200) {
          encrypt.setPublicKey(res.data);
          const params = {
            loginName: encrypt.encrypt(this.loginForm.j_username),
            password:  encrypt.encrypt(this.loginForm.j_password),
            vfCode: this.loginForm.vfCode
          }
          this.signRequest(params)
        }
      },
      async signRequest(params) {
        this.loading = true
        // const params = {
        //   loginName: this.loginForm.j_username,
        //   password:  this.loginForm.j_password,
        //   vfCode: this.loginForm.vfCode
        // }
        console.log('params', params)
        const res = await this.apiUserSignLoginV2({
          params
        })
        if (res && res.code === 600) {
          this.form.id = res.data.id
          this.dialogFormVisible = true
          return false
        }
        if (res && res.data && res.code === 200) {
            localStorage.setItem('userToken', res.data.userToken)
            localStorage.setItem("userName", res.data.userName);
            LocalForage.setItem('companyId', res.data.companyId);
            localStorage.setItem("realName", res.data.realName);
            localStorage.setItem("userId",res.data.id);
            localStorage.setItem("virtId",res.data.virtId);
            localStorage.setItem("isAgentVirt", res.data.isAgentVirt)
            // localStorage.setItem("orgId",(res.data.orgList && res.data.orgList[0]) ? res.data.orgList[0] : '');
          if(res.data.userType > 2){//项目管理员
            //userType 用户类型:1-admin，2-系统管理员 3-项目管理员 4-普通用户 5-企业账号 6-运营中心管理员 7-运营中心普通管理员8-配送员9-商户
            localStorage.setItem("userType", res.data.userType);
            localStorage.setItem("client",res.data.client);
            if(res.data.orgList&&res.data.orgList.length == 1){
              localStorage.setItem("orgId",res.data.orgList[0]);
              LocalForage.setItem('orgId', res.data.orgList[0]);
            }
            if (res.data.client != ''&&res.data.client != null&&res.data.client != undefined) {
              localStorage.setItem('client', res.data.client);
            }
          } else {
            localStorage.setItem("userType", null);
            localStorage.setItem("orgId", null);
            LocalForage.setItem('orgId', null);
            localStorage.setItem('client', '');
          }
          setToken(res.data.token)
          // setTimeout(() => {
          //   this.$router.push({path:'/'})
          // }, 1500)
          // this.oldLign(res.data.token, res.data.id);
          this.$message({
            type: 'success',
            message: '登录成功',
            duration: 2000
          })
          this.loading = false
          this.$router.push({path:'/'})
        } else {
          this.loading = false
          this.handleImageCode()
          this.$message({
            type: 'warning',
            message: res.msg,
            duration: 2000
          })
        }
      },
      handleLogin() {
        this.$refs.loginForm.validate(async (valid) => {
          if (valid) {
            // this.loading = true
            await this.getKey()
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      afterQRScan() {
        // const hash = window.location.hash.slice(1)
        // const hashObj = getQueryObject(hash)
        // const originUrl = window.location.origin
        // history.replaceState({}, '', originUrl)
        // const codeMap = {
        //   wechat: 'code',
        //   tencent: 'code'
        // }
        // const codeName = hashObj[codeMap[this.auth_type]]
        // if (!codeName) {
        //   alert('第三方登录失败')
        // } else {
        //   this.$store.dispatch('LoginByThirdparty', codeName).then(() => {
        //     this.$router.push({ path: '/' })
        //   })
        // }
      }
    }
  }
</script>
 
<style rel="stylesheet/scss" lang="scss" scoped>

  .captcha {
    &-hd {
      display: flex;
      align-items: center;
      margin-bottom: 40px;
      font-weight: bold;
      font-size: 24px;
      color: #000;

      &-title {
        flex: 1;
      }

      &-back {
        font-weight: normal;
        font-size: 18px;
        color: #004889;
        cursor: pointer;
      }
    }

    &-code-btn {
      padding: 0;
      border: none;
      width: 120px;
      height: 50px;
      line-height: 50px;
      background: #004889;
      font-size: 16px;
      color: #fff;
      text-align: center;
      border-radius: 6px;
      cursor: pointer;
      outline: none;

      &.is-disabled {
        color: #fff;
        background-color: #80a4c4;
        border-color: #80a4c4;
      }
    }

    &-login-btn {
      margin-top: 120px;
    }

    &-form {
      /deep/ .el-form-item__error {
        padding-top: 10px;
      }
    }
  }

  .login-container {
    box-sizing: border-box;
    position: relative;
    min-height: 100%;
    width: 100%;
    padding: 60px;
    overflow: hidden;
    background: linear-gradient(120deg, #00498e, #009BDE);
  }

  .login-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    color: #fff;

    &-brand {
      display: flex;
      align-items: center;
      justify-content: flex-start;
      font-size: 30px;

      &-separator {
        margin-left: 15px;
        margin-right: 15px;
        width: 1px;
        height: 24px;
        background: #ffffff;
      }
    }

    &-download {
      display: flex;
      align-items: center;

      &-preview {
        text-align: center;
        width: 180px;
        padding: 0 15px;
        
        &-qrcode {
          width: 150px;
        }
      }

      &-link {
        font-size: 20px;
        color: #fff;
        cursor: pointer; 
      }
    
      &-link:hover {
        opacity: .7;
      }

      &-separator {
        margin-left: 8px;
        margin-right: 8px;
        width: 1px;
        height: 16px;
        background: #ffffff;
      }

    }
    .icon-download {
      width: 24px;
      height: 24px;
      margin-right: 8px;
    }
  }
 

  .login-content {
    height: 80%;
    width: 100%;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .login-con-left {
    margin-right: 180px;

    &-img {
      width: 750px;
    }
  }
  .login-con-right {
    box-sizing: border-box;
    width: 460px;
    height: 445px;
    padding: 40px;
    background: #ffffff;
    box-shadow: 0px 3px 7px 0px #005f8d;
    border-radius: 10px;

    &-img {
      width: 750px;
    }
  }

  .login-form {

    /deep/ .el-form-item {
      box-sizing: border-box;
      margin-bottom: 20px;
      width: 100%;
      border-radius: 6px;
      border: 1px solid #e0e0e0;
    }

    /deep/ .el-input {
      width: 85%;

      input {
        font-size: 16px;
        background: transparent;
        border: 0px;
        -webkit-appearance: none;

        &:-webkit-autofill {
          -webkit-box-shadow: 0 0 0 1000px #fff inset !important;
        }
      }
    }
  }

  .vcode-input.el-input {
    margin-right: 10px;
    width: 240px;
    height: 50px;
    line-height: 50px;
    font-size: 16px;
    border-radius: 6px;
    border: 1px solid #e0e0e0;
  }

  .con-right-title {
    font-size: 26px;
    color: #000;
    line-height: 35px;
    text-align: center;
    font-weight: 600;
    margin-bottom: 40px;
  }

  .login-btn {
    padding: 0;
    border: none;
    width: 380px;
    height: 50px;
    line-height: 50px;
    background: #004889;
    font-size: 20px;
    color: #fff;
    text-align: center;
    border-radius: 6px;
    cursor: pointer;
    outline: none;
  }

  .copyright {
    position: absolute;
    left: 0;
    bottom: 0;
    width: 100%;
    height: 85px;
    line-height: 85px;
    text-align: center;
    font-size: 18px;
    color: #000000;
    background: #fff;
  }

  
            .svg-container {
      padding: 8px 5px 8px 15px;
      color: #889aa4;
      vertical-align: middle;
      width: 30px;
      display: inline-block;
    }
 
    .show-pwd {
      position: absolute;
      right: 10px;
      top: 7px;
      font-size: 16px;
      color: #889aa4;
      cursor: pointer;
      user-select: none;
    }
</style>
