<template>
  <div class="login" v-show="showPage">
    <h1 class="title">
      全国道路运输企业主要负责人和
      <br />安全生产管理人员安全考核管理
    </h1>
    <div class="login-box">
      <div class="login-hd">
        <h2 class="login-title">绑定</h2>
      </div>
      <div class="login-bd">
        <div class="login-form">
          <!-- 验证码登录 -->
          <code-login ref="form" @submit="onSubmit" v-if="isWechat"></code-login>
          <!-- 账号登录 -->
          <account-login ref="form" @submit="onSubmit" v-else></account-login>
          <div class="login-button" @click="handleSubmit">立即绑定</div>
        </div>
      </div>
      <!-- <div class="login-ft">
        <ul>
          <li @click="wechatLogin">
            <img src="../../assets/images/login_wechat.png" alt="微信登录" />微信登录
          </li>
        </ul>
      </div>-->
    </div>
  </div>
</template>
<script>
import Cookies from 'js-cookie'

import * as api from './api'
import AccountLogin from './components/accountLogin.vue'
import CodeLogin from './components/codeLogin.vue'

export default {
  components: { AccountLogin, CodeLogin },
  data() {
    const UA = navigator.userAgent.toLowerCase()
    return {
      ruleForm: {
        type: 2,
        account: '',
        code: '',
        password: '',
        RememberMe: true,
        service: 'https://h5.ezijing.com'
      },
      passwordVisible: false,
      isWechat: /micromessenger/.test(UA),
      unionid: Cookies.get('wechat_login_no_phone_error')
    }
  },
  computed: {
    isWeapp() {
      return this.$store.state.isWeapp
    },
    // 重定向地址
    redirectURI() {
      const { query } = this.$route
      return query.redirect_uri ? decodeURIComponent(query.redirect_uri) : ''
    },
    showPage() {
      return this.isWechat ? !!Cookies.get('wechat_login_no_phone_error') : true
    }
  },
  methods: {
    handleSubmit() {
      this.$refs.form.submit()
    },
    // 提交
    onSubmit(data) {
      this.unionid ? this.bindWechat(data) : this.loginRequest(data)
    },
    // 登录
    loginRequest(data) {
      const params = Object.assign({}, this.ruleForm, data, { type: 1 })
      api
        .login(params)
        .then(response => {
          this.loginSuccess(response)
        })
        .catch(error => {
          error.response && this.$toast(error.response.data.message)
        })
    },
    // 绑定微信并登录
    bindWechat(data) {
      const params = Object.assign({}, this.ruleForm, data, {
        type: 2,
        identity: 'transport',
        unionid: this.unionid,
        code: data.password,
        forceUpdate: '0'
      })
      api
        .bindWechat(params)
        .then(response => {
          const { code, msg: message } = response
          if (code === 0) {
            this.bindVisitor(() => {
              this.loginSuccess(response)
            })
          } else if (code === 1007) {
            this.$dialog({
              confirmButtonText: '知道了',
              message:
                '您的手机号码已绑定其他微信号码，您可以用绑定的微信号登录后解除绑定或拨打客服电话解除绑定。解绑后再尝试绑定当前的微信号。'
            })
          } else {
            this.$dialog({ message })
          }
        })
        .catch(error => {
          error.response && this.$toast(error.response.data.message)
        })
    },
    // 登录成功
    loginSuccess(response, delta = 2) {
      if (response.code === 0) {
        Cookies.remove('wechat_login_error', { domain: '.ezijing.com' })
        Cookies.remove('wechat_login_no_phone_error', {
          domain: '.ezijing.com'
        })
        this.$store.commit('setToken', response.data.TGC)
        if (this.isWeapp) {
          wx.miniProgram.postMessage({ data: { token: response.data.TGC } })
          wx.miniProgram.navigateBack()
          return
        }
        if (this.redirectURI) {
          window.location.href = this.redirectURI
        } else {
          this.$router.replace('/')
        }
      } else {
        this.$toast(response.msg)
      }
    },
    bindVisitor(callback) {
      const userId = window.localStorage.userId
      if (userId) {
        api.bindVisitor({ user_id: userId }).then(res => {
          callback()
        })
      } else {
        callback()
      }
    },
    wechatLogin() {
      const appId = 'wxc6044475caf2805a'
      const wechatRedirectURL = webConf.others.WECHAT_REDIRECT_URL
      // 回调地址
      const redirectURI = `${wechatRedirectURL}/rest/wechat/oauth-callback?needCheck=false&identity=transport&redirectUrl=${window.location.href}`
      // 微信的地址
      const wechatUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${encodeURIComponent(
        redirectURI
      )}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`
      // 移除cookie
      Cookies.remove('wechat_login_error', { domain: '.ezijing.com' })
      Cookies.remove('wechat_login_no_phone_error', {
        domain: '.ezijing.com'
      })
      // 打开地址
      window.location.href = wechatUrl
    },
    checkWechatLogin() {
      return !!(Cookies.get('wechat_login_error') || Cookies.get('wechat_login_no_phone_error'))
    },
    // 显示登录提示框
    showLoginDialog() {
      this.$dialog.confirm({
        title: '您还未登录',
        message: '请先登录再进行操作',
        cancelButtonText: '暂不登录',
        confirmButtonText: '立即登录',
        beforeClose: (action, done) => {
          if (action === 'confirm') {
            this.wechatLogin()
          } else {
            if (this.isWeapp) {
              wx.miniProgram.postMessage({ data: { token: '' } })
              wx.miniProgram.navigateBack()
            } else {
              this.$router.replace('/')
            }
            done(true)
          }
          done(false)
        }
      })
    }
  },
  beforeMount() {
    this.$store.dispatch('checkLogin').then(isLogin => {
      const TGC = Cookies.get('TGC')
      if (isLogin && TGC) {
        this.loginSuccess({ code: 0, data: { TGC } }, 1)
      } else {
        if (this.isWechat) {
          if (!this.checkWechatLogin()) {
            this.showLoginDialog()
            return
          }
          const error = Cookies.get('wechat_login_error')
          if (error) {
            this.$toast(error)
            Cookies.remove('wechat_login_error', { domain: '.ezijing.com' })
            // wx.miniProgram.navigateBack()
          }
        }
      }
    })
  }
}
</script>
<style lang="scss">
.login {
  position: relative;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  background: url('../../assets/images/login_bg.png') no-repeat;
  background-size: contain;
}
.login-box {
  position: absolute;
  top: 100px;
  left: 50px;
  right: 50px;
  height: 400px;
  padding: 20px;
  background: rgba(255, 255, 255, 1);
  box-shadow: 0px 10px 20px 0px rgba(0, 0, 0, 0.1);
  border-radius: 20px;
}
.login-hd {
  padding: 10px 0;
}
.login-title {
  display: inline-block;
  font-size: 24px;
  color: #c62245;
  border-bottom: 5px solid #c62245;
}
.login-bd {
  margin-top: 20px;
  flex: 1;
}
.login-button {
  margin-top: 40px;
  height: 40px;
  font-size: 12px;
  color: #fff;
  line-height: 40px;
  background: linear-gradient(270deg, rgba(198, 34, 69, 1) 0%, rgba(244, 120, 133, 1) 100%);
  text-align: center;
  border-radius: 3px;
  cursor: pointer;
}
.login-ft {
  padding: 20px 0;
  li {
    display: inline-block;
    height: 30px;
    line-height: 30px;
    font-size: 12px;
    color: #ccc;
    cursor: pointer;
  }
  img {
    width: 30px;
    margin-right: 5px;
  }
}
.login-tips {
  text-align: center;
  font-size: 12px;
  color: #999;
  .forget-password {
    color: #1989fa;
  }
}
.login {
  .title {
    padding: 30px 0;
    font-size: 15px;
    font-weight: 600;
    color: #fff;
    line-height: 30px;
    text-align: center;
  }
  .van-field {
    margin-bottom: 20px;
    padding: 0;
    flex-direction: column;
  }
  .van-field__label {
    font-size: 12px;
    color: #222;
    line-height: 1;
    margin-bottom: 5px;
    padding-left: 10px;
  }
  .van-field__control {
    padding: 8px;
    border: 1px solid #ccc;
    border-radius: 3px;
  }
}
.van-toast--text {
  padding: 20px;
  border-radius: 6px;
}
</style>
