<template>
	<view class="container">
		<!-- 用户信息卡片 -->
		<view class="user-card">
			<view class="user-header">
				<image class="avatar" :src="userInfo.avatar || '/static/icons/user_icon.png'"></image>
				<view class="user-detail" v-if="isLogin">
					<text class="nickname">{{userInfo.nickName}}</text>
					<!-- <text class="user-id">性别: {{userInfo.sex == '0' ? '男' :'女' || '未知'}}</text> -->
				</view>
				<view class="user-detail" v-else>
					<text class="login-text" @click="navigateToLogin">登录/注册</text>
				</view>
			</view>
		</view>

		<!-- 地块信息 -->
		<view class="info-card">
			<view class="card-title">
				<text>我的地块</text>
				<text class="more" @click="navigateToPlots">查看更多 ></text>
			</view>
			<view class="plot-info">
				<view class="plot-item">
					<text class="number">{{ plotInfo.total }}</text>
					<text class="label">总地块数</text>
				</view>
				<view class="plot-item">
					<text class="number">{{ plotInfo.active }}</text>
					<text class="label">种植中</text>
				</view>
				<view class="plot-item">
					<text class="number">{{ plotInfo.idle }}</text>
					<text class="label">空闲</text>
				</view>
			</view>
		</view>

		<!-- 农业服务 -->
    <view class="info-card">
      <view class="card-title">
        <text>农业服务</text>
      </view>
      <view class="service-grid">
        <view 
          class="service-item" 
          v-for="(item, index) in serviceList" 
          :key="index"
          @click="navigateToService(item)"
        >
          <view class="service-icon">
            <image v-if="item.iconSvg" class="icon-svg" :src="item.iconSvg"></image>
            <text v-else>{{ item.iconText }}</text>
          </view>
          <text class="service-name">{{ item.name }}</text>
        </view>
      </view>
    </view>


		<!-- 常用功能 -->
		<view class="info-card">
			<view class="function-list">
				<view class="function-item" @click="handleContact">
					<view class="left">
						<text>联系客服</text>
					</view>
					<text class="arrow">></text>
				</view>
				<view class="function-item" @click="viewTerms">
					<view class="left">
						<text>用户协议</text>
					</view>
					<text class="arrow">></text>
				</view>
				<view class="function-item" @click="viewPrivacy">
					<view class="left">
						<text>隐私政策</text>
					</view>
					<text class="arrow">></text>
				</view>

<!--        <view class="function-item" @click="navigateToSettings">
          <view class="left">
            <text>系统设置</text>
          </view>
          <text class="arrow">></text>
        </view> -->
				<view v-if="isLogin" class="function-item" @click="handleLogout">
					<view class="left">
						<!-- <text class="function-icon">退</text> -->
						<text>退出登录</text>
					</view>
					<text class="arrow">></text>
				</view>
			</view>
		</view>
	</view>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { onShow } from '@dcloudio/uni-app'
import { logout, webLogout } from '@/api/services/connect.js'
import { countUserPlots } from '@/api/services/field.js'
import storage from "@/utils/storage.js"
// 查看用户协议
const viewTerms = () => {
  uni.navigateTo({
    url: '/pages/login/terms'
  })
}

// 查看隐私政策
const viewPrivacy = () => {
  uni.navigateTo({
    url: '/pages/login/privacy'
  })
}
// 响应式数据
const plotInfo = reactive({
	total: 0,
	active: 0,
	idle: 0
})

const serviceList = ref([
	// { 
	// 	name: '农资商城',
	// 	iconText: '商',
	// 	iconSvg: '/static/icons/mall.png',
	// 	path: '/pages/service/mall'
	// },
	{ 
		name: '农品交易',
		iconText: '售',
		iconSvg: '/static/icons/sales.png',
		path: '/pages/service/sales'
	},
	{
		name: '农事记录',
		iconText: '录',
		iconSvg: '/static/icons/activity-active.png',
		path: '/pages/activity/index'
	},
	{
		name: '设备管理',
		iconText: '备',
		iconSvg: '/static/icons/device-active.png',
		path: '/pages/device/index'
	},
	// { 
	// 	name: '专家咨询',
	// 	iconText: '诊',
	// 	iconSvg: '/static/icons/expert.png',
	// 	path: '/pages/service/expert'
	// },
	// { 
	// 	name: '绿色认证',
	// 	iconText: '证',
	// 	iconSvg: '/static/icons/certification.png',
	// 	path: '/pages/service/certification'
	// },
	// { 
	// 	name: '保险接入',
	// 	iconText: '保',
	// 	iconSvg: '/static/icons/insurance.png',
	// 	path: '/pages/service/insurance'
	// }
])

const userInfo = reactive({
	nickName: '',
	id: '',
	avatar: '',
	sex: ''
})

const isLogin = ref(false)

// 方法
const userPlots = () => {
	countUserPlots().then((res => {
		if (res.data.code == 200) {
			const { plotsTotal, inUseCount, leiSureCount } = res.data.data
			plotInfo.total = plotsTotal
			plotInfo.active = inUseCount
			plotInfo.idle = leiSureCount
		} else {
			console.error("统计地块数量失败！")
		}
	}))
}

// 检查登录状态
const checkLoginStatus = () => {
	console.log("执行Show")
	if (storage.getHasLogin()) {
		isLogin.value = true
		// 获取用户信息
		const storedUserInfo = storage.getUserInfo()
		console.log("执行Show", storedUserInfo)
		if (storedUserInfo) {
			userInfo.nickName = storedUserInfo.username || '游客'
			userInfo.avatar = storedUserInfo.avatar || '/static/icons/user_icon.png'
			userInfo.sex = storedUserInfo.sex
		}
	} else {
		isLogin.value = false
	}
}

const navigateToLogin = () => {
	uni.navigateTo({
		url: '/pages/login/index'
	})
}

const navigateToPlots = () => {
	if (!storage.getHasLogin()) {
		uni.showModal({
			title: '提示',
			content: '您还未登录，请先登录',
			confirmText: '去登录',
			cancelText: '取消',
			success: function(res) {
				if (res.confirm) {
					uni.navigateTo({
						url: '/pages/login/index'
					});
				}
			},
		});
		return;
	}
	uni.navigateTo({
		url: '/pages/plots/list'
	})
}

const navigateToService = (item) => {
	if (!storage.getHasLogin()) {
		uni.showModal({
			title: '提示',
			content: '您还未登录，请先登录',
			confirmText: '去登录',
			cancelText: '取消',
			success: function(res) {
				if (res.confirm) {
					uni.navigateTo({
						url: '/pages/login/index'
					});
				}
			},
		});
		return;
	}
	uni.navigateTo({ url: item.path })
}

const handleContact = () => {
	uni.makePhoneCall({
		phoneNumber: '13379508760' // 替换为实际的客服电话
	})
}

const navigateToAbout = () => {
	uni.navigateTo({
		url: '/pages/about/index'
	})
}

const navigateToSettings = () => {
	uni.navigateTo({
		url: '/pages/settings/index'
	})
}

// 使用授权服务处理登出
const handleLogout = () => {
	uni.showModal({
		title: '提示',
		content: '确认退出登录？',
		success: (res) => {
			if (res.confirm) {
				
				webLogout().then(res => {
					console.log("tuichu", res)
					storage.setAccessToken("")
					storage.setUserInfo({})
					storage.setHasLogin(false)
					storage.removeCurrentPlot()
					storage.removeUserPlots()
					isLogin.value = false
					userInfo.nickname = '游客'
					userInfo.id = ''
					userInfo.avatar = ''
					plotInfo.total = 0
					plotInfo.active = 0
					plotInfo.idle = 0
				})
				
			}
		}
	})
}

// 生命周期钩子
onShow(() => {
	checkLoginStatus()
	if (isLogin.value) {
		userPlots()
	}
})
</script>

<style>
	.container {
		min-height: 100vh;
		background-color: #f5f5f5;
		padding: 20rpx;
	}

	.user-card {
		background-color: #4CAF50;
		border-radius: 16rpx;
		padding: 30rpx;
		margin-bottom: 20rpx;
	}

	.user-header {
		display: flex;
		align-items: center;
	}

	.avatar {
		width: 120rpx;
		height: 120rpx;
		border-radius: 60rpx;
		/* border: 4rpx solid #fff; */
	}

	.user-detail {
		margin-left: 20rpx;
		color: #fff;
	}

	.nickname {
		font-size: 32rpx;
		font-weight: bold;
		margin-bottom: 10rpx;
		display: block;
	}

	.user-id {
		font-size: 24rpx;
		opacity: 0.8;
	}

	.info-card {
		background-color: #fff;
		border-radius: 16rpx;
		padding: 30rpx;
		margin-bottom: 20rpx;
	}

	.card-title {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 30rpx;
		font-size: 32rpx;
		font-weight: bold;
	}

	.more {
		color: #666;
		font-size: 24rpx;
		font-weight: normal;
	}

	.plot-info {
		display: flex;
		justify-content: space-around;
	}

	.plot-item {
		text-align: center;
	}

	.number {
		font-size: 36rpx;
		font-weight: bold;
		color: #4CAF50;
		display: block;
	}

	.label {
		font-size: 24rpx;
		color: #666;
		margin-top: 10rpx;
		display: block;
	}

	.service-grid {
		display: grid;
		grid-template-columns: repeat(4, 1fr);
		gap: 30rpx;
		padding: 10rpx 0;
	}

	.service-item {
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.service-icon {
		width: 88rpx;
		height: 88rpx;
		background-color: #E8F5E9;
		border-radius: 16rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-bottom: 16rpx;
	}

	.service-icon text {
		font-size: 32rpx;
		color: #4CAF50;
		font-weight: bold;
	}

	.icon-svg {
		width: 48rpx;
		height: 48rpx;
		display: block;
	}

	.service-name {
		font-size: 28rpx;
		color: #666;
		text-align: center;
	}

	.function-list {
		width: 100%;
	}

	.function-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 30rpx 0;
		border-bottom: 1rpx solid #f5f5f5;
	}

	.function-item:last-child {
		border-bottom: none;
	}

	.function-item .left {
		display: flex;
		align-items: center;
	}

	.function-icon {
		width: 44rpx;
		height: 44rpx;
		background-color: #E8F5E9;
		color: #4CAF50;
		font-size: 28rpx;
		font-weight: bold;
		border-radius: 8rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-right: 20rpx;
	}

	.function-item text {
		font-size: 28rpx;
		color: #333;
	}

	.arrow {
		color: #999;
		font-size: 24rpx;
	}

	.login-text {
		font-size: 32rpx;
		font-weight: bold;
		color: #fff;
		background-color: rgba(255, 255, 255, 0.2);
		padding: 10rpx 30rpx;
		border-radius: 30rpx;
	}
</style>