<template>
  <div class="AllHome">
    <div class="title">登录</div>
    <div class="titleTwo">欢迎使用宏天EIP微办公</div>
    <van-form @submit="onSubmit" validate-trigger="onSubmit">
      <van-field
        v-model="loginForm.account"
        name="账号"
        placeholder="请输入账号"
        :rules="[{ required: true, message: '请输入账号' }]"
      >
        <template #left-icon>
          <i class="icon-wode_nor icon"></i>
        </template>
      </van-field>
      <van-field
        v-model="loginForm.password"
        :type="isShowPassword ? 'text' : 'password'"
        name="密码"
        placeholder="请输入密码"
        clearable
        class="password"
        :rules="[{ required: true, message: '请输入密码' }]"
        @click-right-icon="clickPassword"
      >
        <template #left-icon>
          <i class="icon-mima1 icon"></i>
        </template>
        <template #right-icon>
          <i
            class="icon"
            :class="!isShowPassword ? 'icon-yincang' : 'icon-xianshi'"
          ></i>
        </template>
      </van-field>
      <van-field
        v-if="isShowVerificationCode"
        v-model="loginForm.verificationCode"
        size="large"
        name="验证码"
        left-icon="smile-o"
        placeholder="请输入验证码"
        class="verificationCode"
        :rules="[{ required: true, message: '请输入验证码' }]"
      >
        <template #left-icon>
          <i class="icon-yanzhengma1 icon"></i>
        </template>
        <template #right-icon>
          <van-icon
            class="clearIcon"
            v-if="loginForm.verificationCode"
            name="clear"
            @click="clickIcon"
          />
          <img
            :src="captchaImage"
            width="112px"
            height="32px"
            @click="flushVerCode"
            class="ver-code"
          />
        </template>
      </van-field>

      <div>
        <van-checkbox icon-size="18" v-model="loginForm.checked" shape="square">
          记住密码
        </van-checkbox>
      </div>

      <van-button
        :loading="submitLoading"
        loading-type="spinner"
        round
        block
        type="info"
        native-type="submit"
        class="clickLogin"
      >
        <span>立即登录</span>
      </van-button>
    </van-form>
    <ResetPassword
      ref="ResetPassword"
      :account="loginForm.account"
      :loginPage="true"
      @close="
        () => {
          $router.go(0)
        }
      "
    ></ResetPassword>
  </div>
</template>

<script>
  import ResetPassword from '@/components/ResetPassword.vue'
  import { mapMutations, mapActions, mapState } from 'vuex'
  import { Notify, Dialog } from 'vant'

  import {
    getTenantByCode,
    updateClientInfo,
    bindOpenId,
    bindMpOpenId,
  } from '@/api/uc.js'
  import { getCaptcha } from '@/api/auth.js'

  import { encryptWithRsa, appUpdate } from '@/utils/index.js'

  export default {
    name: 'Login',
    props: {
      tenant: {
        type: String,
        default: 'platform',
      },
    },
    components: { ResetPassword },
    data() {
      return {
        loginForm: {
          account: '',
          password: '',
          verificationCode: '',
          verificationKey: '',
          checked: false,
        },

        captchaImage: '',
        submitLoading: false,
        isShowVerificationCode: false,
        tenantId: '',
        isShowPassword: false,
      }
    },
    created() {
      let loginForm = localStorage.getItem('loginForm')
      if (loginForm) {
        this.loginForm = JSON.parse(loginForm)
      }
    },
    computed: {
      ...mapState('login', ['loginStatus', 'currentUser']),
    },
    watch: {
      loginForm: {
        handler(val) {},
        deep: true,
      },
      isShowVerificationCode(val) {
        if (val) {
          this.$nextTick(() => {
            //获取二维码图片
            this.flushVerCode()
          })
        }
      },
    },
    mounted() {
      this.$storage.set(`loginRoutePath`, this.$route.path)
      //获取租户信息
      this.getTenantInfo()
    },
    methods: {
      ...mapMutations('login', ['setAccount']),
      ...mapActions('login', ['loginByPrincipal']),
      onSubmit() {
        if (this.loginForm.checked) {
          localStorage.setItem(
            'loginForm',
            JSON.stringify({
              account: this.loginForm.account,
              password: this.loginForm.password,
              checked: this.loginForm.checked,
            })
          )
        } else {
          let loginForm = localStorage.getItem('loginForm')
          if (loginForm) {
            localStorage.removeItem('loginForm')
          }
        }

        this.submitLoading = true
        this.setRouterPath()
        const params = {
          username: this.loginForm.account,
          password: encryptWithRsa(this.loginForm.password),
          verificationKey: this.loginForm.verificationKey,
          verificationCode: this.loginForm.verificationCode,
        }

        this.loginByPrincipal({ params, tenantId: this.tenantId })
          .then((res) => {
            if (
              res &&
              res.errorCode &&
              ['4012', '4013'].includes(res.errorCode)
            ) {
              this.$toast.fail(res.message)
              this.isShowVerificationCode = true
              if (this.isShowVerificationCode) {
                this.clickIcon()
                this.flushVerCode()
              }

              // Notify({ type: 'danger', message: res.message })

              return
            } else if (res.errorCode && res.errorCode === '2001') {
              this.isShowVerificationCode = true
              return
            } else {
              if (this.loginStatus) {
                this.isShowVerificationCode = false
                //登录成功后，判断缓存中是否有openid，有则绑定到userUnite的openid属性中，
                //绑定成功后务必删除缓存的openid以免多次绑定。另：openid在wcoa_jump.vue跳转时写入缓存的。
                this.hasOpenId()
                //登录成功后，判断缓存中是否有mpOpenid，有则绑定到userUnite的mpOpenid属性中，
                //绑定成功后务必删除缓存的mpOpenid以免多次绑定。另：openid在miniprogram_jump.vue跳转时写入缓存的。
                this.hasMpOpenId()
                this.isApp()

                this.$route.path !== '/' &&
                  this.$store
                    .dispatch('user/loadCurrentUserDetail')
                    .then((res) => {
                      this.$store.dispatch('user/getCurrent')
                    })
                if(this.$route.query.hasOwnProperty('redirect') && this.$route.query.redirect.indexOf('login')==-1){
                  this.$router.push({path:this.$route.query.redirect})
                }else{
                  this.$router.push({
                  name: 'home',
                  params: {
                    fistLogin: true,
                  },
                })
               }   
              } else {
                this.$toast.fail('该密码不符合密码策略，请重置密码')

                setTimeout(() => {
                  this.$refs.ResetPassword.openResetPasswordDialog()
                }, 1000)
                this.submitLoading = false
              }
            }
          })
          .catch((msg) => {
            this.flushVerCode()
            this.clickIcon()
            if (msg && msg.startsWith && msg.startsWith('timeout of')) {
              msg = '登录超时'
              // Notify({ type: 'danger', message: msg })
              this.$toast.fail(msg)
            }
          })
          .finally(() => {
            this.submitLoading = false
          })
      },
      //是否有openid
      hasOpenId() {
        const openid = this.$storage.session.get('openid')
        if (openid) {
          Dialog.confirm({
            title: '温馨提示',
            message: '是否绑定公众号，以便下次免登录',
          })
            .then(() => {
              this.bindWxOffAcc(openid)
            })
            .catch()
        }
      },
      hasMpOpenId() {
        const mpOpenid = this.$storage.session.get('mpOpenid')
        const hideBindMp = this.$storage.get('hideBindMp')
        if (mpOpenid && !hideBindMp) {
          Dialog.confirm({
            title: '温馨提示',
            message: '是否绑定小程序，以便下次免登录',
            confirmButtonText: '绑定',
            cancelButtonText: '以后再说',
          })
            .then(() => {
              this.bindMiniprogram(mpOpenid)
            })
            .catch((e) => {
              //不绑定企业微信的状态保存在localStorage
              this.$storage.set('hideBindMp', true)
            })
        }
      },
      //在手机app环境中
      isApp() {
        if (window.plus) {
          //把设备信息绑定到用户中，以便进行app消息推送
          const clientInfo = plus.push.getClientInfo()
          if (clientInfo) {
            const data = {
              account: this.principal.account,
              clientToken: clientInfo.token,
              clientId: clientInfo.clientid,
            }
            updateClientInfo(data)
          }
          //把token传给app应用进行保存
          window.uni &&
            uni.postMessage({
              data: {
                action: 'login',
                token: this.currentUser.token,
              },
            })
          setTimeout(() => {
            //检查软件更新
            appUpdate()
          }, 5000)
        }
      },
      getTenantInfo() {
        getTenantByCode(this.tenant).then((res) => {
          if (res && res.state) {
            this.tenantId = res.value.id
            //是否启用图形验证码 0-不启用；1-启用且限制失败次数；2-一直启用
            if (res.value.captchaEnabled && res.value.captchaEnabled === 2) {
              this.isShowVerificationCode = true
            }
          }
        })
      },
      async flushVerCode() {
        //获取二维码图片
        await getCaptcha().then((res) => {
          this.loginForm.verificationKey = res.key
          this.captchaImage = res.image
        })
      },
      setRouterPath() {
        this.setAccount(this.loginForm.account)
        //本地存储路由path
        this.$storage.set(
          `${this.loginForm.account}loginRoutePath`,
          this.$route.path
        )
      },
      bindWxOffAcc(openid) {
        bindOpenId({ account: this.loginForm.account, openid }).then((res) => {
          if (res.state) {
            this.$storage.session.remove('openid')
          }
        })
      },
      bindMiniprogram(mpOpenid) {
        bindMpOpenId({ account: this.loginForm.account, mpOpenid }).then(
          (res) => {
            if (res.state) {
              this.$storage.session.remove('mpOpenid')
            }
          }
        )
      },
      clickPassword() {
        this.isShowPassword = !this.isShowPassword
      },
      clickIcon() {
        this.loginForm.verificationCode = ''
      },
    },
  }
</script>

<style lang="scss" scoped>
  @mixin placeholder {
    color: #cccccc;
    font-weight: 400;
    font-size: 14px;
  }
  .clearIcon {
    margin-right: 5px;
  }
  .AllHome {
    background: url(../assets/images/loginBackground.png);

    height: $vh;
    width: calc(100vw - 48px);
    background-repeat: no-repeat;
    background-size: cover;
    background-attachment: fixed;

    padding: 0 24px 0;
    color: #262626;
    .title {
      font-weight: 800;
      font-size: 24px;
      padding-top: 140px;
    }
    .titleTwo {
      font-weight: 400;
      font-size: 16px;
      margin: 8px 0 56px;
    }
    ::v-deep {
      .van-cell {
        background-color: transparent;
        margin-bottom: 32px;
        padding: 0 0 8px;

        &::after {
          right: 0;
          left: 0;
        }
      }
      .van-field__left-icon {
        margin-right: 8px;
        display: flex;
        justify-content: center;
        align-items: center;
        .van-icon {
          font-size: 22px;
        }
      }
      .password,
      .verificationCode {
        margin-bottom: 42px;
      }

      .van-checkbox {
        padding-top: 8px;
        margin: 0 0 16px;
        .van-icon {
          font-size: 15px;
          width: 18px;
          height: 18px;
          border: 1px solid #e6e6e6;
        }
        .van-checkbox__label {
          font-weight: 500;
          font-size: 14px;
          color: #8c8c8c;
        }
      }
      .clickLogin {
        background: #409eff;
        border-radius: 8px 8px 8px 8px;
        .van-button__text {
          font-weight: bold;
          font-size: 16px;
        }
      }
      input::-webkit-input-placeholder {
        /* 使用webkit内核的浏览器 */
        @include placeholder;
      }
      input:-moz-placeholder {
        /* Firefox版本4-18 */
        @include placeholder;
      }
      input::-moz-placeholder {
        /* Firefox版本19+ */
        @include placeholder;
      }
      input:-ms-input-placeholder {
        /* IE浏览器 */
        @include placeholder;
      }
    }
  }
  ::v-deep .icon {
    font-size: 22px !important;
  }
  ::v-deep .van-field__control {
    font-size: 16px !important;
  }
  ::v-deep {
    .van-icon-clear {
      z-index: 99 !important;
      margin-right: 6px !important;
    }
    .van-field__right-icon {
      display: flex;
      justify-content: center;
      align-items: center;
    }
    input:-webkit-autofill {
      box-shadow: 0 0 0 1000px white inset !important;
    }
    input:-internal-autofill-previewed,
    input:-internal-autofill-selected {
      -webkit-text-fill-color: #262626 !important;
      transition: background-color 5000s ease-in-out 0s !important;
    }

    // input:-webkit-autofill::first-line: {
    // }
  }
</style>
