<template>
 <view class="home-land-container">
    <!-- 第三层：背景 -->
    <view class="background-layer"></view>
  
    <!-- 第二层：地图 -->
    <view class="map-layer" id="mapLayer" :style="{ transform: `translateX(${translateX}px)` }" @touchstart="touchStart" @touchmove="touchMove" @touchend="touchEnd" @mousedown="onmousedown" @mousemove="onmousemove" @mouseup="onmouseup">
      <image class="island-image" src="/static/island/island.png" mode="widthFix" style="width:1536rpx; bottom: 0rpx;left: 0rpx; position: absolute;"></image>
      <view style="position: absolute;width: 670rpx;left: 340rpx; bottom:320rpx;align-items: center;">
        <image class="house-image" src="/static/island/building/home1.png" mode="widthFix" style="width:670rpx; position: static;" @click="onHouseClick" :animation="houseAnimationData">	</image>
      </view>

      <view style="position: absolute;width: 300rpx;left:280rpx; bottom:200rpx;align-items: center;">
        <image class="table-image" src="/static/island/building/workTable.png" mode="widthFix" style="width:670rpx; position: static;" @click="onTableClick" :animation="tableAnimationData">	</image>
      </view>

      <view style="position: absolute;width:200rpx;left:660rpx; bottom:260rpx;align-items: center;">
        <image class="mailBox-image" src="/static/island/building/mailBox.png" mode="widthFix" style="width:670rpx; position: static;" >	</image>
      </view>

      <view style="position: absolute;width:200rpx;left:1000rpx; bottom:450rpx;align-items: center;">
        <image class="taskBoard-image" src="/static/island/building/taskBoard.png" mode="widthFix" style="width:670rpx; position: static;" @click="showTask" :animation="taskAnimationData">	</image>
      </view>

      <!-- 主岛箭头 -->
      <view class="main-arrow" @click="goToMainLand" :animation="mainArrowAnimation" :style="{ opacity: mainArrowVisible ? 1 : 0 }">
        <!-- <image src="/static/island/main_arrow.png" mode="widthFix" style="width: 100rpx;"></image> -->
		<view class="arrow" ></view>
        <text class="main-text">主岛</text>

      </view>
    </view>
  
    <!-- 第一层：UI -->
    <view class="ui-layer">
      <view class="ui-content">
        <!-- 添加货币计数器 -->
        <view class="currency-display" >
          <view class="currency-item">
            <image src="/static/island/UI/wd_icon_coin.png" mode="widthFix" class="currency-icon"></image>
            <text class="currency-value">9999</text>
          </view>
          <view class="currency-item">
            <image src="/static/island/UI/wd_icon_xingyuan.png" mode="widthFix" class="currency-icon"></image>
            <text class="currency-value">9999</text>
          </view>
        </view>
        <view class="ui-buttons">
		  <image src="/static/island/icon_backpack.png" mode="widthFix" style="width:100rpx" @click="showInventory"></image>
        </view>
      </view>
    </view>

    <!-- 对话框组件 -->
    <backpack-dialog :visible.sync="inventoryVisible" @close="onInventoryClose"></backpack-dialog>
    <character-dialog :visible.sync="characterVisible" @close="onCharacterClose"></character-dialog>
    <shop-dialog :visible.sync="shopVisible" @close="onShopClose" @buy="onShopBuy"></shop-dialog>
    <task-dialog class="task-dialog" :visible.sync="taskVisible" @close="onTaskClose"></task-dialog>
    
    <!-- 引导对话组件 -->
    <talk-guide 
      :guide-data="guideData"
      :player-name="playerName"
      @guide-complete="onGuideComplete"
    ></talk-guide>

    <!-- 制造台对话框组件 -->
    <crafting-dialog :visible.sync="craftingVisible" @close="craftingVisible = false"></crafting-dialog>
  </view> 
</template>


<script>
import BackpackDialog from '@/components/dialogs/BackpackDialog.vue'
import CharacterDialog from '@/components/dialogs/CharacterDialog.vue'
import ShopDialog from '@/components/dialogs/ShopDialog.vue'
import TaskDialog from './TaskDialog.vue'
import TalkGuide from './talkGuide.vue'
import CraftingDialog from '@/components/dialogs/CraftingDialog.vue'

export default {
	components: {
		BackpackDialog,
		CharacterDialog,
		ShopDialog,
		TaskDialog,
		TalkGuide,
		CraftingDialog
	},
	data() {
		return {
			// 背景位置控制
			translateX: -141,
			startX: 0,
			currentX: 0,
			isDragging : false,
			
			// 获取屏幕宽度和背景宽度
			screenWidth: 0,
			backgroundWidth: 0,
			islandHeight: 0,
			houseAnimationData: {},
			tableAnimationData: {},
			taskAnimationData: {},
			houseAnimating: false,
			tableAnimating: false,
			taskAnimating: false,
			baseTranslate: { x: -50, y: 50 },
			inventoryVisible: false,
			characterVisible: false,
			shopVisible: false,
			mainArrowAnimation: {},
			mainArrowAnimating: false,
			mainArrowVisible: false,
			taskVisible: false,
			playerName: '梦幻',
			guideData: [
				{
					characterImage: '/static/island/npc.png',
					characterName: '罗宾',
					text: '这位大人，这里太大了吧....',
					position: 'left',
					isMirror: true
				},
				{
					characterImage: '/static/island/building/1.png',
					characterName: '我',
					text: '好的，我马上上会教付清',
					position: 'right',
					isMirror: false
				},
				{
					characterImage: '/static/island/building/1.png',
					characterName: '我',
					text: '很奇怪不是吗？',
					position: 'right',
					isMirror: false
				},
				{
					characterImage: '/static/island/npc.png',
					characterName: '罗宾',
					text: '怎么回事',
					position: 'left',
					isMirror: true
				}
			],
			craftingVisible: false
		}
	},
	onLoad() {
		let self = this;
		// 获取屏幕宽度
		uni.getSystemInfo({
			success: (res) => {
				self.screenWidth = res.windowWidth;
				console.log('屏幕宽度:', self.screenWidth);
			}
		});
	},
	onShow() {
		// this.loadData();
	},
	onReady() {
		// 在组件渲染完成后获取图片尺寸
		setTimeout(() => {
			this.getImageSize();
			// 延迟1秒后显示箭头并开始动画
			setTimeout(() => {
				this.mainArrowVisible = true;
				this.startMainArrowAnimation();
			}, 1000);
		}, 300);
	},
	methods: {
		loadData() {
			// 可以在这里加载其他数据
		},
		getImageSize() {
			const query = uni.createSelectorQuery().in(this);
			query.select('.island-image').boundingClientRect(data => {
				if (data) {
					// 获取岛屿图片的宽度和高度
					this.backgroundWidth = data.width;
					this.islandHeight = data.height;
					
					// 计算最大可移动距离
					this.maxTranslate = this.backgroundWidth - this.screenWidth;
					
					// 初始位置居中
					// this.translateX = -this.maxTranslate / 2;
					// this.translateX = 0;
					
					// 打印调试信息
					// console.log('屏幕宽度:', this.screenWidth);
					// console.log('背景宽度:', this.backgroundWidth);
					// console.log('岛屿高度:', this.islandHeight);
					// console.log('最大可移动距离:',this.maxTranslate);
					
					// console.log('岛屿data:', data);
					
				} else {
					console.error('未能获取岛屿图片的尺寸');
				}
			}).exec();
		},
		// 触摸开始
		touchStart(e) {
			this.startX = e.touches[0].clientX;
			this.currentX = this.translateX;
			console.log('this.startX =',this.startX);
			console.log('this.currentX =',this.currentX);
		},
		// 触摸移动
		touchMove(e) {
			console.log('----------- touchMove');
			const moveX = e.touches[0].clientX - this.startX;
			let newTranslateX = this.currentX + moveX;
			
			// 限制移动范围，不让背景两侧露出
			if (newTranslateX > 0) {
				newTranslateX = 0;
			} else if (newTranslateX < -this.maxTranslate) {
				newTranslateX = -this.maxTranslate;
			}
			
			this.translateX = newTranslateX;
			console.log('moveX =',moveX);
			console.log('this.translateX =',this.translateX);
		},
		// 触摸结束
		touchEnd() {
			console.log('----------- touchEnd');
			this.currentX = this.translateX;
			console.log('this.currentX =',this.currentX);
		},
		
		onmousedown(e) {
			console.log('----------- onmousedown');
			console.log('----------- e',e);
			this.isDragging = true;
			this.startX = e.clientX;
			this.currentX = this.translateX;
			mapLayer.style.cursor = 'grabbing';
		},
		
		onmousemove(e) {
			if(this.isDragging){
				console.log('----------- onmousemove');
				const moveX = e.clientX - this.startX;
				let newTranslateX = this.currentX + moveX;
				
				//限制移动范围，不让背景两侧露出
				if (newTranslateX > 0) {
					newTranslateX = 0;
				} else if (newTranslateX < -this.maxTranslate) {
					newTranslateX = -this.maxTranslate;
				}
				
				this.translateX = newTranslateX;
				console.log('moveX =',moveX);
				console.log('this.translateX =',this.translateX);
			}
		},
		
		onmouseup(e) {
			console.log('----------- onmouseup');
			this.isDragging = false;
			mapLayer.style.cursor = 'grab';
		},

		onHouseClick(event) {
			if(this.houseAnimating) return;
			// 处理点击事件
			console.log('House clicked!');
			
			// 播放房子的点击动画
			this.playAnimation('house');
			
			// uni.showToast({
			// 	title: 'House clicked!',
			// 	icon: 'none'
			// });
		},

		onTableClick(event) {
			if(this.tableAnimating) return;
			console.log('Table clicked!');
			
			// 播放大厅的点击动画
			this.playAnimation('table');
			
			// 显示制造台界面
			this.craftingVisible = true;
		},

		onTaskClick(event) {
			if(this.taskAnimating) return;
			// 处理点击事件
			console.log('Task clicked!');
			
			// 播放大厅的点击动画
			this.playAnimation('task');
			
			// uni.showToast({
			// 	title: 'task clicked!',
			// 	icon: 'none'
			// });
		},

		playAnimation(type) {
			let self = this;
			
			// 根据类型设置对应的动画状态
			if (type === 'house') {
				this.houseAnimating = true;
			} else if (type === 'table') {
				this.tableAnimating = true;
			} else if (type === 'task') {
				this.taskAnimating = true;
			}

			// 创建动画实例
			const animation = uni.createAnimation({
				duration: 400,
				timingFunction: 'ease',
			});

			// 定义果冻动画序列
			animation.scale(0.95).step({ duration: 100 })
					.scale(1.05).step({ duration: 100 })
					.scale(0.98).step({ duration: 100 })
					.scale(1).step({ duration: 100 });

			// 根据类型应用动画到对应的元素
			if (type === 'house') {
				this.houseAnimationData = animation.export();
			} else if (type === 'table') {
				this.tableAnimationData = animation.export();
			} else if (type === 'task') {
				this.taskAnimationData = animation.export();
			}

			// 动画结束后重置状态
			setTimeout(() => {
				if (type === 'house') {
					self.houseAnimating = false;
				} else if (type === 'table') {
					self.tableAnimating = false;
				} else if (type === 'task') {
					self.taskAnimating = false;
				}
			}, 800);
		},

		showInventory() {
			console.log('Opening inventory...')
			this.inventoryVisible = true
		},
		onInventoryClose() {
			console.log('Closing inventory...')
			this.inventoryVisible = false
		},
		showCharacter() {
			console.log('Opening character...')
			this.characterVisible = true
		},
		onCharacterClose() {
			console.log('Closing character...')
			this.characterVisible = false
		},
		showShop() {
			console.log('Opening shop...')
			this.shopVisible = true
		},
		onShopClose() {
			console.log('Closing shop...')
			this.shopVisible = false
		},
		onShopBuy(item) {
			console.log('Buying item:', item)
		},
		showTask() {
			console.log('Opening task board...')
			this.taskVisible = true
		},
		onTaskClose() {
			console.log('Closing task board...')
			this.taskVisible = false
		},
		startMainArrowAnimation() {
			if (this.mainArrowAnimating) return;
			this.mainArrowAnimating = true;

			const animation = uni.createAnimation({
				duration: 1000,
				timingFunction: 'ease-in-out',
			});

			const animate = () => {
				if (!this.mainArrowAnimating) return;

				animation.translateY(-10).step({ duration: 1000 });
				this.mainArrowAnimation = animation.export();

				setTimeout(() => {
					animation.translateY(0).step({ duration: 1000 });
					this.mainArrowAnimation = animation.export();

					setTimeout(() => {
						if (this.mainArrowAnimating) {
							animate();
						}
					}, 1000);
				}, 1000);
			};

			animate();
		},
		goToMainLand() {
			uni.navigateTo({
				url: '/pages/isLand/mainLand'
			});
		},
		onGuideComplete() {
			console.log('引导完成')
			// 这里可以添加引导完成后的逻辑
			uni.setStorageSync('isGuideCompleted', true)
		}
	},
	beforeDestroy() {
		this.mainArrowAnimating = false;
	}
}
</script>


<style lang="scss" scoped>
@import './homeLand.scss';
.ui-layer {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  pointer-events: none;
  z-index: 100;

  .ui-content {
    position: absolute;
    top: 20rpx;
    right: 20rpx;
    pointer-events: auto;
    z-index: 101;
  }

  .ui-buttons {
    display: flex;
    flex-direction: column;
    gap: 20rpx;
    
    .ui-button {
      background: rgba(255, 255, 255, 0.9);
      border: none;
      padding: 16rpx 32rpx;
      border-radius: 8rpx;
      font-size: 28rpx;
      color: #333;
      box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
      min-width: 120rpx;
      
      &:active {
        opacity: 0.8;
        transform: scale(0.95);
      }
    }
  }
}

.map-layer {
  position: relative;
  z-index: 1;
  cursor: grab;
  
  &:active {
    cursor: grabbing;
  }
}

.main-arrow {
//   background: rgba(255, 255, 255, 0.9);
  position: absolute;
  height: 190rpx;
  right: 50rpx;
  bottom: 20rpx;  // 改为 bottom 定位
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
  z-index: 10;
  transition: opacity 0.5s ease-in-out;

  .arrow {
    content: '';
    display: block;
    width: 60rpx;
    height: 60rpx;
    background: url('/static/island/arrow.png') no-repeat center center;
    background-size: contain;
    transform: rotate(270deg);
  }

  .main-text {
    color: #ffffff;
    font-size: 32rpx;
    text-shadow: 2rpx 2rpx 4rpx rgba(0, 0, 0, 0.5);
    margin-top: 10rpx;
  }
}
.task-dialog{
	 ::v-deep.dialog-content{
		  background: transparent !important;
	  }
}
</style> 