<template>

    <view class="login-popup" :class="{ 'show': loginPopupVisible }">
        <view class="mask" @tap="handleClose"></view>
        <view class="popup-content">
            <view class="popup-header">
                <text class="title">登录</text>
                <text class="close-btn" @tap="handleClose">×</text>
            </view>

            <!-- 微信登录按钮 -->
            <!-- <button class="wechat-btn" @tap="handleWechatLogin">
                <image src="/static/icon/wechat.png" mode="aspectFit" class="wechat-icon"></image>
                微信一键登录
            </button> -->

            <!-- 分割线 -->
            <!-- <view class="divider">
                <text class="divider-text">或</text>
            </view> -->

            <!-- 账号密码登录 -->
            <view class="account-login">
                <view class="input-item">
                    <input type="text" v-model="form.username" placeholder="用户名" placeholder-class="placeholder"
                        />
                </view>
                <view class="input-item">
                    <input :password="!showPassword" type="text" v-model="form.password" placeholder="密码"
                        placeholder-class="placeholder" />

                    <view class="eye-icon" @tap.stop="showPassword = !showPassword">
                        <image :src="showPassword ? '/static/icon/eye-open.png' : '/static/icon/eye-close.png'"
                            mode="aspectFit" class="eye-image"></image>
                    </view>
                </view>
                <button
                    class="account-btn"
                    :class="{ 'disabled': isLogging }"
                    :disabled="isLogging"
                    @tap="handleAccountLogin"
                >
                    {{ isLogging ? '登录中...' : '登录' }}
                </button>
            </view>

            <!-- 用户协议 -->
            <view class="agreement">
                <checkbox :checked="agreed" @tap="handleAgreementConfirm" color="#40ac6d" />
                <text class="agreement-text">
                    我已阅读并同意
                    <text class="link" @tap="openAgreement('user')">《用户协议》</text>
                    与
                    <text class="link" @tap="openAgreement('privacy')">《隐私协议》</text>
                </text>
            </view>
        </view>
    </view>

    <agreement-popup v-model:visible="showAgreement" :type="agreementType" />
</template>

<script setup>
import AgreementPopup from '../agreement/AgreementPopup.vue'

import { ref } from 'vue'
import { useUserStore } from '@/store/modules/user'
import { storeToRefs } from 'pinia'
import { userApi } from '@/api/user'

const userStore = useUserStore()
const { loginPopupVisible } = storeToRefs(userStore)

const loginType = ref('wechat')
const form = ref({
    username: '',
    password: ''
})
const showPassword = ref(false)
const agreed = ref(false)
const showAgreement = ref(false)
const agreementType = ref('user')

// 防重复点击状态
const isLogging = ref(false)

// 点击协议链接
const openAgreement = (type) => {
    agreementType.value = type
    showAgreement.value = true
}

// 确认阅读协议
const handleAgreementConfirm = () => {
    agreed.value = true
}
const handleClose = () => {
    userStore.hideLoginPopup()
    form.value.username = ''
    form.value.password = ''
    agreed.value = false
    isLogging.value = false // 重置登录状态
    uni.hideLoading() // 确保隐藏 loading
}
// 微信登录
const handleWechatLogin = async () => {
    if (isLogging.value) {
        console.log('正在登录中，请勿重复点击')
        return
    }

    if (!agreed.value) {
        uni.showToast({
            title: '请先同意用户协议和隐私协议',
            icon: 'none'
        })
        return
    }

    try {
        isLogging.value = true

        // 显示获取微信授权的提示
        uni.showLoading({
            title: '获取微信授权...',
            mask: true
        })

        const loginRes = await uni.login()

        // 切换到登录中的 loading
        uni.showLoading({
            title: '微信登录中...',
            mask: true
        })

        const res = await userApi.wechatLogin({
            code: loginRes.code
        }, () => {
            // 请求完成回调，无论成功失败都会执行
            isLogging.value = false
            uni.hideLoading() // 隐藏 loading
        })

        console.log("登录成功", res.data)
        userStore.setUserInfo(res.data)
        uni.$emit('login', res.data)
        handleClose()

    } catch (e) {
        console.error('登录失败：', e)
        uni.showToast({
            title: '登录失败',
            icon: 'none'
        })
        // 确保隐藏 loading 和重置状态
        isLogging.value = false
        uni.hideLoading()
    }
}

// 账号密码登录
const handleAccountLogin = async () => {
    if (isLogging.value) {
        console.log('正在登录中，请勿重复点击')
        return
    }

    if (!agreed.value) {
        uni.showToast({
            title: '请先同意用户协议和隐私协议',
            icon: 'none'
        })
        return
    }
    if (!form.value.username || !form.value.password) {
        uni.showToast({
            title: '请输入用户名和密码',
            icon: 'none'
        })
        return
    }

    try {
        isLogging.value = true

        // 显示获取微信授权的提示
        uni.showLoading({
            title: '获取微信授权...',
            mask: true
        })

        uni.login({
            provider: 'weixin',
            success: async function (loginRes) {
                try {
                    console.log("wxcode", loginRes.code);

                    // 切换到登录中的 loading
                    uni.showLoading({
                        title: '登录中...',
                        mask: true
                    })

                    try {
                        const res = await userApi.accountLogin({
                            yhm: form.value.username,
                            mm: form.value.password,
                            wdConfirmationCaptchaService: "0",
                            wechatCode: loginRes.code
                        })

                        uni.hideLoading()
                        console.log("account登录成功", res.data)
                        uni.$emit('login', res.data)
                        userStore.setUserInfo(res.data)
                        
                        handleClose()

                    } catch (error) {
                        console.error('登录失败：', error)
                        uni.showToast({
                            title: '登录失败',
                            icon: 'none'
                        })
                    } finally {
                        // 无论成功失败，都重置状态
                        isLogging.value = false
                        uni.hideLoading()
                    }
                } catch (outerError) {
                    console.error('登录过程出错：', outerError)
                    uni.showToast({
                        title: '登录失败',
                        icon: 'none'
                    })
                    isLogging.value = false
                    uni.hideLoading()
                }
            },
            fail: function (error) {
                console.error('获取微信授权失败：', error)
                uni.showToast({
                    title: '获取微信授权失败',
                    icon: 'none'
                })
                isLogging.value = false
                uni.hideLoading()
            }
        });

    } catch (e) {
        console.error('登录过程出错：', e)
        uni.showToast({
            title: '登录失败',
            icon: 'none'
        })
        isLogging.value = false
        uni.hideLoading()
    }
}
const handleImageError = (e) => {
    console.error('图片加载失败：', e)
}
</script>

<style scoped>
.login-popup {
    position: fixed;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    z-index: 9999;
    visibility: hidden;
}

.login-popup.show {
    visibility: visible;
}

.login-popup.show .popup-content {
    transform: translateY(0);
}

.mask {
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.6);
}

.popup-content {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    background: #fff;
    border-radius: 12rpx 12rpx 0 0;
    padding: 40rpx 30rpx;
    transform: translateY(100%);
    transition: transform 0.3s ease-out;
}

.popup-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 40rpx;
}

.title {
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
}

.close-btn {
    font-size: 48rpx;
    color: #999;
    padding: 20rpx;
    margin: -20rpx;
}

/* 微信登录按钮 */
.wechat-btn {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100%;
    height: 88rpx;
    background: #40ac6d;
    color: #fff;
    border-radius: 44rpx;
    font-size: 32rpx;
    border: none;
}

.wechat-icon {
    width: 48rpx;
    height: 48rpx;
    margin-right: 16rpx;
}

/* 分割线 */
.divider {
    position: relative;
    text-align: center;
    margin: 40rpx 0;
}

.divider::before,
.divider::after {
    content: '';
    position: absolute;
    top: 50%;
    width: calc(50% - 40rpx);
    height: 1px;
    background: #eee;
}

.divider::before {
    left: 0;
}

.divider::after {
    right: 0;
}

.divider-text {
    display: inline-block;
    padding: 0 20rpx;
    color: #999;
    font-size: 28rpx;
    background: #fff;
    position: relative;
    z-index: 1;
}

/* 账号密码登录 */
.account-login {
    margin-bottom: 30rpx;
}

.input-item {
    position: relative;
    margin-bottom: 20rpx;
}

.input-item input {
    width: 100%;
    height: 88rpx;
    background: #f5f5f5;
    border-radius: 44rpx;
    padding: 0 40rpx;
    font-size: 28rpx;
    box-sizing: border-box;
}

.eye-icon {
    position: absolute;
    right: 20rpx;
    /* 调整位置 */
    top: 50%;
    transform: translateY(-50%);
    padding: 20rpx;
    /* 增加点击区域 */
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1000;
}

.eye-image {
    width: 40rpx;
    height: 40rpx;
    display: block;
    pointer-events: none;

}

.placeholder {
    color: #999;
}

.account-btn {
    width: 100%;
    height: 88rpx;
    line-height: 88rpx;
    background: #666666;
    color: #fff;
    border-radius: 44rpx;
    font-size: 32rpx;
    border: none;
    margin-top: 30rpx;
    transition: all 0.3s ease;
}

.account-btn.disabled {
    background: #cccccc !important;
    color: #999999 !important;
    opacity: 0.6;
    cursor: not-allowed;
}

/* 用户协议 */
.agreement {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 30rpx;
}

.agreement-text {
    font-size: 24rpx;
    color: #999;
    margin-left: 8rpx;
}

.link {
    color: #40ac6d;
}

/* 按钮点击效果 */
.wechat-btn:active,
.account-btn:active {
    opacity: 0.8;
}
</style>