<template>
  <view class="login_box">
    <image class="image" src="https://lihai001.oss-cn-chengdu.aliyuncs.com/public/kk/login-bg.png" mode="">
    </image>

    <view class="cont_box">
      <view class="headline">
        <view class="title">里海数字平台</view>
        <view class="text">输入手机号获取验证码登录</view>
      </view>
      <view class="form_box">
        <view class="from_input">
          <view class="phone_iput">
            <input type="text" placeholder="输入手机号码" class="text_input" v-model="account">
          </view>
          <view class="codeIput_box">
            <input type="text" placeholder="填写验证码" class="codeIput" v-model="captcha">
            <button v-debounce class="code" :disabled="disabled" :class="disabled === true ? 'on' : ''"
              @click="handleVerify">
              {{ text }}
            </button>
          </view>
        </view>
        <view class="protocol">
          <checkbox-group class="checkgroup" @change='isAgree=!isAgree'>
            <checkbox class="checkbox" :checked="isAgree ? true : false" />
            <text class="protocol_text">登录及代表同意<text @click="userAgree" class="font_pro">用户协议</text>与<text
                @click="userPrivacyAgree" class="font_pro">隐私政策</text></text>
          </checkbox-group>
        </view>
        <view class="logon" @click="loginMobile">登录</view>
        <!-- #ifdef APP-PLUS -->
        <view class="iconfont icon-weixin weixin" @click="wxLogin"></view>
        <!-- #endif -->
      </view>
    </view>
    <Verify @success="success" :captchaType="'blockPuzzle'" :imgSize="{ width: '330px', height: '155px' }" ref="verify">
    </Verify>
  </view>
</template>

<script>
  import { commonAuth } from '@/api/public';
  import { loginMobile, registerVerify, getSiteAPI } from '@/api/user'
  import { LOGO_URL, USER_INFO, EXPIRES_TIME } from '@/config/cache';
  import Cache from '@/utils/cache';
  import sendVerifyCode from "@/mixins/SendVerifyCode";
  import Verify from '@/components/verify/verify.vue';
  const BACK_URL = "login_back_url";
  export default {
    mixins: [sendVerifyCode],
    components: {
      Verify
    },
    data() {
      return {
        isAgree: true,
        account: "",
        captcha: '',
        appUserInfo: null, // 微信登录保存的用户信息
      }
    },
    onLoad(e) {
      console.log('options', e)
    },
    methods: {
      // App微信登录
      wxLogin() {
        if (!this.isAgree) return this.$util.Tips({
          title: '请勾选用户协议与隐私政策'
        });
        let self = this
        this.account = ''
        this.captcha = ''
        uni.showLoading({
          title: '登录中'
        })
        uni.login({
          provider: 'weixin',
          // onlyAuthorize: true,
          success: function(loginRes) {
            self.appUserInfo = loginRes
            self.wxLoginApi()
          },
          fail(error) {
            uni.showToast({
              title: '登录失败',
              icon: 'none',
              duration: 2000
            })
          }
        });
      },
      wxLoginApi() {
        const that = this
        console.log('appUserInfo', that.appUserInfo);
        commonAuth({
          auth: {
            type: 'app_wechat',
            auth: {
              code: that.appUserInfo.authResult.access_token,
              openid: that.appUserInfo.authResult.openid,
              phone: this.account,
              // code: '68_CTElk8-PqBEmCksAPUQ8CYBEPbArY6MsSSjn8DjT_ZUhbkpGSwJECWjzYBEmvvkZloz2-E20smA8l7uNhGyGbuzqVxV9wVx-bAazxnSL_Us',
              // openid: "oRrdQt-mZ3UOPossISgiDt-aEWNg",
              // phone: this.account,
            }
          }
        }).then(res => {
          const data = res.data;
          console.log('res', data);
          if (res.data.status == 200) {
            that.$Cache.clear(BACK_URL);
            that.$store.commit("LOGIN", {
              'token': data.result.token,
              'time': data.result.exp
            });
            that.$store.commit("SETUID", data.result.user.uid);
            that.$store.commit('UPDATE_USERINFO', data.result.user);
            let time = data.expires_time - Cache.time();
            // #ifdef MP
            Cache.set(EXPIRES_TIME, data.expires_time, time);
            Cache.set(USER_INFO, data.user, time);
            // #endif
            if (data.user.no_update === 1) {
              uni.navigateTo({
                url: `/pages/users/completeMsg/completeMsg?phone=${data.user.phone}`
              })
              return
            }
            getSiteAPI().then(res => that.$store.commit('setMyInfo', res))
            uni.reLaunch({
              url: '/pages/user/index'
            });
          } else {
            that.auth_token = res.data.result.key;
            that.bindStatus = true;
          }
          uni.hideLoading();
        }).catch(res => {
          uni.hideLoading();
          uni.showToast({
            title: res.message || res,
            icon: 'none',
            duration: 2000
          });
        });
      },
      handleVerify() {
        let that = this;
        if (!that.account) return that.$util.Tips({
          title: '请输入手机号码'
        });
        if (!/^1(3|4|5|7|8|9|6)\d{9}$/i.test(that.account)) return that.$util.Tips({
          title: '请输入正确的手机号码'
        });
        if (!that.isAgree) return that.$util.Tips({
          title: '请勾选用户协议与隐私政策'
        });
        that.$refs.verify.show();
      },
      success(data) {
        this.$refs.verify.hide();
        this.code(data);
      },
      async loginMobile() {
        // 验证码登录
        let that = this;
        if (!that.account) return that.$util.Tips({
          title: '请输入手机号码'
        });
        if (!/^1(3|4|5|7|8|9|6)\d{9}$/i.test(that.account)) return that.$util.Tips({
          title: '请输入正确的手机号码'
        });
        if (!that.captcha) return that.$util.Tips({
          title: '请输入验证码'
        });
        if (!/^[\w\d]+$/i.test(that.captcha)) return that.$util.Tips({
          title: '请输入正确的验证码'
        });
        if (!that.isAgree) return that.$util.Tips({
          title: '请勾选用户协议与隐私政策'
        });
        loginMobile({
            auth_token: uni.getStorageSync('auth_token'),
            phone: that.account,
            sms_code: that.captcha,
            spread: that.$Cache.get("spread"),
            // #ifdef APP-PLUS
            user_type: 'app',
            // #endif
            // #ifdef H5
            user_type: 'h5',
            // #endif
          })
          .then(({
            data
          }) => {
            console.log('验证码登录', data);
            let time = data.expires_time - Cache.time();
            const backUrl = that.$Cache.get(BACK_URL) || "/pages/home/index";
            that.$Cache.clear(BACK_URL);
            that.$store.commit("LOGIN", {
              'token': data.token,
              'time': data.exp
            });
            that.$store.commit("SETUID", data.user.uid);
            that.$store.commit('UPDATE_USERINFO', data.user);
            // Cache.set(EXPIRES_TIME, data.result.expires_time, time);
            // #ifdef MP
            Cache.set(EXPIRES_TIME, data.expires_time, time);
            Cache.set(USER_INFO, data.user, time);
            // #endif
            let method
            let indexPat = ['/pages/home/index', '/pages/order_addcart/order_addcart',
              '/pages/goods_cate/goods_cate',
              '/pages/user/index'
            ]
            if (indexPat.includes(this.getPath(backUrl))) {
              method = 'switchTab'
            } else {
              method = 'navigateTo'
            }
            if (this.getPath(backUrl) === '/pages/users/login/index') {
              uni.switchTab({
                url: '/pages/home/index'
              });
              return
            }
            uni[method]({
              url: backUrl
            });
          })
          .catch(res => {
            that.$util.Tips({
              title: res
            });
          });
      },
      async code(data) {
        let that = this;
        if (!that.account) return that.$util.Tips({
          title: '请输入手机号码'
        });
        if (!/^1(3|4|5|7|8|9|6)\d{9}$/i.test(that.account)) return that.$util.Tips({
          title: '请输入正确的手机号码'
        });
        // if (that.formItem == 2) that.type = "register";
        await registerVerify({
            phone: that.account,
            type: 'login',
            key: that.keyCode,
            // code: that.codeVal,
            toke: data.token,
            captchaType: 'blockPuzzle',
            captchaVerification: data.captchaVerification
          })
          .then(res => {
            that.$util.Tips({
              title: res.message
            });
            that.sendCode();
          })
          .catch(res => {
            that.$util.Tips({
              title: res
            });
          });
      },
      getPath(url) {
        if (url.indexOf("?") != -1) {
          url = url.split("?")[0];
          console.log(url);
        }
        return url
      },
      userAgree() {
        uni.navigateTo({
          url: '/pages/users/user_about/index?from=sys_user_agree'
        })
      },
      userPrivacyAgree() {
        uni.navigateTo({
          url: '/pages/users/user_about/index?from=sys_userr_privacy'
        })
      },
    }
  }
</script>

<style lang="scss">
  page {
    background-color: #fff;
  }

  .login_box {

    .image {
      width: 750rpx;
      height: 812.28rpx;
      position: fixed;
      top: 0;
      left: 0;
      z-index: -1;
    }

    .logon {
      width: 526.32rpx;
      height: 84.21rpx;
      background-color: #009E56;
      border-radius: 100px;
      color: #fff;
      text-align: center;
      line-height: 84.21rpx;
      font-size: 29.82rpx;
      margin-top: 78.95rpx;
      margin-left: 50%;
      transform: translate(-50%);
    }

    .cont_box {
      position: absolute;
      top: 208.77rpx;
      left: 50%;
      transform: translate(-50%);
      width: 682.46rpx;

      .headline {
        margin-left: 43.86rpx;
        color: #fff;

        .title {
          font-size: 45.61rpx;
          font-weight: 700;
        }

        .text {
          font-size: 29.82rpx;
          margin-top: 14.04rpx;
        }
      }

      .form_box {
        margin-top: 196.49rpx;
        width: 682.46rpx;
        height: 701.75rpx;
        padding: 61.4rpx;
        background: #FFFFFF;
        box-shadow: 0px 3px 6px 1px rgba(0, 106, 53, 0.2);
        border-radius: 16px 16px 16px 16px;

        .protocol {
          margin-top: 70.18rpx;
          font-size: 26.32rpx;

          .checkgroup {
            display: flex;
            align-items: center;

            .font_pro,
            .font_pro {
              color: #68A2FF;
            }
          }
        }


        .from_input {

          .phone_iput,
          .codeIput_box {
            display: flex;
            align-items: center;
            height: 87.72rpx;
            border-bottom: 1px solid #b7b7b7;
          }

          .codeIput_box {
            display: flex;
            justify-content: space-between;
            margin-top: 47.37rpx;

            .code {
              font-size: 29.82rpx;
              color: #68A2FF;
            }

            .on {
              color: #AEAEAE;
            }
          }
        }

        .weixin {
          color: #009E56;
          font-size: 45.61rpx;
          margin: 35.09rpx auto;
          width: 87.72rpx;
          height: 87.72rpx;
          text-align: center;
          line-height: 87.72rpx;
          border-radius: 50%;
          background-color: rgba(0, 0, 0, 0.1);
        }
      }
    }
  }
</style>