<template>
  <view class="page">
    <view class="system-height" :style="{ height: statusBarHeight }"></view>
    <!-- #ifdef MP -->
    <view class="title-bar" style="height: 43px">
      <view class="icon" @click="back" v-if="!isHome">
        <image src="/static/left.png"></image>
      </view>
      <view class="icon" @click="home" v-else>
        <image src="/static/home.png"></image>
      </view>
      账户登录
    </view>
    <!-- #endif -->
    <view class="wechat_login">
      <view class="img">
        <image src="/static/wechat_login.png" mode="widthFix"></image>
      </view>
      <view class="btn-wrapper">
        <!-- #ifdef H5 -->
        <button hover-class="none" @click="wechatLogin" class="bg-green btn1">
          微信登录
        </button>
        <!-- #endif -->
        <!-- #ifdef MP -->
        <button hover-class="none" @tap="getUserProfile" class="bg-green btn1">
          微信登录
        </button>
        <!-- #endif -->
        <!-- <button hover-class="none" @click="isUp = true" class="btn2">手机号登录</button> -->
      </view>
    </view>
    <block v-if="isUp">
      <mobileLogin
        :isUp="isUp"
        @close="maskClose"
        :authKey="authKey"
        @wechatPhone="wechatPhone"
      ></mobileLogin>
    </block>
    <block v-if="isPhoneBox">
      <routinePhone
        :logoUrl="logoUrl"
        :isPhoneBox="isPhoneBox"
        @close="bindPhoneClose"
        :authKey="authKey"
      >
      </routinePhone>
    </block>
  </view>
</template>

<script setup>
import { ref, getCurrentInstance } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import { useAppStore } from "@/stores/app";
import mobileLogin from "@/components/login_mobile/index.vue";
import routinePhone from "@/components/login_mobile/routine_phone.vue";
import { getLogo, getUserPhone } from "@/api/public";
import { getUserInfo } from "@/api/user.js";
import Routine from "@/libs/routine";
import wechat from "@/libs/wechat";
import Cache from "@/utils/cache";
import { EXPIRES_TIME } from "@/config/cache";

const appStore = useAppStore();
const { proxy } = getCurrentInstance();

const isUp = ref(false);
const phone = ref("");
const statusBarHeight = ref(uni.getSystemInfoSync().statusBarHeight + "px");
const isHome = ref(false);
const isPhoneBox = ref(false);
const logoUrl = ref("");
const code = ref("");
const authKey = ref("");
const options = ref({});
const userInfo = ref({});
const codeNum = ref(0);

function back() {
  uni.navigateBack();
}
function home() {
  uni.switchTab({ url: "/pages/index/index" });
}
function maskClose() {
  isUp.value = false;
}
function bindPhoneClose(data) {
  if (data.isStatus) {
    isPhoneBox.value = false;
    proxy.$util.Tips(
      {
        title: "登录成功",
        icon: "success",
      },
      { tab: 3 }
    );
  } else {
    isPhoneBox.value = false;
  }
}

// #ifdef MP
function getphonenumber(e) {
  uni.showLoading({ title: "正在登录中" });
  Routine.getCode()
    .then((code) => {
      getUserPhoneNumber(e.detail.encryptedData, e.detail.iv, code);
    })
    .catch(() => {
      uni.$emit("closePage", false);
      uni.hideLoading();
    });
}
function getUserPhoneNumber(encryptedData, iv, codeVal) {
  getUserPhone({
    encryptedData,
    iv,
    code: codeVal,
    type: "routine",
    key: authKey.value,
  })
    .then((res) => {
      appStore.LOGIN({ token: res.data.token });
      appStore.SETUID(res.data.uid);
      // 保存过期时间（7天后过期）
      const expiresTime = Math.round(new Date() / 1000) + 7 * 24 * 60 * 60;
      Cache.set(EXPIRES_TIME, expiresTime, 0);
      getUserInfoFn();
      proxy.$util.Tips(
        {
          title: "登录成功",
          icon: "success",
        },
        { tab: 3 }
      );
    })
    .catch((res) => {
      uni.hideLoading();
      proxy.$util.Tips({ title: res });
    });
}
function getUserInfoFn() {
  getUserInfo().then((res) => {
    uni.hideLoading();
    userInfo.value = res.data;
    appStore.UPDATE_USERINFO(res.data);
    proxy.$util.Tips(
      {
        title: "登录成功",
        icon: "success",
      },
      { tab: 3 }
    );
  });
}
function getUserProfile() {
  uni.showLoading({ title: "正在登录中" });
  Routine.getUserProfile()
    .then((res) => {
      Routine.getCode()
        .then((codeVal) => {
          getWxUser(codeVal, res);
        })
        .catch(() => {
          uni.hideLoading();
        });
    })
    .catch(() => {
      uni.hideLoading();
    });
}
function getWxUser(codeVal, res) {
  let user = res.userInfo;
  user.code = codeVal;
  user.spread_spid = getApp().globalData.spid;
  user.spread_code = getApp().globalData.code;
  user.avatar = user.avatarUrl;
  user.city = user.city;
  user.country = user.country;
  user.nickName = user.nickName;
  user.province = user.province;
  user.sex = user.gender;
  user.type = "routine";
  Routine.authUserInfo(user.code, user)
    .then((res2) => {
      authKey.value = res2.data.key;
      if (res2.data.type === "register") {
        uni.hideLoading();
        isPhoneBox.value = true;
      }
      if (res2.data.type === "login") {
        uni.hideLoading();
        appStore.LOGIN({ token: res2.data.token });
        appStore.SETUID(res2.data.uid);
        getUserInfoFn();
        proxy.$util.Tips(
          {
            title: res2,
            icon: "success",
          },
          { tab: 3 }
        );
      }
    })
    .catch((res2) => {
      uni.hideLoading();
      uni.showToast({
        title: res2,
        icon: "none",
        duration: 2000,
      });
    });
}
// #endif

// #ifdef H5
function getQueryString(name) {
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
  var reg_rewrite = new RegExp("(^|/)" + name + "/([^/]*)(/|$)", "i");
  var r = window.location.search.substr(1).match(reg);
  var q = window.location.pathname.substr(1).match(reg_rewrite);
  if (r != null) {
    return unescape(r[2]);
  } else if (q != null) {
    return unescape(q[2]);
  } else {
    return null;
  }
}
function wechatLogin() {
  if (!code.value && options.value.scope !== "snsapi_base") {
    proxy.$wechat.oAuth("snsapi_userinfo", "/pages/users/wechat_login/index");
  } else {
    isUp.value = true;
  }
}
function wechatPhone() {
  proxy.$Cache.clear("snsapiKey");
  if (options.value.back_url) {
    let url = uni.getStorageSync("snRouter");
    url = url.indexOf("/pages/index/index") != -1 ? "/" : url;
    if (url.indexOf("/pages/users/wechat_login/index") !== -1) {
      url = "/";
    }
    if (!url) {
      url = "/pages/index/index";
    }
    isUp.value = false;
    uni.showToast({
      title: "登录成功",
      icon: "none",
    });
    setTimeout(() => {
      location.href = url;
    }, 800);
  } else {
    uni.navigateBack();
  }
}
// #endif

onLoad((opts) => {
  getLogo().then((res) => {
    logoUrl.value = res.data.logoUrl;
  });
  // #ifdef H5
  document.body.addEventListener("focusout", () => {
    setTimeout(() => {
      const scrollHeight =
        document.documentElement.scrollTop || document.body.scrollTop || 0;
      window.scrollTo(0, Math.max(scrollHeight - 1, 0));
    }, 100);
  });
  const { code: c, state, scope } = opts;
  options.value = opts;
  code.value = c || "";
  if (c && options.value.scope !== "snsapi_base") {
    let spread = getApp().globalData.spid ? getApp().globalData.spid : 0;
    wechat
      .auth(c, spread)
      .then((res) => {
        if (res.type === "register") {
          authKey.value = res.key;
          isUp.value = true;
        }
        if (res.type === "login") {
          appStore.LOGIN({ token: res.data.token });
          appStore.SETUID(res.data.uid);
          // 保存过期时间（7天后过期）
          const expiresTime = Math.round(new Date() / 1000) + 7 * 24 * 60 * 60;
          Cache.set(EXPIRES_TIME, expiresTime, 0);
          getUserInfoFn();
          wechatPhone();
        }
      })
      .catch(() => {});
  }
  // #endif

  let pages = getCurrentPages();
  // let prePage = pages[pages.length - 2]
  // if (prePage.route == 'pages/order_addcart/order_addcart') {
  //   isHome.value = true
  // } else {
  //   isHome.value = false
  // }
});
</script>

<style lang="scss">
page {
  background: #fff;
  height: 100%;
}

.page {
  background: #fff;
  height: 100%;
}

.wechat_login {
  padding: 72rpx 34rpx;

  .img image {
    width: 100%;
  }

  .btn-wrapper {
    margin-top: 86rpx;
    padding: 0 66rpx;

    button {
      width: 100%;
      height: 86rpx;
      line-height: 86rpx;
      margin-bottom: 40rpx;
      border-radius: 120rpx;
      font-size: 30rpx;

      &.btn1 {
        color: #fff;
      }

      &.btn2 {
        color: #666666;
        border: 1px solid #666666;
      }
    }
  }
}

.title-bar {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 36rpx;
}

.icon {
  position: absolute;
  left: 30rpx;
  top: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 86rpx;
  height: 86rpx;

  image {
    width: 50rpx;
    height: 50rpx;
  }
}
</style>
