<template>
  <view class="guide-manager">
    <!-- 遮罩层 -->
    <view class="guide-mask" v-if="currentStage" @click="handleMaskClick">
      <!-- 高亮区域 -->
      <view class="highlight-area" :style="highlightStyle"></view>
      
      <!-- 提示框 -->
      <view class="guide-tips" :style="tipsStyle">
        <view class="tips-content">
          <text class="tips-text">{{ currentStep.tips }}</text>
          <view class="tips-buttons">
            <text class="skip-btn" @click.stop="skipStage">跳过</text>
            <text class="next-btn" @click.stop="nextStep">{{ isLastStep ? '完成' : '下一步' }}</text>
          </view>
        </view>
        <!-- 箭头 -->
        <view class="arrow" :style="arrowStyle"></view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  name: 'GuideManager',
  data() {
    return {
      // 当前引导阶段
      currentStage: null,
      // 当前步骤索引
      currentStepIndex: 0,
      // 已完成阶段
      completedStages: [],
      // 已完成的主线
      completedMainLines: [],
      // 引导配置
      guideConfig: {
        mainLines: [
          {
            name: "new immigrant",
            stage: "homeLand",
            steps: [
              {
                arrow: null,
                talkData: [
                  {
                    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
                  }
                ]
              },
              {
                arrow: {x: 350, y: 460, r: 0},
                talkData: [
                  {
                    characterImage: '/static/island/npc.png',
                    characterName: '罗宾',
                    text: '工作台在这里呢',
                    position: 'left',
                    isMirror: true
                  },
                  {
                    characterImage: '/static/island/building/1.png',
                    characterName: '我',
                    text: '好的，我去看看',
                    position: 'right',
                    isMirror: false
                  }
                ]
              }
            ]
          },
          {
            name: "new craftsman",
            stage: "mainLand_table",
            steps: [
              {
                arrow: null,
                talkData: [
                  {
                    characterImage: '/static/island/npc.png',
                    characterName: '罗宾',
                    text: '工作台在这里呢！',
                    position: 'left',
                    isMirror: true
                  },
                  {
                    characterImage: '/static/island/building/1.png',
                    characterName: '我',
                    text: '好像可以有好多工具，但是好像没有材料呢~',
                    position: 'right',
                    isMirror: false
                  },

                ]
              },
              {
                arrow: {x: 750, y: 660, r: 270},
                talkData: [
                  {
                    characterImage: '/static/island/npc.png',
                    characterName: '罗宾',
                    text: '是的呀，也可以去看看别人发布的任务，获取材料呢！',
                    position: 'left',
                    isMirror: true
                  }
                ]
              }
            ]
          },
          {
            name: "new flower farmer",
            stage: "mainLand",
            steps: [
              {
                arrow: {x: 50, y: 50, r: 90},
                talkData: [
                  {
                    characterImage: '/static/island/npc.png',
                    characterName: '罗宾',
                    text: '这里可以种花呦....',
                    position: 'left',
                    isMirror: true
                  }
                ]
              }
            ]
          }
        ]
      },
      // 当前主线ID
      currentMainLineId: 0,
      // 当前主线
      currentMainLine: null,
      // 对话数据
      currentTalkData: [],
      // 当前对话索引
      currentTalkIndex: 0
    }
  },
  computed: {
    // 当前步骤
    currentStep() {
      if (!this.currentStage) return null
      return this.currentStage.steps[this.currentStepIndex]
    },
    // 是否是最后一步
    isLastStep() {
      if (!this.currentStage) return false
      return this.currentStepIndex === this.currentStage.steps.length - 1
    },
    // 高亮区域样式
    highlightStyle() {
      if (!this.currentStep) return {}
      return this.currentStep.rect ? {
        top: `${this.currentStep.rect.top}px`,
        left: `${this.currentStep.rect.left}px`,
        width: `${this.currentStep.rect.width}px`,
        height: `${this.currentStep.rect.height}px`
      } : {}
    },
    // 提示框样式
    tipsStyle() {
      if (!this.currentStep || !this.currentStep.rect) return {}
      
      const rect = this.currentStep.rect
      const position = this.currentStep.position
      const systemInfo = uni.getSystemInfoSync()
      
      let style = {}
      switch (position) {
        case 'top':
          style = {
            bottom: `${systemInfo.windowHeight - rect.top + 10}px`,
            left: `${rect.left + rect.width / 2}px`,
            transform: 'translateX(-50%)'
          }
          break
        case 'bottom':
          style = {
            top: `${rect.bottom + 10}px`,
            left: `${rect.left + rect.width / 2}px`,
            transform: 'translateX(-50%)'
          }
          break
        case 'left':
          style = {
            top: `${rect.top + rect.height / 2}px`,
            right: `${systemInfo.windowWidth - rect.left + 10}px`,
            transform: 'translateY(-50%)'
          }
          break
        case 'right':
          style = {
            top: `${rect.top + rect.height / 2}px`,
            left: `${rect.right + 10}px`,
            transform: 'translateY(-50%)'
          }
          break
      }
      
      return style
    },
    // 箭头样式
    arrowStyle() {
      if (!this.currentStep) return {}
      const position = this.currentStep.position
      
      let style = {}
      switch (position) {
        case 'top':
          style = {
            transform: 'rotate(180deg)',
            bottom: '0'
          }
          break
        case 'bottom':
          style = {
            transform: 'rotate(0deg)',
            top: '0'
          }
          break
        case 'left':
          style = {
            transform: 'rotate(90deg)',
            right: '0'
          }
          break
        case 'right':
          style = {
            transform: 'rotate(-90deg)',
            left: '0'
          }
          break
      }
      
      return style
    }
  },
  methods: {
    // 开始引导
    startGuide(stage) {
      // 获取当前主线
      const mainLine = this.guideConfig.mainLines[this.currentMainLineId];
      
      // 检查主线是否存在且场景是否匹配
      if (!mainLine || mainLine.stage !== stage) {
        return false;
      }

      // 检查主线是否已完成
      if (this.completedMainLines.includes(this.currentMainLineId)) {
        return false;
      }

      // 设置当前主线
      this.currentMainLine = mainLine;
      this.currentStepIndex = 0;
      this.currentTalkIndex = 0;
      
      // 初始化对话数据
      this.initTalkData();
      
      return true;
    },
    // 设置当前主线ID
    setMainLineId(id) {
      if (id >= 0 && id < this.guideConfig.mainLines.length) {
        this.currentMainLineId = id;
        // 保存到本地存储
        this.saveCurrentMainLineId();
      }
    },
    // 保存当前主线ID
    saveCurrentMainLineId() {
      uni.setStorageSync('currentGuideMainLineId', this.currentMainLineId);
    },
    // 加载当前主线ID
    loadCurrentMainLineId() {
      const id = uni.getStorageSync('currentGuideMainLineId');
      if (id !== '') {
        this.currentMainLineId = id;
      }
    },
    // 初始化对话数据
    initTalkData() {
      if (this.currentMainLine && this.currentMainLine.steps[this.currentStepIndex]) {
        this.currentTalkData = this.currentMainLine.steps[this.currentStepIndex].talkData;
      }
    },
    // 下一步
    nextStep() {
      console.log("-------- next step", {
        currentMainLine: this.currentMainLine,
        currentStepIndex: this.currentStepIndex,
        currentTalkIndex: this.currentTalkIndex,
        currentTalkData: this.currentTalkData
      });
      
      if (!this.currentMainLine) return;

      // 如果当前步骤是最后一步
      if (this.currentStepIndex === this.currentMainLine.steps.length - 1) {
        this.completeMainLine();
      } else {
        // 进入下一步
        this.currentStepIndex++;
        this.currentTalkIndex = 0;
        this.initTalkData();
      }

      console.log("-------- next step2", {
        currentMainLine: this.currentMainLine,
        currentStepIndex: this.currentStepIndex,
        currentTalkIndex: this.currentTalkIndex,
        currentTalkData: this.currentTalkData
      });
      
    },
    // 完成主线
    completeMainLine() {
      if (this.currentMainLine) {
        // 添加到已完成列表
        this.completedMainLines.push(this.currentMainLine.name);
        
        // 保存到本地存储
        this.saveCompletedMainLines();
        
        // 重置状态
        this.currentMainLine = null;
        this.currentStepIndex = 0;
        this.currentTalkIndex = 0;
        this.currentTalkData = [];
      }
    },
    // 保存已完成主线
    saveCompletedMainLines() {
      uni.setStorageSync('completedGuideMainLines', this.completedMainLines);
    },
    // 加载已完成主线
    loadCompletedMainLines() {
      const mainLines = uni.getStorageSync('completedGuideMainLines');
      if (mainLines) {
        this.completedMainLines = mainLines;
      }
    },
    // 获取当前箭头位置
    getCurrentArrowPosition() {
      if (!this.currentMainLine || !this.currentMainLine.steps[this.currentStepIndex]) {
        return null;
      }
      return this.currentMainLine.steps[this.currentStepIndex].arrow;
    },
    // 获取当前对话数据
    getCurrentTalkData() {
      if (!this.currentTalkData.length) return null;
      return this.currentTalkData;
    },
    // 跳过当前阶段
    skipStage() {
      this.completeStage()
    },
    // 完成当前阶段
    completeStage() {
      if (this.currentStage) {
        // 添加到已完成列表
        this.completedStages.push(this.currentStage.id)
        
        // 如果当前阶段有主线ID，检查该主线的所有阶段是否都已完成
        if (this.currentStage.mainLineId) {
          const mainLineId = this.currentStage.mainLineId
          const mainLineStages = Object.values(this.guideConfig).filter(
            stage => stage.mainLineId === mainLineId
          )
          
          // 检查该主线的所有阶段是否都已完成
          const isMainLineCompleted = mainLineStages.every(
            stage => this.completedStages.includes(stage.id)
          )
          
          // 如果主线完成，添加到已完成主线列表
          if (isMainLineCompleted && !this.completedMainLines.includes(mainLineId)) {
            this.completedMainLines.push(mainLineId)
          }
        }
        
        // 保存到本地存储
        this.saveCompletedStages()
        this.saveCompletedMainLines()
        
        // 重置状态
        this.currentStage = null
        this.currentStepIndex = 0
      }
    },
    // 更新位置
    updatePositions() {
      if (!this.currentStep) return
      
      const query = uni.createSelectorQuery().in(this)
      query.select(this.currentStep.target).boundingClientRect(data => {
        if (data) {
          // 更新当前步骤的位置信息
          this.$set(this.currentStage.steps[this.currentStepIndex], 'rect', data)
        }
      }).exec()
    },
    // 保存已完成阶段
    saveCompletedStages() {
      uni.setStorageSync('completedGuideStages', this.completedStages)
    },
    // 加载已完成阶段
    loadCompletedStages() {
      const stages = uni.getStorageSync('completedGuideStages')
      if (stages) {
        this.completedStages = stages
      }
    },
    // 处理遮罩层点击
    handleMaskClick() {
      // 可以在这里添加点击遮罩层的处理逻辑
    }
  },
  mounted() {
    // 加载已完成主线和当前主线ID
    this.loadCompletedMainLines();
    this.loadCurrentMainLineId();
  }
}
</script>

<style lang="scss" scoped>
.guide-manager {
  .guide-mask {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.7);
    z-index: 9999;
    
    .highlight-area {
      position: absolute;
      box-shadow: 0 0 0 9999px rgba(0, 0, 0, 0.7);
      border-radius: 4px;
      transition: all 0.3s ease;
    }
    
    .guide-tips {
      position: absolute;
      background: #fff;
      border-radius: 8px;
      padding: 16px;
      min-width: 200px;
      box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
      transition: all 0.3s ease;
      
      .tips-content {
        .tips-text {
          font-size: 14px;
          color: #333;
          line-height: 1.5;
          margin-bottom: 12px;
        }
        
        .tips-buttons {
          display: flex;
          justify-content: space-between;
          align-items: center;
          
          .skip-btn,
          .next-btn {
            font-size: 14px;
            padding: 4px 12px;
            border-radius: 4px;
            cursor: pointer;
          }
          
          .skip-btn {
            color: #999;
          }
          
          .next-btn {
            color: #fff;
            background-color: #1890ff;
          }
        }
      }
      
      .arrow {
        position: absolute;
        width: 0;
        height: 0;
        border: 8px solid transparent;
        border-bottom-color: #fff;
      }
    }
  }
}
</style> 