<template>
  <view class="my-application-page">
    <!-- 顶部导航栏 -->
    <uni-nav-bar
      left-icon="left"
      title="我的应用"
      @clickLeft="goBack"
      fixed
      color="#8B2316"
      height="180rpx"
      :border="false"
      backgroundColor="#eeeeee"
    >
      <template #right>
        <text class="edit-btn" @click="toggleEdit">{{
          isEditMode ? "完成" : "编辑"
        }}</text>
      </template>
    </uni-nav-bar>

    <scroll-view class="content" scroll-y>
      <!-- 我的应用部分 -->
      <view class="section">
        <view class="section-title">我的应用</view>
        <view class="app-grid">
          <view
            class="app-item"
            v-for="(app, index) in myApps"
            :key="app.id"
            @click="openApp(app)"
          >
            <view
              class="iconbox"
              v-if="isEditMode"
              @click.stop="removeFromMyApps(index)"
            >
              <up-icon
                name="minus-circle"
                color="#fe0001"
                size="40rpx"
              ></up-icon>
            </view>
            <view class="app-icon">
              <image :src="app.icon" mode="aspectFit" class="icon-image" />
            </view>
            <text class="app-name">{{ app.name }}</text>
          </view>
        </view>
      </view>

      <!-- 常用功能部分 -->
      <view class="section">
        <view class="section-title">常用功能</view>
        <view class="app-grid">
          <view
            class="app-item"
            v-for="(app, index) in commonApps"
            :key="app.id"
            @click="openApp(app)"
          >
            <view
              class="iconbox"
              @click.stop="addToMyApps(app)"
              v-if="isEditMode"
            >
              <up-icon
                name="plus-circle"
                color="#067fe6"
                size="40rpx"
              ></up-icon>
            </view>
            <view class="app-icon">
              <image :src="app.icon" mode="aspectFit" class="icon-image" />
            </view>
            <text class="app-name">{{ app.name }}</text>
          </view>
        </view>
      </view>
    </scroll-view>
  </view>
</template>

<script setup>
	import { ref } from 'vue';
	import { onShow } from "@dcloudio/uni-app";
  import api from "@/api/api";
  import docUrl from '@/utils/docUrl';
  import navTo from '@/utils/navTo';

	// 编辑模式状态
	const isEditMode = ref(false);
	
	// 我的应用列表
	const myApps = ref([]);
	
	// 常用功能列表
	const commonApps = ref([]);
	
	
	const blackList=['临床研究','精品课程','名医名科','肝病学院','病例分享','科研项目','肝病检测','我的下载','病例讨论','临床研究']
	// 页面路由映射
	
	// 获取用户图标数据
    const addUserIcon = () => {
        api.addUserIcon({
            idStr:myApps.value.map(item => item.id).join(',')
        }).then(res => {
            console.log('addUserIcon API响应:', res);
            if(res.code === '200'){
                uni.showToast({
                    title: '保存成功',
                    icon: 'none',
                    duration: 1500
                });
            }
        });
    };
	const getUserIcon = () => {
		api.getUserIcon({}).then(res => {
			console.log('getUserIcon API响应:', res);
			
			if (res.code === '200' && res.data && Array.isArray(res.data)) {
				// 处理API数据（先过滤黑名单）
				const sourceList = res.data.filter(item => !blackList.includes(item.name));
				const allApps = sourceList.map(item => ({
					id: item.id,
					name: item.name,
					icon: docUrl + item.img, // 使用docUrl拼接图片路径 // 使用预设颜色// 使用预设路由
					selected: item.selected
				}));
				
				// 根据selected字段分离我的应用和常用功能
				myApps.value = allApps.filter(app => 
					app.selected !== 'false' && app.selected !== false
				);
				
				commonApps.value = allApps.filter(app => 
					app.selected === 'false' || app.selected === false
				);
				
				console.log('我的应用:', myApps.value);
				console.log('常用功能:', commonApps.value);
			} else {
				console.error('获取应用图标失败:', res.message || '未知错误');
				uni.showToast({
					title: res.message || '获取应用列表失败',
					icon: 'error',
					duration: 2000
				});
			}
		}).catch(error => {
			console.error('获取应用图标异常:', error);
			uni.showToast({
				title: '网络请求失败',
				icon: 'error',
				duration: 2000
			});
		});
	};

	// 返回上一页
	const goBack = () => {
		uni.navigateBack();
	};

	// 切换编辑模式
	const toggleEdit = () => {
		isEditMode.value = !isEditMode.value;
		if(!isEditMode.value){
			addUserIcon();
		}
	};

	// 打开应用
	const openApp = (app) => {
		if (isEditMode.value) return;
		 let url='';
         if(app.name=="肝胆课件"){
            url='/pages_app/ppt/ppt'
            navTo({
			     url:url
		    })
         }else if(app.name=="精品课"){
            url='/pages_course/course/course'
            navTo({
			     url:url
		    })
         }else if(app.name=="积分商城"){
            url='/pages_goods/pointMall/pointMall'
            navTo({
			     url:url
		    })
         }else if(app.name=="肝病新闻"){
            url='/pages_app/news/news'
            navTo({
			     url:url
		    })
         }else if(app.name=="我的福利"){
            url='/pages_app/myWelfare/myWelfare'
            navTo({
			     url:url
		    })
         }else if(app.name=="专题e站"){
            url='https://wx.igandan.com/Esite/index.htm#/home?fromtype=doctor'
            // H5 端
		// #ifdef H5
		window.open(url, '_blank');
		// #endif
		
		// App 端
		// #ifdef APP-PLUS
		plus.runtime.openURL(url);
		// #endif
		
		// 小程序端：使用内嵌 webview 页面打开
		// #ifdef MP
		const encoded = encodeURIComponent(url)
		uni.navigateTo({
			url: `/pages_app/webview/webview?url=${encoded}`
		})
		// #endif
            
         }
		
	};

	// 添加到我的应用
	const addToMyApps = (app) => {
		// 检查是否已存在
		const exists = myApps.value.some(item => item.id === app.id);
		if (exists) {
			uni.showToast({
				title: '已在我的应用中',
				icon: 'none',
				duration: 1500
			});
			return;
		}

		// 检查是否超过最大数量
		if (myApps.value.length >= 3) {
			uni.showToast({
				title: '最多添加3个应用',
				icon: 'none',
				duration: 1500
			});
			return;
		}

		// 更新应用状态为已选中
		app.selected = '1';
		
		// 从常用功能中移除
		const commonIndex = commonApps.value.findIndex(item => item.id === app.id);
		if (commonIndex > -1) {
			commonApps.value.splice(commonIndex, 1);
		}
		
		// 添加到我的应用
		myApps.value.push(app);
		
		
	};

	// 从我的应用中移除
	const removeFromMyApps = (index) => {
		const app = myApps.value[index];
		
		// 更新应用状态为未选中
		app.selected = 'false';
		
		// 从我的应用中移除
		myApps.value.splice(index, 1);
		
		// 添加到常用功能
		commonApps.value.push(app);
		
		
	};

	onShow(() => {
		// 页面显示时的逻辑
        getUserIcon();
	});
</script>

<style lang="scss" scoped>
.my-application-page {
  background-color: #ffffff;
  min-height: 100vh;
}

.content {
  position: fixed;
  top: calc(var(--status-bar-height) + 64px);
  bottom: 0;
  left: 0;
  width: 100%;
  right: 0;
  box-sizing: border-box;
  background-color: #fff;
}

.edit-btn {
  color: #8b2316;
  font-size: 28rpx;
  font-weight: 500;
}

.section {
  margin-bottom: 40rpx;
}

.section-title {
  color: #666666;
  font-size: 28rpx;
  margin-bottom: 20rpx;
  padding: 0 30rpx;
}

.app-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
 
}

.app-item {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20rpx 10rpx;
  border: 1rpx solid #e0e0e0;
  
  border-right:none;
  transition: all 0.3s ease;
  .iconbox {
    position: absolute;
    top: 8rpx;
    right: 8rpx;
  }

  &:active {
    transform: scale(0.95);
  }

  // 右边框处理
  &:nth-child(3n) {
  
  }

  // 下边框处理（最后一行）
  &:nth-last-child(1){
    border-right: 1rpx solid #e0e0e0;
  }
}

.app-icon {
  width: 100rpx;
  height: 100rpx;
  border-radius: 20rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 16rpx;
}

.icon-image {
  width: 60rpx;
  height: 60rpx;
}

.app-name {
  font-size: 24rpx;
  color: #000;
  text-align: center;
  line-height: 1.2;
  font-weight: 500;
}

.delete-btn {
  position: absolute;
  top: -8rpx;
  right: -8rpx;
  width: 32rpx;
  height: 32rpx;
  background-color: #ff4757;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2rpx 8rpx rgba(255, 71, 87, 0.3);
}

.add-btn {
  position: absolute;
  top: -8rpx;
  right: -8rpx;
  width: 32rpx;
  height: 32rpx;
  background-color: #ffffff;
  border: 2rpx solid #8b2316;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2rpx 8rpx rgba(139, 35, 22, 0.2);
}

// 编辑模式下的样式调整
.app-item:has(.delete-btn) {
  border-right-color: #ff4757;
  border-bottom-color: #ff4757;
}

.app-item:has(.add-btn) {
  border-right-color: #8b2316;
  border-bottom-color: #8b2316;
}
</style>
