<template>
  <view class="loginContainer">
    <view class="body">
      <image class="login-ground-img" :src="`${imgPrefix}loginGroundImg.png`" mode="widthFix" />
      <view class="btnConent">
        <button v-show="!checked" class="loginBtn" @click="unCheckAndGetPhoneNumber">
          手机快捷登录
        </button>
        <button v-show="checked" class="loginBtn" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">
          手机快捷登录
        </button>
        <view class="notLoginBtn" @click="goBack">
          暂不登录
        </view>
      </view>
    </view>

    <view class="footer">
      <view class="radioWrapper">
        <view class="checkbox-wrapper" @click.stop="changeChecked">
          <view class="checkbox" :class="{ 'checkbox-checked': checked }">
            <image v-if="checked" class="check-icon" :src="require('@/static/images/y.png')" />
          </view>
          <!-- <view v-if="uncheckMessageDialog" class="tooltip">
            <view class="tooltip-content">请先勾选，同意后再进行登录</view>
            <view class="tooltip-arrow"></view>
          </view> -->
        </view>
        <text class="radioText">
          请阅读并同意
          <text class="color" @click.stop="ptfwxy">《帮宠到家平台服务协议》</text>
          <text class="color" @click.stop="ysxy">《隐私协议》</text>
        </text>
      </view>
      <view class="bottom-safe-area" />
    </view>
  </view>
</template>

<script>
import appConfig from "@/constants/app.config";
import { login, getPhone } from "@/api/login";
import { imgPrefix } from "@/utils/common";

export default {
  data() {
    return {
      appConfig,
      imgPrefix,
      checked: false,
      uncheckMessageDialog: false,
    };
  },
  mounted() { },
  methods: {
    ptfwxy() {
      this.jumpTo("/pages/richText/index?code=ptfwxy");
    },
    ysxy() {
      this.jumpTo("/pages/richText/index?code=ysxy");
    },
    goBack() {
      this.loginAction();
    },
    jumpTo(url) {
      uni.navigateTo({
        url,
      });
    },
    changeChecked() {
      uni.requestSubscribeMessage({
        tmplIds: ['QoTeQwj4xw2UQMK5jI67MzAVOo6og76oqZ7BDIJW7cE', 'GPWlTkaNbi7JqvxltLKuZZMtKedSZfEKlirV7yOUu-0'],// TEMPLATE_ID替换为选用的模版id
        success(res) {
          uni.hideLoading()
          if (res['QoTeQwj4xw2UQMK5jI67MzAVOo6og76oqZ7BDIJW7cE'] === 'accept') {
            // setSubscribeStatus(true, '已订阅')
            uni.showToast({
              title: '订阅成功',
              icon: 'success',
            })
          }
          if (res['GPWlTkaNbi7JqvxltLKuZZMtKedSZfEKlirV7yOUu-0'] === 'accept') {
            // setSubscribeStatus(true, '已订阅')
            uni.showToast({
              title: '订阅成功',
              icon: 'success',
            })
          }
        },
        fail() {
          uni.showToast({
            title: '订阅失败',
            icon: 'error',
          })
        },
        complete: () => {
          // isSubscribing = false
        },
      })
      this.checked = !this.checked;
    },
    unCheckAndGetPhoneNumber() {
      uni.showToast({
        title: '请先勾选，同意后再进行登录',
        icon: 'none',
        duration: 2000
      });
    },
    async getPhoneNumber(e) {
      // console.log(e,'?')
      // return
      // 检查是否有 code
      if (!e.detail.code) {
        uni.showToast({
          title: "获取手机号失败，请重试",
          icon: "none",
        });
        return;
      }

      uni.showLoading({
        title: "获取手机号中...",
        icon: "none",
        mask: true,
      });

      try {
        // 登录前先记录是否有邀请码(referrerID)，用于登录后导航判断
        const hasReferrer =
          this.$store.state?.user && this.$store.state.user.referrerID;
        // 拿着code获取手机号
        const codeRes = await getPhone(e.detail.code);
        const phone = codeRes?.data?.phoneNumber || "";

        if (!phone) {
          uni.hideLoading();
          uni.showToast({
            title: "获取手机号失败，请重试",
            icon: "none",
          });
          return;
        }

        uni.showLoading({
          title: "登录中...",
          icon: "none",
          mask: true,
        });

        // 手机号登录
        login(phone)
          .then((res) => {
            uni.hideLoading();
            this.$store.dispatch("user/setToken", res?.data?.token || "");
            this.$store.dispatch("user/setUserInfo", res?.data || {});

            // 如果是带邀请码(referrerID)的登录，统一跳转到首页
            if (hasReferrer) {
              uni.reLaunch({
                url: "/pages/client/index/index",
              });
              return;
            }

            var pages = getCurrentPages();
            if (pages.length === 1) {
              uni.reLaunch({
                url: "/pages/client/index/index",
              });
              return;
            }
            uni.navigateBack();
          })
          .catch((err) => {
            uni.hideLoading();
            uni.showToast({
              title: err || "登录失败，请重试",
              icon: "none",
            });
          });
      } catch (error) {
        uni.hideLoading();
        console.error("获取手机号失败:", error);
        // 检查是否是 access_token 相关错误
        const errorMsg = error?.message || error || "";
        if (errorMsg.includes("access_token") || errorMsg.includes("invalid credential")) {
          uni.showToast({
            title: "服务暂时不可用，请稍后重试",
            icon: "none",
            duration: 3000,
          });
        } else {
          uni.showToast({
            title: errorMsg || "获取手机号失败，请重试",
            icon: "none",
          });
        }
      }
    },
    loginAction() {
      if (!this.checked) {
        uni.showModal({
          title: '提示',
          content: '请先勾选，同意后再进行登录',
          confirmText: '确认',
          cancelText: '取消',
          success: (res) => {
            if (res.confirm) {
              // 自动勾选协议
              this.checked = true;
              // 继续执行登录
              this.loginAction();
            }
          }
        });
        return;
      }
      // 登录前先记录是否有邀请码(referrerID)，用于登录后导航判断
      const hasReferrer =
        this.$store.state?.user && this.$store.state.user.referrerID;

      uni.showLoading({
        title: "加载中...",
        icon: "none",
        mask: true,
      });
      login()
        .then((res) => {
          this.$store.dispatch("user/setToken", res?.data?.token || "");
          this.$store.dispatch("user/setUserInfo", res?.data || {});

          // 如果是带邀请码(referrerID)的登录，统一跳转到首页
          if (hasReferrer) {
            uni.reLaunch({
              url: "/pages/client/index/index",
            });
            return;
          }

          var pages = getCurrentPages();
          if (pages.length === 1) {
            uni.reLaunch({
              url: "/pages/client/index/index",
            });
            return;
          }
          uni.navigateBack();
        })
        .finally(() => {
          uni.hideLoading();
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.loginContainer {
  height: 100vh;
  background-color: #f7f8fa;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  padding-top: 20rpx;

  .body {
    background-color: #fff;
    padding: 20rpx;
    border-radius: 16rpx;
    margin: 0 20rpx;

    .login-ground-img {
      width: 100%;
    }

    .btnConent {
      padding: 0rpx 20rpx;
      padding-bottom: 100rpx;
      margin-top: 30rpx;

      .loginBtn {
        color: #fff;
        background-color: #ff19a0;
        border-radius: 300rpx;
        padding: 26rpx 0rpx;
        text-align: center;
        font-size: 32rpx;
        border: none;
        width: 100%;

        &::after {
          border: none;
        }
      }

      .notLoginBtn {
        background-color: #fff;
        color: #FF19A0;
        border: 1rpx solid #FF19A0;
        border-radius: 300rpx;
        padding: 26rpx 0rpx;
        text-align: center;
        font-size: 32rpx;
        margin-top: 60rpx;
      }
    }
  }

  .footer {
    .radioWrapper {
      margin-bottom: 20rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      position: relative;

      .checkbox-wrapper {
        position: relative;
        display: flex;
        align-items: center;
        margin-right: 8rpx;

        .checkbox {
          width: 32rpx;
          height: 32rpx;
          border-radius: 50%;
          border: 2rpx solid #999999;
          display: flex;
          align-items: center;
          justify-content: center;
          background: #FFFFFF;
          transition: all 0.3s ease;
          flex-shrink: 0;

          &.checkbox-checked {
            border-color: #FF19A0;
            background: #FF19A0;
          }

          .check-icon {
            width: 20rpx;
            height: 20rpx;
          }
        }

        .tooltip {
          position: absolute;
          bottom: 100%;
          left: 50%;
          transform: translateX(-50%);
          margin-bottom: 12rpx;
          background: rgba(0, 0, 0, 0.85);
          border-radius: 12rpx;
          padding: 16rpx 24rpx;
          white-space: nowrap;
          z-index: 100;

          .tooltip-content {
            font-size: 24rpx;
            color: #FFFFFF;
            line-height: 1.4;
          }

          .tooltip-arrow {
            position: absolute;
            bottom: -12rpx;
            left: 50%;
            transform: translateX(-50%);
            width: 0;
            height: 0;
            border-left: 12rpx solid transparent;
            border-right: 12rpx solid transparent;
            border-top: 12rpx solid rgba(0, 0, 0, 0.85);
          }
        }
      }

      .radioText {
        font-size: 22rpx;
        color: #9b939a;

        .color {
          color: #FF19A0;
          font-size: 22rpx;
        }
      }
    }
  }

  .bottom-safe-area {
    padding-bottom: constant(safe-area-inset-bottom);
    padding-bottom: env(safe-area-inset-bottom);
  }
}
</style>
