<template>
  <view class="login-box">
    <view class="login-title">商家登录</view>
    <view class="logo">
      <image src="@/static/index/merchant.png" mode="aspectFit"></image>
    </view>
    <view class="desc">
      <image src="@/static/index/desc-merchant.png"></image>
    </view>
    <view class="form">
      <view class="form_item">
        <image class="img1" src="@/static/login/phone.png"></image>
        <input class="inp1" placeholder-class="pl" type="text" v-model="phone" placeholder="请输入用户名"
          @input="onInput" />
      </view>
      <view class="form_item">
        <image class="img1" src="@/static/login/password.png"></image>
        <input class="inp1" password="true" placeholder-class="pl" type="text" v-model="password" placeholder="请输入密码" />
      </view>
      <view class="form_item">
        <image class="img1" src="@/static/login/password.png"></image>
        <input class="inp1" \placeholder-class="pl" type="text" v-model="code" placeholder="请输入验证码" />
        <image class="img2" :src="codeUrl" @click="getCode"></image>
      </view>
    </view>
    <view style="padding-top: 76rpx;">
      <button class="btn" @click="userLogin()">登录</button>
      <button class="btn" @click="goBack">返回</button>
    </view>
    <!-- #ifdef MP-WEIXIN -->
    <!-- <view class="other-login" @click="getUserProfile()">
      <view class="ol-tilte">
        <text>快捷登录</text>
      </view>
      <div class="wx-login">
        <image src="@/static/login/weixin_icon.png" mode="aspectFit" />
      </div>
    </view> -->
    <!-- #endif -->
    <image class="bottom_img" src="@/static/login/bottom_img.png" mode="widthFix" />

    <view class="popup-box" v-show="showPopup">
      <view class="login-popup">
        <view class="lp-top">
          <view class="lpt-left">
            <view class="title"> <text>登录</text> </view>
            <view class="tips"> <text>登录即可解锁更多权益</text> </view>
          </view>
          <view class="lpt-right" @click="showPopup=false">
            <image src="@/static/login/close_icon.png" mode="aspectFill"></image>
          </view>
        </view>

        <view class="lp-center">
          <view class="title">申请获取以下权限</view>
          <view class="tips">获得你的公开信息（昵称、头像等）</view>
          <view class="tips">获得你的手机号码</view>
        </view>

        <view class="lp-bottom">
          <!-- getUserInfo -->
          <button class="option-btn" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">
            获取手机号
          </button>
        </view>
      </view>
    </view>

  </view>
</template>

<script>
  import {
    mapState,
    mapMutations
  } from 'vuex';
  import appConfig from "@/config/appConfig.js";
  export default {
    data() {
      return {
        phone: 'admin',
        password: '',
        code: '',
        uuid: '',
        appConfig,
        showLoding: true, // 初始化加载时显示遮挡页
        wxUserInfo: null, // 保存微信用户数据(临时)
        wxLoginInfo: {
          code: null,
          openid: null,
          session_key: null
        }, // 微信登录返回信息（临时）
        showPopup: false, // 获取电话弹窗
        codeUrl: ''
      }
    },
    onLoad() {
      this.initLogin();
      this.getCode()
    },
    onBackPress() {
      //  console.log(e)
      // 这里可以自定义返回逻辑，比如下面跳转其他页面
      uni.navigateTo({
        url: '/pages/login/index'
      });
      // return true 表示禁止默认返回
      return true
    },
    computed: {
      ...mapState(['token'])
    },
    methods: {
      ...mapMutations(['saveUserInfo', 'sessionToken']),
      getCode() {
        this.request("get", "captchaImage").then(res => {
          this.codeUrl = "data:image/gif;base64," + res.data.img;
          this.uuid = res.data.uuid
        });
      },
      userLogin() {
        if (this.phone === '') {
          uni.showToast({
            title: '请输入正确的手机号',
            icon: 'none'
          })
          return false;
        }
        if (this.password == '') {
          uni.showToast({
            title: '请输入密码',
            icon: 'none'
          })
          return false;
        }
        let params = {
          username: this.phone,
          password: this.password,
          ip: '',
          code: this.code,
          uuid: this.uuid
        }
        let that = this
        that.request("post", "login", null, params).then(res => {
          if (res.code === 200) {
            // 返回带token, 进入订单页
            let duration = 1500; // 延迟跳转页面
            that.saveUserInfo(res.data); // 缓存用户基础数据
            that.sessionToken(res.data.token); // 缓存token
            uni.showToast({
              title: '登录成功',
              duration
            })
            that.toTaskPage(duration);
          } else {
            this.getCode()
          }
        }, () => this.getCode())
      },
      /* 判断是否已登录 */
      async initLogin() {
        try {
          let that = this
          if (that.token) {
            let newUserData = await that.getUserInfo();
            if (newUserData) {
              that.saveUserInfo(newUserData); // 缓存用户基础数据
              that.toTaskPage();
            } else {
              that.showLoding = false;
            }
          } else {
            that.showLoding = false;
          }
        } catch (e) {
          console.log(e)
        }

      },
      onInput(e) {
        this.phone = e.target.value;
      },
      /* 前往任务列表页 */
      toTaskPage(duration = 100) {
        // debugger
        setTimeout(() => {
          uni.navigateTo({
            url: '/pages/task/task1'
          })
        }, duration)
      },
      goBack() {
        uni.navigateTo({
          url: '/pages/login/index'
        })
      },
      /* 获取后台用户信息（进入即判断是否过期） */
      getUserInfo() {
        let that = this;
        return new Promise((resolve, reject) => {
          that.request("get", "getInfo", that.token, null).then(res => {
            if (res.code === 200) {
              resolve(res.data)
            } else {
              reject(res.msg)
            }
          })
        })
      },

      /* 获取微信用户信息（登录使用） */
      getUserProfile() {
        // #ifdef MP-WEIXIN
        let that = this;
        if (that.wxLoginInfo.openid) {
          // 已登录，但未获取手机号
          that.showPopup = true;
        } else if (uni.getUserProfile) {
          // 未登录，且版本支持 uni.getUserProfile
          uni.getUserProfile({
            lang: 'zh_CN',
            desc: "获取您的昵称、头像、手机号",
            success: async (res) => {
              console.log('用户同意了授权', res)
              that.wxUserInfo = res.userInfo; // 临时保存微信用户基础数据
              that.wxUserInfo['phone'] = '';
              that.mpWeixinTologin(); // 微信一键登录
            },
            fail: (err) => {
              console.log('授权失败:', err)
              uni.showToast({
                title: err
              })
            }
          })
        } else {
          uni.showToast({
            title: '当前版本过低'
          })
        }
        // #endif
        // #ifdef H5
        this.tempH5Login()
        // #endif
      },

      tempH5Login() {
        let data = {
          "accessToken": "29478626990E478DA9539866489DD87D",
          "avatarUrl": "https://thirdwx.qlogo.cn/mmopen/vi_32/DYAIOgq83epib9DbQJ7VsbLFhWMgiarZSibmRPXWb2tHOtzicnbzpj7Z8lIoBy6icUn0vESMicnMnv8lbGjxYKwSnspw/132",
          "deliveryEnd": "23:00",
          "deliveryStart": "8:30",
          "gmtCreate": 1666885726000,
          "gmtLastLogin": 1667054521000,
          "gmtUpdate": 1666885726000,
          "id": 151,
          "lastLoginIp": "27.10.60.71",
          "loginType": 1,
          "name": "L",
          "openId": "o7LCC5YUDftbpo907smJhvgsMnBs",
          "phone": "18522563339",
          "sessionKey": "yjKdFE0CMSLBKNmrXmFyyQ==",
          "state": 1,
          "storageId": 11,
          "workState": 1
        }
        let token = '29478626990E478DA9539866489DD87D';
        this.saveUserInfo(data); // 缓存用户基础数据
        this.sessionToken(token); // 缓存token
        this.toTaskPage(100);
      },

      /* 微信登录 */
      mpWeixinTologin() {
        let that = this;
        uni.login({
          provider: 'weixin',
          async success(res) {
            console.log('微信一键登录', res);
            if (res.errMsg == 'login:ok') {
              that.wxLoginInfo.code = res.code;
              that.serverLogin(1);
            }
          },
          fail(err) {
            console.log('uni.login', err);
          }
        });
      },

      /* 获取手机号 */
      getPhoneNumber(e) {
        console.log('获取手机号', e);
        let that = this;
        if (!that.wxLoginInfo.openid || !e.detail.encryptedData) {
          return false; // 未登录
        }
        that.showPopup = false; // 显示获取手机号按钮
        let content = {
          openid: that.wxLoginInfo.openid,
          sessionkey: that.wxLoginInfo.session_key,
          encryptedData: e.detail.encryptedData,
          iv: e.detail.iv,
        }
        let params = {
          raw: JSON.stringify(content)
        };
        that.request("get", "rider/wxLogin/decryptS5", null, params).then(resolve => {
          //console.log('获取解密手机号', resolve)
          if (resolve.code === 200) {
            //debugger
            let data = JSON.parse(resolve.data);
            that.wxUserInfo.phone = data.phoneNumber;
            that.serverLogin(2);
          } else {
            uni.showToast({
              title: resolve.msg
            })
          }
        })
      },

      /* 后台登录 */
      serverLogin(type) {
        // type: 1-第一次后台登录(返回无token) 2-第一次后台登录(返回带token)
        let that = this;
        let content = {
          code: that.wxLoginInfo.code,
          phone: that.wxUserInfo.phone,
          nickName: that.wxUserInfo.nickName,
          avatar: that.wxUserInfo.avatar,
          openid: that.wxLoginInfo.openid,
          session_key: that.wxLoginInfo.session_key,
        };
        that.request("post", "rider/wxLogin/wechatLogin", null, content).then(res => {
          console.log('获取数据库返回的用户信息', res);
          if (res.code === 200) {
            // 至此实际已登录
            that.wxLoginInfo.openid = res.data.openId;
            that.wxLoginInfo.session_key = res.data.sessionKey;
            // 保存数据库返回的用户信息

            if (type === 1) {
              // 返回无token, 另需获取手机号绑定对应的openid
              that.showPopup = true; // 显示获取手机号按钮
            } else {
              // 返回带token, 进入订单页
              let duration = 1500; // 延迟跳转页面
              that.saveUserInfo(res.data); // 缓存用户基础数据
              that.sessionToken(res.data.accessToken); // 缓存token
              uni.showToast({
                title: '登录成功',
                duration
              })
              that.toTaskPage(duration);
            }
          } else {
            uni.showToast({
              title: res.msg
            })
          }
        })
      }
    }
  }
</script>

<style lang="less" scoped>
  .login-box {
    position: relative;
    width: 100vw;
    height: 100vh;
  }

  .login-title {
    text-align: center;
    padding-top: 74rpx;
    font-size: 36rpx;
    color: #333333;
    font-weight: bold;
  }

  .logo {
    text-align: center;
    padding-top: 72rpx;

    image {
      width: 172rpx;
      height: 172rpx;
    }
  }

  .desc {
    text-align: center;
    padding-top: 48rpx;

    image {
      width: 284rpx;
      height: 46rpx;
    }
  }

  .form {
    width: 618rpx;
    margin: 0 auto;
    padding-top: 32rpx;

    .form_item {
      height: 100rpx;
      border-bottom: 2rpx solid #EFEFEF;
      position: relative;
    }

    .img1 {
      width: 36rpx;
      height: 40rpx;
      position: absolute;
      left: 26rpx;
      bottom: 28rpx;
    }

    .inp1 {
      width: 524rpx;
      display: inline-block;
      position: absolute;
      bottom: 0;
      height: 98rpx;
      left: 96rpx;
      /* color: #BBBBBB; */
      font-size: 30rpx;
      line-height: 98rpx;
    }

    .pl {
      color: #BBBBBB;
      font-size: 30rpx;
    }

    .img2 {
      width: 260rpx;
      height: 70rpx;
      right: 0;
      position: absolute;
      bottom: 14rpx;
      z-index: 10;
    }
  }

  .btn {
    width: 640rpx;
    height: 96rpx;
    line-height: 96rpx;
    color: #FFFFFF;
    background: linear-gradient(to right, #5095F4, #3662DD);
    font-size: 32rpx;
    border-radius: 8rpx;
    margin: 0 auto;
  }

  .btn+.btn {
    margin-top: 20rpx;
  }

  .other-login {
    position: relative;
    z-index: 5;
    width: 618rpx;
    margin: 80rpx auto 0;

    .ol-tilte {
      display: flex;

      align-items: center;
      justify-content: center;

      &:before,
      &:after {
        display: block;
        content: '';
        width: 30%;
        border-bottom: 2rpx solid #EFEFEF;
      }

      text {
        color: #666;
        font-size: 26rpx;
        padding: 0 20rpx;
      }
    }

    .wx-login {
      width: 88rpx;
      height: 88rpx;
      margin: 40rpx auto 0;

      image {
        display: block;
        width: 100%;
        height: 100%;
      }
    }
  }

  .bottom_img {
    position: absolute;
    left: 0;
    bottom: 0;
    display: block;
    width: 100%;
  }

  .popup-box {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 10;
    background-color: rgba(0, 0, 0, .5);
  }

  .login-popup {
    position: absolute;
    left: 0;
    bottom: 0;
    width: 100%;
    z-index: 10;
    background-color: #fff;
    padding-bottom: 40rpx;

    .lp-top {
      display: flex;
      align-items: center;
      color: #000;
      line-height: 1.2;

      .lpt-left {
        flex: 1;
        padding: 30rpx;

        .title {
          font-size: 28rpx;
          font-weight: 500;
        }

        .tips {
          color: #9a9b9b;
          font-size: 18rpx;
          margin-top: 10rpx;
        }
      }

      .lpt-right {
        padding: 30rpx;

        image {
          display: block;
          width: 28rpx;
          height: 28rpx;
        }
      }
    }

    .lp-center {
      position: relative;
      padding: 10rpx 30rpx 40rpx;
      color: #000;

      &:after {
        position: absolute;
        bottom: 0;
        left: 30rpx;
        right: 30rpx;
        content: '';
        border-bottom: 1rpx solid #ededed;
      }

      .title {
        font-size: 28rpx;
        font-weight: 600;
      }

      .tips {
        font-size: 26rpx;
        margin-top: 10rpx;
      }
    }

    .lp-bottom {
      padding: 0 30rpx;
      margin-top: 40rpx;

      .option-btn {
        height: 86rpx;
        color: #fff;
        font-size: 22rpx;
        text-align: center;
        line-height: 86rpx;
        padding: 0 30rpx;
        background: linear-gradient(to right, #5095F4, #3662DD);
      }
    }
  }
</style>
