<template>
  <BasicModal type="bottom" v-model:open="getOpen" :isMack="true">
    <view class="login-modal">
      <!-- 右上角关闭按钮 -->
      <view class="login-modal__close" @click="handleClose">暂不登录</view>
      
      <!-- 标题 -->
      <view class="login-modal__title">欢迎登录U店在哪</view>
      
      <!-- 描述 -->
      <view class="login-modal__desc">授权手机号登录,享受更多便利和会员服务</view>
      
      <!-- 一键登录按钮 -->
      <button 
        class="login-modal__btn" 
        type="primary"
        open-type="getPhoneNumber" 
        @getphonenumber="handleGetPhoneNumber"
        :disabled="!agreed"
      >
        一键登录
      </button>
      
      <!-- 协议同意 -->
      <view class="login-modal__agreement">
        <view class="agreement-checkbox" @click="toggleAgree">
          <view class="checkbox-icon" :class="{ 'checked': agreed }">
            <text v-if="agreed" class="icon-check">✓</text>
          </view>
        </view>
        <text class="agreement-text">我已阅读并同意</text>
        <text class="agreement-link" @click="handlePrivacy">《隐私协议》</text>
        <text class="agreement-text">和</text>
        <text class="agreement-link" @click="handleUserAgreement">《用户协议》</text>
      </view>
    </view>
  </BasicModal>
</template>

<script setup>
import { ref, computed } from 'vue';
import BasicModal from '@/components/Modal/BasicModal.vue';
import { DiningUserWechatLogin, GetUserInfo } from '@/api/dining.js';
import { useUserStore } from '@/store/user.js';

const props = defineProps({
  open: {
    type: Boolean,
    default: false
  }
});

const emit = defineEmits(['update:open', 'success', 'cancel']);

const agreed = ref(false);
const userStore = useUserStore();

const getOpen = computed({
  get: () => props.open,
  set: (val) => emit('update:open', val)
});

// 切换同意状态
const toggleAgree = () => {
  agreed.value = !agreed.value;
};

// 处理关闭
const handleClose = () => {
  getOpen.value = false;
  emit('cancel');
};

// 处理获取手机号
const handleGetPhoneNumber = async (e) => {
  if (!agreed.value) {
    uni.showToast({
      title: '请先同意用户协议和隐私协议',
      icon: 'none'
    });
    return;
  }

  if (!e.detail.code) {
    uni.showToast({
      title: '授权失败，请重试',
      icon: 'none'
    });
    return;
  }

  try {
    const phoneCode = e.detail?.code || "";
    // 登录接口：传 code、phoneCode；手机号明文传递（不加密），有缓存则一并传 phone）
    uni.login({
      success: async (loginRes) => {
        try {
          const res = await DiningUserWechatLogin({
            code: loginRes.code,
            phoneCode: phoneCode || undefined,
            phone: userStore.getPhone || undefined  // 明文传递，有缓存则传
          });

          if (res && res.token) {
            userStore.login(res);
            try {
              const userRes = await GetUserInfo();
              const raw = userRes?.data ?? userRes?.result ?? userRes?.userInfo ?? userRes?.user ?? userRes ?? {};
              const userData = typeof raw === 'object' && raw !== null ? raw : {};
              const merged = { ...userStore.getUserInfo, ...userData };
              userStore.setUserInfo(merged);
            } catch (err) {
              console.warn('获取用户信息失败', err);
            }
            getOpen.value = false;
            emit('success', res);
          } else {
            uni.showToast({
              title: res?.msg || '登录失败，请重试',
              icon: 'none'
            });
          }
        } catch (error) {
          console.error('登录失败:', error);
          uni.showToast({
            title: '登录失败，请重试',
            icon: 'none'
          });
        }
      },
      fail: () => {
        uni.showToast({
          title: '获取登录凭证失败',
          icon: 'none'
        });
      }
    });
  } catch (error) {
    console.error('获取手机号失败:', error);
    uni.showToast({
      title: '授权失败，请重试',
      icon: 'none'
    });
  }
};

// 处理隐私协议
const handlePrivacy = () => {
  // TODO: 跳转到隐私协议页面
  uni.showToast({
    title: '隐私协议',
    icon: 'none'
  });
};

// 处理用户协议
const handleUserAgreement = () => {
  // TODO: 跳转到用户协议页面
  uni.showToast({
    title: '用户协议',
    icon: 'none'
  });
};
</script>

<style scoped lang="scss">
/* 优先级最高，避免被 tabbar 等挡住 */
:deep(.uni-popup) {
  z-index: 99999 !important;
}

:deep(.uni-popup__wrapper) {
  z-index: 99999 !important;
}

:deep(.uni-popup__mask) {
  z-index: 99998 !important;
}

.login-modal {
  width: 100%;
  background: #FFFFFF;
  border-radius: 24rpx;
  padding: 60rpx 40rpx 50rpx;
  position: relative;
  box-sizing: border-box;

  &__close {
    position: absolute;
    top: 30rpx;
    right: 30rpx;
    font-size: 24rpx;
    color: #ccc;
    line-height: 1;
  }

  &__title {
    font-size: 44rpx;
    font-weight: bold;
    color: #010101;
    // text-align: center;
    margin-bottom: 24rpx;
    line-height: 1.2;
  }

  &__desc {
    font-size: 28rpx;
    color: #333333;
    // text-align: center;
    margin-bottom: 60rpx;
    line-height: 1.5;
  }

  &__btn {
    width: 100%;
    height: 88rpx;
    // background: #07C160;
    border-radius: 44rpx;
    color: #FFFFFF;
    font-size: 32rpx;
    font-weight: 500;
    line-height: 88rpx;
    text-align: center;
    border: none;
    margin-bottom: 40rpx;
    padding: 0;

    &::after {
      border: none;
    }

    &[disabled] {
      background: #CCCCCC;
      color: #999999;
    }
  }

  &__agreement {
    display: flex;
    align-items: center;
    justify-content: center;
    flex-wrap: wrap;
    font-size: 24rpx;
    line-height: 1.5;

    .agreement-checkbox {
      margin-right: 8rpx;

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

        &.checked {
          background: #07C160;
          border-color: #07C160;

          .icon-check {
            color: #FFFFFF;
            font-size: 20rpx;
            font-weight: bold;
          }
        }
      }
    }

    .agreement-text {
      color: #333333;
      margin: 0 4rpx;
    }

    .agreement-link {
      color: #1677FF;
      margin: 0 4rpx;
    }
  }
}
</style>

