<template>
  <view class="login-bg">
    <image class="bg-image" src="/static/background.png" mode="aspectFill" />
    <!-- 医生卡片及头像 -->
    <view class="doctor-card-wrap">
      <view v-if="team" class="doctor-card">
        <view class="doctor-info">
          <view class="doctor-name">{{ team.teamName }}</view>
          <view class="doctor-hospital">{{ team.corpName }}</view>
          <view class="login-tip">为您提供团队个性化专属服务</view>
        </view>
      </view>
      <view v-else class="doctor-card doctor-card-empty">
        <view class="doctor-info">
          <image class="logo" src="/static/logo-plain.png" mode="aspectFill" />
          <view class="doctor-name">健康柚</view>
          <view class="login-tip">全周期健康管理伙伴</view>
        </view>
      </view>
      <view v-if="team" class="doctor-avatar">
        <group-avatar :avatarList="team.avatars" />
      </view>
    </view>
    <!-- 登录按钮 -->
    <view class="login-btn-wrap">
      <button v-if="checked && account && account.mobile" class="login-btn" type="primary" @click="getPhoneNumber">
        手机号快捷登录
      </button>
      <button v-else-if="checked" class="login-btn" type="primary" open-type="getPhoneNumber"
        @getphonenumber="getPhoneNumber">
        手机号快捷登录
      </button>
      <button v-else class="login-btn" type="primary" @click="visible = true">
        手机号快捷登录
      </button>
    </view>
    <!-- 协议 -->
    <view class="agreement">
      <checkbox :checked="checked" @click="checked = !checked" />
      <text>我已阅读并同意</text>
      <text class="link" @click="toAggreement('userAgreement')">《用户协议》</text>
      <text>、</text>
      <text class="link" @click="toAggreement('privacyPolicy')">《隐私政策》</text>
    </view>
  </view>
  <agreement-popup :visible="visible" @close="visible = false" @confirm="onAgree()" />
</template>


<script setup>
import { ref } from "vue";
import { storeToRefs } from "pinia";
import { onLoad } from "@dcloudio/uni-app";
import useAccountStore from "@/store/account";
import api from '@/utils/api';
import { get, set } from "@/utils/cache";
import { toast } from "@/utils/widget";

import groupAvatar from "@/components/group-avatar.vue";
import agreementPopup from "./agreement-popup.vue";

const env = __VITE_ENV__;
const appid = env.MP_WX_APP_ID;
const team = ref(null);
const checked = ref(false);
const redirectUrl = ref("");
const { account } = storeToRefs(useAccountStore());
const { login } = useAccountStore();
const visible = ref(false)

function attempRedirect(url) {
  return new Promise((resolve, reject) => {
    uni.redirectTo({
      url,
      success: () => resolve(true),
      fail: () => reject(false),
    });
  });
}

function attempSwitchTab(url) {
  return new Promise((resolve, reject) => {
    uni.switchTab({
      url,
      success: () => resolve(true),
      fail: () => reject(false),
    });
  });
}

function onAgree() {
  visible.value = false;
  checked.value = true;
}

function toAggreement(type) {
  uni.navigateTo({
    url: `/pages/login/agreement?type=${type}`
  })
}

function toHome() {
  uni.switchTab({
    url: "/pages/home/home",
  });
}

async function syncExternalUserRelation() {
  const currentTeam = team.value || {};
  const currentAccount = account.value || {};
  if (!(currentTeam.corpId && currentTeam.externalUserId && currentAccount.openid)) return;
  try {
    const res = await api('syncWxappExternalUserRelation', {
      corpId: currentTeam.corpId,
      externalUserId: currentTeam.externalUserId,
      unionid: currentAccount.unionid || '',
      openid: currentAccount.openid,
      corpUserId: currentTeam.corpUserId || '',
    }, false);
    if (!res || !res.success) {
      console.warn('关联 externalUserId 失败:', res && res.message);
    }
  } catch (error) {
    console.warn('关联 externalUserId 异常:', error && error.message ? error.message : error);
  }
}


async function bindTeam() {
  const res = await api('bindWxappWithTeam', { appid, corpId: team.value.corpId, teamId: team.value.teamId, openid: account.value.openid });
  if (!res || !res.success) {
    return toast("关联团队失败");
  }
  await syncExternalUserRelation();
  const res1 = await api('getWxAppCustomerCount', { miniAppId: account.value.openid, corpId: team.value.corpId, teamId: team.value.teamId });
  if (res1 && res1.data > 0) {
    toHome();
  } else {
    attempToPage(redirectUrl.value)
  }
}

async function getPhoneNumber(e) {
  const phoneCode = e && e.detail && e.detail.code;
  if (!account.value || !account.value.mobile) {
    const res = await login(phoneCode);
    if (!res) return;
  }
  if (team.value) {
    bindTeam()
  } else if (redirectUrl.value) {
    await attempToPage(redirectUrl.value);
  } else {
    toHome();
  }
}

async function attempToPage(url) {
  const res1 = attempRedirect(url);
  if (res1) return;
  const res2 = attempSwitchTab(url);
  if (res2) return;
  toHome();
}

onLoad((opts) => {
  if (opts.source === "teamInvite") {
    team.value = get("invite-team-info");
    redirectUrl.value = `/pages/archive/edit-archive?corpUserId=${team.value.corpUserId || ''}&teamId=${team.value.teamId}&corpId=${team.value.corpId}`;
    return;
  }
  redirectUrl.value = opts.redirectUrl || "";
});
</script>
<style scoped>
.pt-lg {
  padding-top: 20vh;
}

.login-btn-wrap {
  width: 100vw;
  display: flex;
  justify-content: center;
  margin-top: 80rpx;
}

.login-btn-wrap-loading {
  pointer-events: none;
}

.login-btn {
  width: calc(100vw - 112rpx);
  max-width: 600rpx;
  height: 80rpx;
  line-height: 80rpx;
  background: linear-gradient(270deg, #1b5cc8 2.26%, #0877f1 94.33%);
  color: #fff;
  font-size: 32rpx;
  border-radius: 48rpx;
  font-weight: 600;
  box-shadow: 0 4rpx 16rpx rgba(59, 124, 255, 0.08);
  border: none;
}

.login-btn:active {
  background: linear-gradient(270deg, #1b5cc8 2.26%, #0877f1 94.33%);
}

.login-bg {
  min-height: 100vh;
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.logo {
  width: 180rpx;
  height: 180rpx;
  border-radius: 50%;
}

.bg-image {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 500rpx;
  z-index: 0;
}

.login-gradient {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 340rpx;
  background: linear-gradient(270deg, #1b5cc8 2.26%, #0877f1 94.33%);
  z-index: 0;
}

.doctor-card-wrap {
  width: calc(100vw - 48rpx);
  max-width: 600rpx;
  margin: 0 auto;
  position: relative;
  margin-top: 320rpx;
}

.doctor-card {
  /* min-height: 300rpx; */
  background: #fff;
  border-radius: 24rpx;
  background: linear-gradient(180deg, #dbe8ff 0%, #fff 50.25%);
  box-shadow: 0 8rpx 32rpx rgba(59, 124, 255, 0.08);
  padding: 100rpx 24rpx 60rpx 24rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
  z-index: 1;
}

.doctor-avatar {
  border-radius: 16rpx;
  background: #f2f2f2;
  box-shadow: 0 2rpx 8rpx rgba(59, 124, 255, 0.08);
  position: absolute;
  left: 50%;
  top: 0;
  transform: translate(-50%, -50%);
  border: 6rpx solid #fff;
  z-index: 2;
}

.doctor-info {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.doctor-name {
  font-size: 42rpx;
  font-weight: 600;
  color: #1d2129;
  margin-top: 40rpx;
}

.doctor-hospital {
  font-size: 30rpx;
  color: #78808f;
  font-weight: 400;
  margin-top: 20rpx;
  text-align: center;
}

.doctor-dept {
  display: inline-block;
  color: #213e80;
  border-radius: 4rpx;
  border: 1rpx solid #1a3e8433;
  padding: 0 8rpx;
  font-size: 24rpx;
  font-weight: 400;
  margin-top: 20rpx;
}

.login-tip {
  font-size: 34rpx;
  color: #000000;
  font-weight: 500;
  text-align: center;
  margin-top: 40rpx;
}

.login-btn-wrap {
  width: 100vw;
  display: flex;
  justify-content: center;
  margin-top: 136rpx;
}

.login-btn-wrap-loading {
  pointer-events: none;
}

.login-btn {
  width: calc(100vw - 112rpx);
  max-width: 600rpx;
  height: 96rpx;
  line-height: 96rpx;
  background: linear-gradient(270deg, #1b5cc8 2.26%, #0877f1 94.33%);
  color: #fff;
  font-size: 34rpx;
  border-radius: 48rpx;
  font-weight: 600;
  box-shadow: 0 4rpx 16rpx rgba(59, 124, 255, 0.08);
  border: none;
}

.login-btn:active {
  background: linear-gradient(270deg, #1b5cc8 2.26%, #0877f1 94.33%);
}

.agreement {
  width: 100vw;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #b2b7c2;
  font-size: 24rpx;
  margin-top: 40rpx;
  gap: 8rpx;
}

.link {
  color: #3b7cff;
  margin: 0 4rpx;
}

.agreement checkbox {
  transform: scale(0.7);
  vertical-align: middle;
}
</style>
