<template>
  <div class="login">
    <div class="container">
      <div class="ml28">
        <img v-if="logo" :src="logo" alt="logo" class="logo">
        <img :src="require('@/assets/images/title.svg')" class="title" alt="">
      </div>
      <div class="content">
        <van-cell-group>
          <ErrorWrap :error="error.phone !== ''" :error-message="error.phone">
            <van-field
              v-model="phone"
              :left-icon="require('@/assets/icon/icon_telephone.png')"
              placeholder="请输入手机号"
              type="tel"
              clearable/>
          </ErrorWrap>
        </van-cell-group>
        <van-cell-group>
          <ErrorWrap :error="error.captcha !== ''" :error-message="error.captcha">
            <div class="flex">
              <van-field
                v-model="captcha"
                :left-icon="require('@/assets/icon/icon_code.png')"
                placeholder="请输入验证码"
                clearable
                class="code-input"/>
              <div><img :src="codeImg" class="code-img" alt="验证码" @click="getNewGraphic"></div>
            </div>
          </ErrorWrap>
        </van-cell-group>
        <van-cell-group>
          <ErrorWrap :error="error.sms !== ''" :error-message="error.sms">
            <van-field
              v-model="sms"
              :left-icon="require('@/assets/icon/icon_msg_code.png')"
              maxlength="6"
              placeholder="请输入短信验证码"
              type="number"
              clearable>
              <div slot="button" class="send-message" >
                <span v-if="!countDown" @click="getMessage">获取验证码</span>
                <span v-else>{{ timeCount }}s</span>
              </div>
            </van-field>
          </ErrorWrap>
        </van-cell-group>

        <van-checkbox v-model="readAgreement" class="agreement">
          <span class="agreement-text" >我已阅读并同意<a @click="toAgreement($event, 'LoginAgreement')">实名制登记用户协议、隐私政策</a></span>
        </van-checkbox>
        <van-checkbox v-if="!typeToB" v-model="readUserInfoAgreement" class="agreement">
          <span class="agreement-text" >我已阅读并同意<a @click="toAgreement($event, 'RnrPersonUserInfoAgreement')">个人信息保护政策共享条款</a></span>
        </van-checkbox>
        <van-button type="info" class="login-btn" round color="linear-gradient(120deg, #4F4CFB 0%, #376FF4 97%)" @click="logIn">登录</van-button>
      </div>
    </div>
  </div>
</template>

<script>
import { SET_LOGIN_USER_INFO } from '@/store/modules/user'
import { getGraphicToB, getSmsToB, loginToB } from '@/api/loginToB'
import { getGraphic, getSms, login } from '@/api/loginToC'
import { Toast } from 'vant'
import { setToken } from '@/utils/auth'
import ErrorWrap from './components/ErrorWrap.vue'
export default {
  name: 'Login',
  components: {
    ErrorWrap
  },
  data() {
    return {
      logo: this.$store.getters.logo,
      phone: '', // 手机号
      captcha: '', // 图片验证码
      sms: '', // 短信验证码
      readAgreement: false,
      readUserInfoAgreement: false,
      error: {
        phone: '',
        captcha: '',
        sms: ''
      },
      timeCount: 60, // 短信倒计时
      countDown: false, // 是否倒计时
      codeImg: '', // 图形验证码图片
      requestId: '', // 图形验证码对应id
      validateList: { // 输入框验证规则
        'phone': [
          {
            validate: '',
            error: '手机号不能为空'
          },
          {
            validate: /^1(3\d|4[5-9]|5[0-35-9]|6[567]|7[0-8]|8\d|9[0-35-9])\d{8}$/,
            error: '手机号格式有误'
          }
        ],
        'captcha': [{
          validate: '',
          error: '验证码不能为空'
        }],
        'sms': [{
          validate: '',
          error: '短信验证码不能为空'
        }]
      }
    }
  },
  computed: {
    urlName() {
      const urlName = (this.$route.params.name || '').toLowerCase()
      return urlName === 'home' ? 'business' : urlName
    },
    typeToB() {
      return this.urlName === 'business'
    },
    platformSource() {
      return 'H5'
    }

  },
  created() {
    // 获取图形验证码
    this.getNewGraphic()
  },
  methods: {
    // 获取图形验证码
    getNewGraphic() {
      (this.typeToB ? getGraphicToB : getGraphic)({
        platformSource: this.platformSource
      }).then(res => {
        this.codeImg = res.captchaImg
        this.requestId = res.requestId
      })
    },
    // 获取短信验证码
    getMessage() {
      const flag = this.validateRule({
        'phone': this.validateList.phone,
        'captcha': this.validateList.captcha
      })
      if (flag) {
        // 调接口
        (this.typeToB ? getSmsToB : getSms)({
          phone: this.phone,
          captchaImage: this.captcha, // captcha: this.captcha,
          requestId: this.requestId,
          platformSource: this.platformSource
        }).then(res => {
          // 倒计时
          this.countsDown()
          Toast('验证码发送成功！')
        }).catch(() => {
          this.getNewGraphic()
        })
      }
    },
    // 倒计时
    countsDown() {
      this.countDown = true
      const timer = setInterval(() => {
        this.timeCount--
        if (this.timeCount < 0) {
          clearInterval(timer)
          this.timeCount = 60
          this.countDown = false
        }
      }, 1000)
    },
    // 登录
    async logIn() {
      // 登录验证
      const flag = this.validateRule(this.validateList)
      if (flag) {
        if (!this.readAgreement) {
          Toast('请勾选用户协议')
          return
        }
        if (!this.readUserInfoAgreement && !this.typeToB) {
          Toast('请勾选个人信息共享条款')
          return
        }
        // 开始登录
        const res = await (this.typeToB ? loginToB : login)({
          phone: this.phone,
          sms: this.sms,
          platformSource: this.platformSource
        })
        // 设置token
        const token = res.accessToken || res.access_token
        setToken(token)
        // 开始commit数据
        this.$store.commit(`user/${SET_LOGIN_USER_INFO}`, {
          token,
          organId: res.organId,
          organName: res.organName,
          type: this.typeToB ? 'B' : 'C'
        })
        // 跳转页面
        this.$router.push({ name: this.typeToB ? 'Home' : 'UserHome' })
        // if (this.typeToB) {
        //   this.$router.push({ name: 'Home' })
        // } else {
        //   this.$router.push({ name: res.agreement ? 'UserHome' : 'RnrPersonUserInfoAgreement', query: { tenantNo: this.tenantNo }})
        // }
      }
    },
    // 通用输入框验证
    validateRule(rule) {
      var flag = true
      Object.keys(rule).forEach(key => {
        var errorList = []
        rule[key].map(x => {
          if (x.validate === '') {
            if (this[key] === '') errorList.push(x.error)
          } else {
            if (!x.validate.test(this[key])) errorList.push(x.error)
          }
        })
        console.log(errorList, ' errorList')
        this.error[key] = errorList[0] ? errorList[0] : ''
        if (errorList.length > 0) flag = false
      })
      return flag
    },
    toAgreement(e, name) {
      e.stopPropagation()
      this.$router.push({ name })
    }
  }
}
</script>

<style lang="scss">
.login {
  background: url(../../assets/images/bg_login.png) 0 0 no-repeat;
  background-size: 100% 100%;
  height: 100vh;
  .container {
    padding: 0 32px;
    .ml28 {
      margin-left: 28px;
      padding: 170px 0 0;
    }
    .logo {
      width: auto;
      height: 48px;
    }
    .title {
      margin-top: 87px;
      width: 347px;
      height: 47px;
      display: block;
    }
    .content {
      margin-top: 96px;
      .flex {
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        align-items: center;
      }
      .van-cell-group {
        border-radius: 96px;
        background-color: rgba(255, 255, 255, 0);
        .van-field {
          border-radius: 96px;
          height: 96px;
          align-items: center;
          .van-icon__image {
            width: 38px;
            height: 38px;
          }
          input {
            font-size: 30px;
            color: #242424;
          }
        }
        .code-input {
          // width: 490px;
          margin-right: 16px;
        }
        .code-img {
          width: 180px;
          height: 80px;
        }

      }
      .van-hairline--top-bottom::after, .van-hairline-unset--top-bottom::after {
        border: none;
      }
      // .van-checkbox__icon, .van-checkbox__icon--checked {
      //   height: 30px;
      //   .van-icon{
      //     width: 30px;
      //     height: 30px;
      //   }
      //   .van-icon-success::before {
      //     width: 25px;
      //     height: 0px;
      //   }
      // }
      .agreement {
        margin-top: 10px;
      }
      .agreement-text {
          font-size: 24px;
          color: #242424;
          line-height: 30px;
          font-weight: 400;
          a {
            color: #0761F3;
          }
        }
      .login-btn {
        width: 686px;
        height: 96px;
        margin: 88px auto 0;
        display: block;
      }
      .send-message {
        font-size: 30px;
        color: #0761F3;
        font-weight: 400;
      }
    }

  }
}
</style>
