<template>
	<view class="wrap">
		<u-gap height="20" bg-color="#f5f5f5"></u-gap>
		<u-cell-group :border="false">
			<u-cell-item title="清除缓存" :arrow="false">
				<view slot="right-icon">
					{{ cacheSize }}
				</view>
			</u-cell-item>
		</u-cell-group>
		<view class="u-m-40">
			<u-button type="primary" @click="clearCache" :hair-line="false">清除缓存</u-button>
		</view>
	</view>
</template>
<script>
/**
 * Copyright (c) 2013-Now http://aidex.vip All rights reserved.
 */
export default {
	data() {
		return {
			cacheSize: '计算中...'
		};
	},
	onLoad() {
		this.calculateCacheSize();
	},
	methods: {
		navTo(url) {
			uni.navigateTo({
				url: url
			});
		},
		clearCache() {
			uni.showModal({
				title: '提示',
				content: '确定要清除缓存吗？',
				success: (res) => {
					if (res.confirm) {
						this.performClearCache();
					}
				}
			});
		},
		performClearCache() {
			try {
				// 清除本地存储
				uni.clearStorageSync();
				
				// 清除Vuex状态（除了必要的配置）
				this.$store.dispatch('updateUserInfo', null);
				
				// 重新计算缓存大小
				this.calculateCacheSize();
				
				uni.showToast({
					title: '缓存清除成功',
					icon: 'success',
					duration: 2000
				});
				
				// 延迟跳转到登录页面
				setTimeout(() => {
					uni.reLaunch({
						url: '/pages/sys/login/index'
					});
				}, 2000);
				
			} catch (error) {
				console.error('清除缓存失败:', error);
				uni.showToast({
					title: '清除缓存失败',
					icon: 'none',
					duration: 2000
				});
			}
		},
		calculateCacheSize() {
			try {
				// 获取本地存储信息
				const storageInfo = uni.getStorageInfoSync();
				const currentSize = storageInfo.currentSize || 0;
				
				// 转换为合适的单位显示
				if (currentSize < 1024) {
					this.cacheSize = currentSize + 'KB';
				} else if (currentSize < 1024 * 1024) {
					this.cacheSize = (currentSize / 1024).toFixed(1) + 'MB';
				} else {
					this.cacheSize = (currentSize / (1024 * 1024)).toFixed(1) + 'GB';
				}
				
				// 如果没有缓存数据，显示0KB
				if (currentSize === 0) {
					this.cacheSize = '0KB';
				}
				
			} catch (error) {
				console.error('获取缓存大小失败:', error);
				this.cacheSize = '未知';
			}
		}
	}
};
</script>
<style lang="scss">
@import '../home/index.scss';

page {
	background-color: #f8f8f8;
}

::v-deep( .u-cell-title) {
	padding: 25rpx 30rpx;
	font-size: 30rpx;
}
</style>
