<template>
    <view class="data-page">
        <!-- 头像卡片 -->
        <view class="data-card">
            <view class="data-card__item data-card__avatar-row" @tap="chooseAvatar">
                <view class="data-card__avatar-left">
                    <image class="data-card__avatar" :src="defaultAvatar" mode="aspectFill" />
                    <text class="data-card__avatar-text">{{ userInfo?.nickname || '用户' }}</text>
                </view>
                <u-icon name="arrow-right" size="20" color="#737373" />
            </view>
        </view>

        <!-- 个人信息卡片 -->
        <view class="data-card">
            <view class="data-card__item data-card__item--border"
                @tap="; (showUserName = true), (newUsername = userInfo?.username)">
                <text class="data-card__label">账号</text>
                <view class="data-card__right">
                    <text class="data-card__value">{{ userInfo?.account }}</text>
                    <u-icon name="arrow-right" size="20" color="#737373" />
                </view>
            </view>
            <view class="data-card__item data-card__item--border"
                @tap="; (showNickName = true), (newNickname = userInfo?.nickname)">
                <text class="data-card__label">昵称</text>
                <view class="data-card__right">
                    <text class="data-card__value">{{ userInfo?.nickname }}</text>
                    <u-icon name="arrow-right" size="20" color="#737373" />
                </view>
            </view>
            <view class="data-card__item data-card__item--border" @tap="changeSex">
                <text class="data-card__label">性别</text>
                <view class="data-card__right">
                    <text class="data-card__value">{{ userInfo?.sex }}</text>
                    <u-icon name="arrow-right" size="20" color="#737373" />
                </view>
            </view>
            <view class="data-card__item data-card__item--border">
                <text class="data-card__label">手机号</text>
                <view class="data-card__right">
                    <text class="data-card__value">{{ userInfo?.mobile || '未绑定' }}</text>
                    <!-- #ifdef MP-WEIXIN -->
                    <u-button open-type="getPhoneNumber" @getphonenumber="getPhoneNumber" type="primary" shape="circle"
                        size="mini" :plain="true">
                        {{ userInfo?.mobile == '' ? '绑定手机号' : '更换手机号' }}
                    </u-button>
                    <!-- #endif -->
                    <!-- #ifndef MP-WEIXIN -->
                    <view class="data-card__action" @tap="showMobilePop = true">
                        <text>{{ userInfo?.mobile == '' ? '绑定手机号' : '更换手机号' }}</text>
                    </view>
                    <!-- #endif -->
                </view>
            </view>
            <view class="data-card__item">
                <text class="data-card__label">注册时间</text>
                <text class="data-card__value">{{ userInfo?.create_time }}</text>
            </view>
        </view>

        <!-- 昵称修改组件 -->
        <u-popup v-model="showNickName" :closeable="true" mode="center" :maskCloseAble="false" border-radius="20">
            <view class="px-[50rpx] py-[40rpx] bg-white" style="width: 85vw">
                <form @submit="changeNameConfirm">
                    <view class="mb-[70rpx] text-xl text-center">修改昵称</view>
                    <u-form-item borderBottom>
                        <input class="nr h-[60rpx] w-full" :value="userInfo.nickname" name="nickname" type="nickname"
                            placeholder="请输入昵称" />
                    </u-form-item>
                    <view class="mt-[80rpx]">
                        <button class="text-white w-full h-[80rpx] !text-lg !leading-[80rpx] rounded-full"
                            form-type="submit" size="mini" hover-class="none" style="background: #185dff">
                            确定
                        </button>
                    </view>
                </form>
            </view>
        </u-popup>

        <!-- 账号修改组件 -->
        <u-popup v-model="showUserName" :closeable="true" mode="center" border-radius="20">
            <view class="px-[50rpx] py-[40rpx] bg-white" style="width: 85vw">
                <view class="mb-[70rpx] text-xl text-center">修改账号</view>
                <u-form-item borderBottom>
                    <u-input class="flex-1" v-model="newUsername" placeholder="请输入账号" :border="false" />
                </u-form-item>
                <view class="mt-[80rpx]">
                    <u-button @click="changeUserNameConfirm" shape="circle"
                        :custom-style="{ background: '#185dff', color: '#fff', borderColor: '#185dff' }">
                        确定
                    </u-button>
                </view>
            </view>
        </u-popup>

        <!-- 性别修改组件 -->
        <u-picker mode="selector" v-model="showPicker" confirm-color="#4173FF" :default-selector="[0]" :range="sexList"
            @confirm="changeSexConfirm" />

        <!-- 账号修改组件 -->
        <u-popup v-model="showMobilePop" :closeable="true" mode="center" border-radius="20">
            <view class="px-[50rpx] py-[40rpx] bg-white" style="width: 85vw">
                <view class="mb-[70rpx] text-xl text-center">{{ userInfo?.mobile == '' ? '绑定手机号' : '更换手机号' }}</view>
                <u-form-item borderBottom>
                    <u-input class="flex-1" v-model="newMobile" placeholder="请输入新的手机号码" :border="false" />
                </u-form-item>
                <u-form-item borderBottom>
                    <u-input class="flex-1" v-model="mobileCode" placeholder="请输入验证码" :border="false" />
                    <view class="border-l border-solid border-0 border-light pl-3 text-muted leading-4 ml-3 w-[180rpx]"
                        @click="sendSms">
                        <u-verification-code ref="uCodeRef" :seconds="60" @change="codeChange" change-text="x秒" />
                        {{ codeTips }}
                    </view>
                </u-form-item>
                <view class="mt-[80rpx]">
                    <u-button @click="changeCodeMobile" type="primary" shape="circle"> 确定 </u-button>
                </view>
            </view>
        </u-popup>
    </view>
</template>

<script lang="ts" setup>
import { ref, shallowRef, computed } from 'vue'
import { onShow, onUnload } from '@dcloudio/uni-app'
import { getUserInfo, userEdit, userBindMobile, userMnpMobile } from '@/api/user'
import { getVerifyInfo } from '@/api/app'
import { FieldType } from '@/enums/appEnums'
import { useAppStore } from '@/stores/app'

const appStore = useAppStore()

// 用户信息
const userInfo = ref<any>({})
const defaultAvatar = computed(() => {
    const logo = appStore.config?.website?.shop_logo
    if (!logo) return '/static/images/avatar.png'
    if (logo.startsWith('http')) return logo
    return (appStore.config?.domain || '') + logo
})

const chooseAvatar = () => {
    uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
            const tempFilePath = res.tempFilePaths[0]
            uni.uploadFile({
                url: (appStore.config?.domain || '') + '/api/upload/image',
                filePath: tempFilePath,
                name: 'file',
                header: {
                    token: uni.getStorageSync('token')
                },
                success: (uploadRes) => {
                    const data = JSON.parse(uploadRes.data)
                    if (data.code === 1 && data.data?.uri) {
                        handleAvatarChange(data.data.uri)
                    }
                }
            })
        }
    })
}
// 用户信息的枚举
const fieldType = ref(FieldType.NONE)
//选择性别数据
const sexList = ref<Array<string> | null>(['男', '女'])

//显示昵称弹窗
const showNickName = ref<boolean | null>(false)
//显示账户弹窗
const showUserName = ref<boolean | null>(false)
//显示性别选择弹窗
const showPicker = ref<boolean | null>(false)
// 显示手机号验证码调整弹窗 非小程序才需要
const showMobilePop = ref<boolean | null>(false)

//新昵称
const newNickname = ref<string>('')
//新账号
const newUsername = ref<string>('')
//新的手机号码
const newMobile = ref<string>('')

//修改手机验证码
const mobileCode = ref<string>('')
const codeTips = ref('')
const uCodeRef = shallowRef()

// 获取用户信息
const getUser = async (): Promise<void> => {
    userInfo.value = await getUserInfo()
}

// 获取验证码显示字段
const codeChange = (text: string) => {
    codeTips.value = text
}

// 发送验证码
const sendSms = async () => {
    if (!newMobile.value) return uni.$u.toast('请输入新的手机号码')
    if (!uCodeRef.value?.canGetCode) return

    try {
        const scene = userInfo.value.mobile ? 'change' : 'bind'
        const data: any = await getVerifyInfo({ mobile: newMobile.value, scene })
        const phone = data.phone
        const code = data.code

        mobileCode.value = code
        uCodeRef.value?.start()

        uni.showModal({
            title: '发送验证短信',
            content: `请发送短信到 ${phone}\n发送内容：${code}\n\n点击确定将打开短信编辑界面`,
            confirmText: '发送短信',
            success: (res) => {
                if (res.confirm) {
                    // #ifdef APP-PLUS
                    try {
                        // @ts-ignore
                        const main = plus.android.runtimeMainActivity()
                        // @ts-ignore
                        const Intent = plus.android.importClass('android.content.Intent')
                        // @ts-ignore
                        const Uri = plus.android.importClass('android.net.Uri')
                        // @ts-ignore
                        const intent = new Intent(Intent.ACTION_SENDTO, Uri.parse('smsto:' + phone))
                        // @ts-ignore
                        intent.putExtra('sms_body', code)
                        // @ts-ignore
                        main.startActivity(intent)
                    } catch (e) {
                        uni.$u.toast('无法打开短信应用')
                    }
                    // #endif
                    // #ifdef H5
                    window.location.href = `sms:${phone}?body=${code}`
                    // #endif
                }
            }
        })
    } catch (error: any) {
        uni.$u.toast(error || '获取验证信息失败')
    }
}

const handleAvatarChange = (value) => {
    fieldType.value = FieldType.AVATAR
    setUserInfoFun(value)
}

// 验证码修改手机号-非微信小程序
const changeCodeMobile = async () => {
    await userBindMobile({
        type: userInfo.value.mobile ? 'change' : 'bind',
        mobile: newMobile.value,
        code: mobileCode.value
    })
    uni.$u.toast('操作成功')
    showMobilePop.value = false
    getUser()
}

// 修改用户信息
const setUserInfoFun = async (value: string): Promise<void> => {
    await userEdit({
        field: fieldType.value,
        value: value
    })
    uni.$u.toast('操作成功')
    getUser()
}

// 显示修改用户性别弹窗
const changeSex = () => {
    showPicker.value = true
    fieldType.value = FieldType.SEX
}

// 修改用户性别
const changeSexConfirm = (value) => {
    setUserInfoFun(value[0] + 1)
    showPicker.value = false
}

// 修改用户账号
const changeUserNameConfirm = () => {
    if (newUsername.value == '') return uni.$u.toast('账号不能为空')
    if (newUsername.value.length > 10) return uni.$u.toast('账号长度不得超过十位数')

    fieldType.value = FieldType.USERNAME
    setUserInfoFun(newUsername.value)
    showUserName.value = false
}

// 修改用户昵称
const changeNameConfirm = async (e: any) => {
    newNickname.value = e.detail.value.nickname
    if (newNickname.value == '') return uni.$u.toast('昵称不能为空')
    if (newNickname.value.length > 10) return uni.$u.toast('昵称长度不得超过十位数')
    fieldType.value = FieldType.NICKNAME
    await setUserInfoFun(newNickname.value)

    showNickName.value = false
}

// 微信小程序 绑定｜｜修改用户手机号
const getPhoneNumber = async (e): Promise<void> => {
    const { encryptedData, iv, code } = e.detail
    const data = {
        code,
        encrypted_data: encryptedData,
        iv
    }
    if (encryptedData) {
        await userMnpMobile({
            ...data
        })
        uni.$u.toast('操作成功')
        getUser()
    }
}

const goPage = (url: string) => {
    uni.navigateTo({
        url: url
    })
}

onShow(async () => {
    getUser()
})

onUnload(() => { })
</script>

<style lang="scss" scoped>
.data-page {
    min-height: 100vh;
    background: #f5f5f5;
}

.data-card {
    margin: 20rpx 16rpx 0;
    background: #fff;
    border-radius: 12rpx;
    overflow: hidden;

    &__item {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 0 32rpx;
        height: 110rpx;

        &--border {
            position: relative;

            &::after {
                content: '';
                position: absolute;
                left: 32rpx;
                right: 32rpx;
                bottom: 0;
                height: 1rpx;
                background: #f2f2f2;
            }
        }
    }

    &__avatar-row {
        height: 160rpx;
    }

    &__avatar-left {
        display: flex;
        align-items: center;
        gap: 20rpx;
    }

    &__avatar {
        width: 96rpx;
        height: 96rpx;
        border-radius: 12rpx;
        flex-shrink: 0;
    }

    &__avatar-text {
        font-size: 28rpx;
        color: #666;
    }

    &__label {
        font-size: 28rpx;
        color: #000;
    }

    &__right {
        display: flex;
        align-items: center;
        gap: 8rpx;
    }

    &__value {
        font-size: 28rpx;
        color: #666;
    }

    &__action {
        padding: 8rpx 20rpx;
        background: #e5edff;
        border-radius: 24rpx;

        text {
            font-size: 24rpx;
            color: #185dff;
        }
    }
}
</style>
