<template>
    <view>
        <view class="mine-container">

            <view class="mine-header" :style="{ paddingTop: globalData.navBarHeight + 'px' }">
                <view class="flex_c_s mine-header-info">
                    <img :show-loading="true" :src="userInfo.avatar" class="header-avatar" />
                    <view class="header-info flex_c_s">
                        <view class="info-top ">
                            <view class="user-info flex_c_c">
                                <view class="info-name" @click="onLogin">{{
                                    userInfo.nickName
                                }}</view>
                                <view class="info-tag flex_c_c" v-if="userType">{{ userType === 1 ? '用户' : '志愿者' }}
                                </view>
                            </view>
                            <view class="info-real-name flex_c_c">
                                <view class="real-name">{{ authentication ? '已实名' : '暂未实名' }}</view>
                                <img src="/static/serverImg/mine/suce.png" alt="" style="width: 24rpx; height: 24rpx;"
                                    v-if="authentication">
                                <img src="/static/serverImg/mine/left.png" alt="" style="width: 24rpx; height: 24rpx;"
                                    v-else>


                            </view>
                        </view>
                        <img src="/static/serverImg/mine/setting.png" alt="" style="width: 40rpx; height: 40rpx;"
                            @click="handLsetTing">
                    </view>
                </view>
                <view class="applause-rate flex_c_c" v-if="userType === 2">
                    <view class="rate-lable">好评率:</view>
                    <view class="rate-value">{{ rateValue }}星</view>
                    <view v-for="(item, index) in new Array(5)" :key="item">
                        <img src="/static/serverImg/mine/flower.png" v-if="rateValue <= index" alt="" class="flower" />
                        <img src="/static/serverImg/mine/flower_active.png" v-else alt="" class="flower" />
                    </view>
                </view>

                <view class="order-main flex_c_s" v-if="userType === 1">
                    <view v-for="item in orderMainList" :key="item.iconName" class="order-item flex_c_c_f">
                        <view class="order-num">
                            {{ data[item.key] }}
                        </view>
                        <view>
                            {{ item.name }}
                        </view>
                    </view>
                </view>
            </view>

            <view class="price-main ">
                <view class="price-card flex_c_c">
                    <view v-for="item in priceList" :key="item.key" class="price-item flex_c_c" @click="onClick(item)">
                        <view class="flex_c_c_f">
                            <view class="price-balance">{{ data[item.key] }}</view>
                            <view class="price-name flex_c_c">
                                <view class="price-name-text">{{ item.name }}</view>

                            </view>
                        </view>
                        <img src="/static/serverImg/mine/rigth.png" alt="" class="price-rigth"
                            style="width: 24rpx;height: 24rpx;" />
                    </view>
                </view>
            </view>

            <view class="list-main">
                <view class="list-box">
                    <view v-for="item in list" :key="item.key" class="list-item flex_c_s" @click="onClick(item)">
                        <view class="list-left flex_c_l">
                            <img :src="item.img" alt="" style="width: 56rpx;height: 56rpx;">
                            <view class="list-name">{{ item.name }}</view>
                        </view>
                        <view class="list-rigth flex_c_r">
                            <view class="list-text">{{ item.text }}</view>
                            <up-icon name="arrow-right"></up-icon>
                        </view>
                    </view>
                </view>
            </view>


        </view>
        <CustomTabBar page="mine" />
        <up-popup :show="show" mode="center" @close="close" @open="open">
            <view v-if="show">
                <QRCode scene="123" page="/pages/index/index" width="430" auto-color line-color="#000000" is-hyaline>
                </QRCode>
            </view>
        </up-popup>
    </view>
</template>

<script setup>
import { onMounted, ref, computed } from 'vue'
import { onLoad, onShow } from '@dcloudio/uni-app'
import store from '@/store'
import { getVolunteerAccountInfo, volunteerOrderStatistics, getAccountInfo } from '@/api/mine'
import CustomTabBar from '@/components/CustomTabBar/index.vue'
import QRCode from '@/components/QRCode/index.vue'
import { getNavBarHeight } from '@/utils/index.js'
import { getToken } from '@/utils/auth'
import { showConfirm } from '@/utils/common'
import {
    userOrWorker
} from '@/api/login';
const show = ref(false); // 是否显示二维码
const userInfo = ref({
    avatar: '/static/serverImg/mine/user.png',
    nickName: '登陆/注册',
})

const authentication = ref(false);//是否认证

const globalData = ref({
    statusBarHeight: 47,
    navBarHeight: 91,
})
const data = ref({
    balance: 0.0,
    reservationCount: 0,
    doingCount: 0,
    finishedCount: 0,
    cancelCount: 0,
    orderCount: 0,
    orderFrozenBalance: 0,

    browsing: 0,
    collect: 0,
    comment: 0
})
const rateValue = ref(5)

const orderMainList = [
    {
        name: '浏览记录',
        key: 'browsing',
    },
    {
        name: '收藏',
        key: 'collect',
    },
    {
        name: '评论',
        key: 'comment',
    },

]


const priceUser = [
    {
        name: '我的钱包(元)',
        key: 'balance',
        decimals: 2,
        balance: 'orderFrozenBalance',
        page: '/pages_mine/pages/wallet/index',
    },
    {
        name: '我的积分',
        key: 'orderCount',
        decimals: 0,
        page: '/pages_mine/pages/integral/index',
    },
]
const priceAdmin = [
    {
        name: '我的余额',
        key: 'balance',
        decimals: 2,
        balance: 'orderFrozenBalance',
        page: '/pages_mine/pages/wallet/index',
    },
    {
        name: '预约单数',
        key: 'orderCount',
        decimals: 0,
        switchPage: '/pages/classify',
        value: 1,
    },
]

const priceList = computed(() => {
    if (userType === 1) {
        return priceUser
    }
    return priceAdmin
})

const userType = uni.getStorageSync('userType') //读取本地存储

const adminList = [
    {
        name: '我的地址',
        img: '/static/serverImg/mine/adress.png',
        key: 'map',
        text: '',
        page: '/pages_mine/pages/selectAddress/index',
    },
    {
        name: '帮助与客服',
        img: '/static/serverImg/mine/kf.png',
        key: 'map',
        text: '',
        operate: () => {
            uni.navigateTo({
                url: `/pages_orderuser/pages/talk/pages/index/index?customerService=true&conversationType=3`
            })
        },
    },
    {
        name: '我的评论',
        key: 'share',
        img: '/static/serverImg/mine/yq.png',
        text: '查看所有订单',
        switchPage: '/pages/classify',
        value: 3,
    },
    // {
    //     name: '修改个人信息',
    //     img: '/static/serverImg/mine/xg.png',
    //     key: 'map',
    //     text: '去认证资质',
    //     operate: () => {
    //         handLsetTing();
    //     },
    // },
    {
        name: '成为用户',
        img: '/static/serverImg/mine/sf.png',
        key: 'map',
        text: '切换身份',
        operate: () => {
            switchUserType(1)
        },
    },

]
const userList = [
    {
        name: '我的地址',
        img: '/static/serverImg/mine/adress.png',
        key: 'map',
        text: '',
        page: '/pages_mine/pages/selectAddress/index',
    },
    {
        name: '帮助与客服',
        img: '/static/serverImg/mine/kf.png',
        key: 'map',
        text: '',
        operate: () => {
            uni.navigateTo({
                url: `/pages_orderuser/pages/talk/pages/index/index?customerService=true&conversationType=3`
            })
        },
    },
    {
        name: '邀请二维码',
        key: 'share',
        img: '/static/serverImg/mine/yq.png',
        text: '推荐好友得好礼',
        operate: () => {
            show.value = true
        },
    },
    // {
    //     name: '修改个人信息',
    //     img: '/static/serverImg/mine/xg.png',
    //     key: 'map',
    //     text: '去实名认证',
    //     operate: () => {
    //         handLsetTing();
    //     },
    // },
    {
        name: '成为志愿者',
        img: '/static/serverImg/mine/sf.png',
        key: 'map',
        text: '切换身份',
        operate: () => {
            switchUserType(2)
        },
    },
]


const switchUserType = (userType) => {
    uni.setStorageSync('userType', userType)
    store.dispatch('GetInfo').then((res) => {
        userInfo.value = store.state.user
        userOrWorker({ userType: userType })
            .then(res => {
                console.log("TCL: loginSuccess -> res", res)
                uni.reLaunch({
                    url: '/pages/index',
                })
            })
    })
        .catch(err => {
            console.error('设置失败:', err);
        });
}

const list = computed(() => {
    if (userType === 1) {
        return userList
    }
    return adminList
})

function open() {  //弹框打开逻辑
    // 打开逻辑，比如设置 show 为 true  
    show.value = true;
}

function close() {
    // 关闭逻辑，设置 show 为 false  
    show.value = false;
}

const onLogin = () => {
    const token = getToken()
    !token &&
        showConfirm('您还未登陆系统，是否前往登陆?').then((res) => {
            if (res.confirm) {
                store.dispatch('LogOut').then((res) => {
                    uni.reLaunch({ url: '/pages/login' })
                })
            }
        })
}

const onLogou = () => {
    showConfirm('确认退出登陆吗？').then((res) => {
        if (res.confirm) {
            store.dispatch('LogOut').then((res) => {
                // uni.reLaunch({ url: '/pages/login' })
                uni.reLaunch({
                    url: '/pages/index',
                })
            })
        }
    })
}
const onClick = (record) => {
    console.log('record', record, record.page)
    if (record.page) {
        uni.navigateTo({
            url: record.page,
        })
    }
    if (record.operate) {
        record.operate()
    }

    if (record.switchPage && record.value) {
        const app = getApp()
        app.globalData.switchTabParams = {
            tabKey: record.value,
        }
        // JS跳转
        uni.switchTab({
            url: record.switchPage,
        })
        return
    }
}

const getDetails = async () => {
    try {
        // const res = await getVolunteerAccount();
        // console.log('res',res);
    } catch (error) {
        console.log('error', error)
    }
}

const handLsetTing = () => {
    uni.navigateTo({
        url: '/pages_mine/pages/setupUser/index',
    })
}

const geUserInfo = () => {
    console.log(store.state.user, '>>>>99')
    userInfo.value = store.state.user
    // store.dispatch('GetInfo').then((res) => {
    // 	userInfo.value = store.state.user
    // });
}

onShow(() => {
    const token = getToken()
    // console.log("TCL: token", token)
    if (token) {
        geUserInfo()
        init()
    }

})
onMounted(() =>{
    getNav()
})

const init = async () => {
    try {
        // uni.hideLoading();
        uni.showLoading({
            title: '数据加载中...',
        })

        if (userType === 2) {
            const res1 = await getVolunteerAccountInfo()
            const res2 = await volunteerOrderStatistics()
            data.value = {
                ...res1.data,
                ...res2.data,
            }
            console.log(11, res1, res2, data.value, userType)
        }
        if (userType === 1) {
            const res = await getAccountInfo();
            data.value = {
                ...data.value,
                ...res.data,
            };
        }

    } catch (error) {
        console.log('error', error)
        uni.showToast({
            title: error.msg,
            icon: 'error',
        })
    } finally {
        uni.hideLoading()
    }
}

const getNav = async () => {
    try {
        const res = await getNavBarHeight();
        globalData.value = res;
        console.log("TCL: getNav -> res", res)
    } catch (error) {

    }
}

</script>

<style lang="scss" scoped>
@import "./index.scss";
</style>