<script setup lang="ts">
    import { useRuntime } from '@/hooks/app/useRuntime'
    import ConfirmDialog from '@/components/ConfirmDialog/index.vue'

    import { convertKB } from '@/utils'
    import { calculateCacheSize, cleanCache } from '@/components/CacheImage/index'
    import { useUserStore } from '@/store/modules/user'
    import { useFarmStore } from '@/store/modules/farm'
    import { checkUpgrade } from '@/utils/upgrade'
    import * as NongchangAPI from '@/api/model/nongchang'

    // import { Permissions, usePermissions } from '@/components/Permissions'
    // import { useUserPermissions } from '@/utils/auth'

    // const [registerPermissions, { request }] = usePermissions()

    const userStore = useUserStore()
    const farmStore = useFarmStore()
    const { app } = useRuntime()
    const version = computed(() => app.value.version)

    onShow(() => {
        const { id, realname, phone, avatar } = userStore.getUserInfo
        model.id = id
        model.realname = realname
        model.phone = phone
        if (avatar) {
            model.avatar = avatar
        }
    })
    // 个人信息
    function navMsg() {
        uni.navigateTo({
            url: '/pages/mine/components/myMessage',
        })
    }
    // 退出登录
    function logOut() {
        model.showLogoutDialog = true
    }

    // 确认退出
    function handleConfirmLogout() {
        loginOut()
    }

    // 调用登出
    function loginOut() {
        model.loading = true
        userStore.logout().finally(() => {
            model.loading = false
        })
    }

    /**
     * 计算缓存
     */
    function calculateCache() {
        // 重新计算
        const cacheIamgeSizeTotal = calculateCacheSize()
        const { size: currentStorageSize, unit: currentStorageSizeUnit } = convertKB(cacheIamgeSizeTotal / 1024)

        // 更新视图
        items.find((item) => item.title === '系统缓存清除').suffix =
            Number(currentStorageSize) === 0 ? '' : `${currentStorageSize}${currentStorageSizeUnit}`
    }

    const model = reactive({
        id: '',
        avatar: '/static/logo.png',
        realname: '',
        phone: '',
        show: false,
        descr: '',
        state: '',
        version: '',
        loading: false,
        showLogoutDialog: false,
    })

    // 用户默认层级
    // const { isPermission } = useUserPermissions('user_default_zIndex_btn')
    // 用户应急管理
    // const { isPermission: emergencyPermission } = useUserPermissions('emergency_response_btn')
    const pageData = reactive({
        farmsListTotal: 0,
    })
    const items = reactive<Recordable[]>([
        {
            title: '我的农场',
            icon: 'nongchang2',
            disabled: false,
            show: true,
            handle: () => {
                if (pageData.farmsListTotal > 0) {
                    uni.navigateTo({
                        url: '/pages/wode/wode',
                    })
                } else {
                    uni.navigateTo({
                        url: '/pages/nongchang/create-nongchang-form',
                    })
                }
            },
        },
        {
            title: '我的基地',
            icon: 'jidi',
            disabled: false,
            show: true,
            handle: () => {
                uni.navigateTo({
                    url: '/pages/jidiguanli/jidiguanli',
                })
            },
        },

        {
            title: '问题意见反馈',
            icon: 'feedback',
            disabled: false,
            show: true,
            handle: () => {
                uni.navigateTo({
                    url: '/pages/common/feedback/index',
                })
            },
        },
        {
            title: '系统缓存清除',
            icon: 'clean',
            suffix: '',
            show: true,
            handle: (item: Recordable) => {
                if (!item.suffix) {
                    return
                }

                Message.confirm('确认清除缓存?', '温馨提示').then(async (confirm) => {
                    if (confirm) {
                        Message.loading('清理中...')

                        try {
                            // 清理缓存
                            await cleanCache()

                            // 重新计算
                            calculateCache()
                        } finally {
                            // 延迟提示
                            setTimeout(() => {
                                Message.toast('缓存清除成功')
                                Message.hideLoading()
                            }, 500)
                        }
                    }
                })
            },
        },
        {
            title: '系统检查更新',
            icon: 'update',
            suffix: '',
            show: !userStore.isAuditMode,
            handle: () => {
                // #ifdef APP-PLUS
                // 检查更新
                checkUpgrade(true)
                // #endif
            },
        },
        {
            title: `关于${$app.name}`,
            icon: 'about',
            show: true,
            handle: () => {
                uni.navigateTo({
                    url: '/pages/common/about/index',
                })
            },
        },
    ])

    function getFarmsList() {
        NongchangAPI.farmsList({
            pageNo: 1,
            pageSize: 10,
        }).then((res) => {
            console.log(res)
            const { total } = res
            pageData.farmsListTotal = total
            if (res.records.length) {
                farmStore.setFarmInfo(res.records[0])
            }
        })
    }

    onShow(() => {
        getFarmsList()
        // 计算缓存
        calculateCache()
    })

    watch(
        () => version.value,
        (value) => {
            if (value) {
                items.find((item) => item.title === '系统检查更新').suffix = `v${value}`
            }
        },
    )
</script>

<template>
    <view class="main page-bg">
        <view class="w-full h-170 flex flex-row items-center avatar pl-6">
            <CacheImage
                :src="model.avatar"
                width="150"
                height="150"
                radius="999"
                background="transparent"
                style="box-shadow: 0 0 10rpx #cdcdcd"
                @click="navMsg"
            />
            <view class="flex flex-col ml-50rpx">
                <text class="text-#fff" style="text-shadow: 0 0 10rpx #888">{{ model.realname }}</text>
                <view class="max-w-400rpx mt-20rpx flex-center">
                    <fui-overflow-hidden
                        width="100%"
                        size="24"
                        color="#fff"
                        :text="model.phone ? `${model.phone}` : '- -'"
                    />
                </view>
            </view>
        </view>
        <view class="px-6 pt-4">
            <view class="w-full h-130rpx pl-3 border-rd-lg bg-#fff flex justify-between items-center">
                <view class="w-40% flex flex-row">
                    <image src="/static/images/codefun/shield.png" class="w-100 h-100" />
                    <view class="color-#FFAA1E text-50 line-height-loose">{{
                        userStore.getUserInfo?.creditScore
                    }}</view>
                </view>
                <view class="w-60%">
                    <view class="text-25">信用评级: 良好</view>
                    <view class="text-23 color-#686868">完善信息提升20分</view>
                </view>
            </view>
            <fui-list class="rd-3 overflow-hidden shadow !mt-20rpx" :top-border="false">
                <fui-list-cell
                    arrow
                    v-for="(item, index) in items.slice(2, 10)"
                    :key="index"
                    :bottom-border="false"
                    class="pos-relative"
                    :class="{ disabled: item.disabled }"
                    v-show="item.show"
                    @tap="item.handle(item)"
                >
                    <CacheImage
                        :src="`/static/images/mine/${item.icon}.png`"
                        width="42"
                        height="42"
                        background="transparent"
                    />
                    <text class="ml-3.5 text-30 text-#333333 font-500">{{ item.title }}</text>
                    <text
                        v-if="item.suffix"
                        class="pos-absolute right-70"
                        :style="{ color: item.icon === 'call' ? '#1890FF' : '#999' }"
                    >
                        {{ item.suffix }}
                    </text>
                </fui-list-cell>
            </fui-list>
        </view>
        <view class="p-6 pt-5 pb-2">
            <fui-button
                class="shadow"
                background="#fff"
                radius="18rpx"
                color="#4da25b"
                @click="logOut"
                :disabled="model.loading"
                :loading="model.loading"
            >
                退出登录
            </fui-button>
        </view>

        <!-- 退出登录确认对话框 -->
        <ConfirmDialog
            v-model:show="model.showLogoutDialog"
            title="退出登录"
            content="确认退出当前账号?"
            cancelText="取消"
            confirmText="确认"
            @confirm="handleConfirmLogout"
        />

        <!-- 权限提示组件 -->
        <!-- <Permissions @register="registerPermissions" /> -->
    </view>
</template>

<style lang="less" scoped>
    .main {
        width: 100%;
        height: 100%;
        // #ifdef H5
        height: calc(100vh - 60px - 44px);
        // #endif
    }

    .page-bg {
        background: url('/static/images/codefun/7a5dc4ee864fe55da98b41c14ee3b931.png') no-repeat top center;
        background-size: 100%;
    }

    .userInfo_box {
        background: #fff;
        padding: 32rpx 30rpx;
        display: flex;
        align-items: center;
        padding-top: 120rpx;

        .user_info {
            height: 125rpx;
            margin-left: 32rpx;
            display: flex;
            flex-direction: column;
            justify-content: space-around;
        }
    }

    .fui-color-border {
        border-color: #fff;
    }

    .me_action {
        margin-top: 20rpx;
    }

    .fui-list__item {
        flex: 1;
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: space-between;
    }

    .fui-text__explain {
        font-size: 28rpx;
        color: #7f7f7f;
        flex-shrink: 0;
    }

    .fui-list__img {
        width: 48rpx;
        height: 48rpx;
        margin-right: 10rpx;
    }

    .action_text {
        font-size: 32rpx;
    }

    .loginout {
        height: 104rpx;
        background: #fff;
        font-weight: 400;
        color: #1890ff;
        font-size: 32rpx;
        text-align: center;
        line-height: 104rpx;
        margin-top: 20rpx;
    }

    .avatar {
        font-weight: bold;
        color: #fff;
    }

    .border-bottom {
        &.disabled {
            pointer-events: none;

            * {
                color: gray;
            }
        }
    }
</style>
