<template>
  <custom-dialog :visible.sync="dialogVisible" title="我的农场" @close="onClose">
    <view class="farm-container" @click="onContainerClick">
      <view class="farm-beds">
        <view class="farm-grid upper-bed">
          <view class="row row-1">
            <view v-for="index in 3" :key="index-1" 
                  class="farm-plot" 
                  :class="getPlotClass(plots[index-1])"
                  @click.stop="onPlotClick(index-1)">
              <view class="plot-content">
                <view v-if="plots[index-1].state !== 'locked'" class="crop-stage">
                  <image v-if="plots[index-1].state === 'growing' || plots[index-1].state === 'harvestable'" 
                         :src="getCropImage(plots[index-1])" 
                         mode="aspectFit" 
                         class="crop-image">
                  </image>
                </view>
                <view class="plot-state-text" :class="{ 'state-changed': plots[index-1].stateChanged }">
                  {{ getPlotStateText(plots[index-1].state) }}
                </view>
              </view>
            </view>
          </view>
          <view class="row row-2">
            <view v-for="index in 4" :key="index+2" 
                  class="farm-plot" 
                  :class="getPlotClass(plots[index+2])"
                  @click.stop="onPlotClick(index+2)">
              <view class="plot-content">
                <view v-if="plots[index+2].state !== 'locked'" class="crop-stage">
                  <image v-if="plots[index+2].state === 'growing' || plots[index+2].state === 'harvestable'" 
                         :src="getCropImage(plots[index+2])" 
                         mode="aspectFit" 
                         class="crop-image">
                  </image>
                </view>
                <view class="plot-state-text" :class="{ 'state-changed': plots[index+2].stateChanged }">
                  {{ getPlotStateText(plots[index+2].state) }}
                </view>
              </view>
            </view>
          </view>
          <view class="row row-3">
            <view v-for="index in 3" :key="index+6" 
                  class="farm-plot" 
                  :class="getPlotClass(plots[index+6])"
                  @click.stop="onPlotClick(index+6)">
              <view class="plot-content">
                <view v-if="plots[index+6].state !== 'locked'" class="crop-stage">
                  <image v-if="plots[index+6].state === 'growing' || plots[index+6].state === 'harvestable'" 
                         :src="getCropImage(plots[index+6])" 
                         mode="aspectFit" 
                         class="crop-image">
                  </image>
                </view>
                <view class="plot-state-text" :class="{ 'state-changed': plots[index+6].stateChanged }">
                  {{ getPlotStateText(plots[index+6].state) }}
                </view>
              </view>
            </view>
          </view>
        </view>
        
        <view class="farm-grid lower-bed">
          <view class="row row-1">
            <view v-for="index in 3" :key="index+9" 
                  class="farm-plot" 
                  :class="getPlotClass(plots[index+9])"
                  @click.stop="onPlotClick(index+9)">
              <view class="plot-content">
                <view v-if="plots[index+9].state !== 'locked'" class="crop-stage">
                  <image v-if="plots[index+9].state === 'growing' || plots[index+9].state === 'harvestable'" 
                         :src="getCropImage(plots[index+9])" 
                         mode="aspectFit" 
                         class="crop-image">
                  </image>
                </view>
                <view class="plot-state-text" :class="{ 'state-changed': plots[index+9].stateChanged }">
                  {{ getPlotStateText(plots[index+9].state) }}
                </view>
              </view>
            </view>
          </view>
          <view class="row row-2">
            <view v-for="index in 4" :key="index+12" 
                  class="farm-plot" 
                  :class="getPlotClass(plots[index+12])"
                  @click.stop="onPlotClick(index+12)">
              <view class="plot-content">
                <view v-if="plots[index+12].state !== 'locked'" class="crop-stage">
                  <image v-if="plots[index+12].state === 'growing' || plots[index+12].state === 'harvestable'" 
                         :src="getCropImage(plots[index+12])" 
                         mode="aspectFit" 
                         class="crop-image">
                  </image>
                </view>
                <view class="plot-state-text" :class="{ 'state-changed': plots[index+12].stateChanged }">
                  {{ getPlotStateText(plots[index+12].state) }}
                </view>
              </view>
            </view>
          </view>
          <view class="row row-3">
            <view v-for="index in 3" :key="index+16" 
                  class="farm-plot" 
                  :class="getPlotClass(plots[index+16])"
                  @click.stop="onPlotClick(index+16)">
              <view class="plot-content">
                <view v-if="plots[index+16].state !== 'locked'" class="crop-stage">
                  <image v-if="plots[index+16].state === 'growing' || plots[index+16].state === 'harvestable'" 
                         :src="getCropImage(plots[index+16])" 
                         mode="aspectFit" 
                         class="crop-image">
                  </image>
                </view>
                <view class="plot-state-text" :class="{ 'state-changed': plots[index+16].stateChanged }">
                  {{ getPlotStateText(plots[index+16].state) }}
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
      
      <view class="action-panel" >
        <view class="farm-state-indicator" :class="{ 'state-changed': farmStateChanged }">
          当前状态: {{ getFarmStateText(farmState) }}
        </view>
        <view class="action-buttons">
          <button @click.stop="onUnlockClick" >解锁</button>
          <button @click.stop="onPlantClick" >播种</button>
          <button @click.stop="onHarvestClick" >收获</button>
          <!-- <button @click.stop="onUnlockClick" :disabled="!canUnlock">解锁</button>
          <button @click.stop="onPlantClick" :disabled="!canPlant">播种</button>
          <button @click.stop="onHarvestClick" :disabled="!canHarvest">收获</button> -->
        </view>
      </view>
    </view>
  </custom-dialog>
</template>

<script>
import CustomDialog from '@/components/CustomDialog/CustomDialog.vue'
// import { showModal, showToast } from '@/utils/uniapi'

const PLOT_STATES = {
  LOCKED: 'locked',
  EMPTY: 'empty',
  GROWING: 'growing',
  HARVESTABLE: 'harvestable'
}

const FARM_STATES = {
  IDLE: 'idle',
  PLANTING: 'planting',
  HARVESTING: 'harvesting'
}

export default {
  name: 'FarmDialog',
  components: {
    CustomDialog
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    coins: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      dialogVisible: false,
      farmState: FARM_STATES.IDLE,
      farmStateChanged: false,
      plots: Array(20).fill().map(() => ({
        state: PLOT_STATES.LOCKED,
        plantedAt: null,
        stateChanged: false
      }))
    }
  },
  computed: {
    canUnlock() {
      return this.farmState === FARM_STATES.IDLE && this.hasLockedPlots
    },
    canPlant() {
      return this.farmState === FARM_STATES.IDLE && this.hasEmptyPlots
    },
    canHarvest() {
      return this.farmState === FARM_STATES.IDLE && this.hasHarvestablePlots
    },
    hasLockedPlots() {
      return this.plots.some(plot => plot.state === PLOT_STATES.LOCKED)
    },
    hasEmptyPlots() {
      return this.plots.some(plot => plot.state === PLOT_STATES.EMPTY)
    },
    hasHarvestablePlots() {
      return this.plots.some(plot => plot.state === PLOT_STATES.HARVESTABLE)
    },
    nextUnlockedPlotIndex() {
      return this.plots.findIndex(plot => plot.state === PLOT_STATES.LOCKED)
    }
  },
  watch: {
    visible(newVal) {
      this.dialogVisible = newVal
      if (newVal) {
        // 初始化第一块地为空地状态
        if (this.plots[0].state === PLOT_STATES.LOCKED) {
          this.plots[0].state = PLOT_STATES.EMPTY
        }
        console.log('农场对话框打开，当前农场状态:', this.farmState)
      }
    },
    farmState: {
      handler(newVal, oldVal) {
        if (newVal !== oldVal) {
          console.log(`农场状态发生变化: ${oldVal} -> ${newVal}`)
          this.farmStateChanged = true;
          setTimeout(() => {
            this.farmStateChanged = false;
          }, 300);
        }
      }
    }
  },
  methods: {
    onClose() {
      console.log('关闭农场对话框，重置农场状态为空闲')
      this.farmState = FARM_STATES.IDLE
      this.$emit('update:visible', false)
    },
    getPlotClass(plot) {
      return {
        'is-locked': plot.state === PLOT_STATES.LOCKED,
        'is-empty': plot.state === PLOT_STATES.EMPTY,
        'is-growing': plot.state === PLOT_STATES.GROWING,
        'is-harvestable': plot.state === PLOT_STATES.HARVESTABLE,
        'highlight-empty': this.farmState === FARM_STATES.PLANTING && plot.state === PLOT_STATES.EMPTY,
        'highlight-harvestable': this.farmState === FARM_STATES.HARVESTING && plot.state === PLOT_STATES.HARVESTABLE
      }
    },
    getCropImage(plot) {
      if (plot.state === PLOT_STATES.GROWING) {
        return '/static/crops/growing.png'
      } else if (plot.state === PLOT_STATES.HARVESTABLE) {
        return '/static/crops/harvestable.png'
      }
      return ''
    },
    updatePlotState(index, newState) {
      const plot = this.plots[index];
      if (plot.state !== newState) {
        console.log(`更新土地 ${index} 状态: ${plot.state} -> ${newState}`)
        plot.state = newState;
        plot.stateChanged = true;
        setTimeout(() => {
          plot.stateChanged = false;
        }, 300);
      }
    },
    async onUnlockClick() {
      if (!this.hasLockedPlots) {
        console.log('没有可解锁的土地，保持当前状态:', this.farmState)
        uni.showToast({ title: '已经解锁所有土地', icon: 'none' })
        return
      }

      const unlockCost = 100
      console.log(`当前金币: ${this.coins}, 解锁费用: ${unlockCost}`)
      const result = await uni.showModal({
        title: '解锁新土地',
        content: `是否使用${unlockCost}金币解锁新土地？\n当前金币：${this.coins}`
      })

      if (result.confirm) {
        if (this.coins < unlockCost) {
          console.log(`金币不足，需要 ${unlockCost} 金币，当前只有 ${this.coins} 金币`)
          uni.showToast({ title: '金币不够', icon: 'none' })
          return
        }

        console.log(`解锁成功，扣除 ${unlockCost} 金币，剩余 ${this.coins - unlockCost} 金币`)
        this.$emit('update:coins', this.coins - unlockCost)
        this.updatePlotState(this.nextUnlockedPlotIndex, PLOT_STATES.EMPTY)
      } else {
        console.log('用户取消解锁，保持当前状态:', this.farmState)
      }
    },
    onPlantClick() {
      console.log(`点击播种按钮，当前农场状态: ${this.farmState}`);
      if (this.farmState === FARM_STATES.PLANTING) {
        console.log('取消播种模式，切换为空闲状态');
        this.farmState = FARM_STATES.IDLE;
      } else {
        console.log('进入播种模式，请选择要播种的空地');
        this.farmState = FARM_STATES.PLANTING;
      }
    },
    onHarvestClick() {
      console.log(`点击收获按钮，当前农场状态: ${this.farmState}`);
      if (this.farmState === FARM_STATES.HARVESTING) {
        console.log('取消收获模式，切换为空闲状态');
        this.farmState = FARM_STATES.IDLE;
      } else {
        console.log('进入收获模式，请选择要收获的土地');
        this.farmState = FARM_STATES.HARVESTING;
      }
    },
    onPlotClick(index) {
      const plot = this.plots[index]
      console.log(`点击土地 ${index}，当前状态: ${plot.state}，农场状态: ${this.farmState}`)

      if (plot.state === PLOT_STATES.LOCKED) {
        console.log(`土地 ${index} 未解锁，无法操作`)
        uni.showToast({ title: '请先解锁该土地', icon: 'none' })
        return
      }

      if (this.farmState === FARM_STATES.PLANTING) {
        console.log(`当前为播种状态，尝试在土地 ${index} 播种`)
        if (plot.state !== PLOT_STATES.EMPTY) {
          console.log(`土地 ${index} 不是空地，无法播种，当前状态: ${plot.state}`)
          uni.showToast({ title: '只有空地可以播种', icon: 'none' })
          return
        }
        console.log(`在土地 ${index} 播种成功，状态更新为生长中`)
        this.updatePlotState(index, PLOT_STATES.GROWING)
        plot.plantedAt = Date.now()
        console.log(`土地 ${index} 开始生长，种植时间: ${new Date(plot.plantedAt).toLocaleString()}`)
        
        setTimeout(() => {
          if (plot.state === PLOT_STATES.GROWING) {
            console.log(`土地 ${index} 生长完成，状态更新为可收获`)
            this.updatePlotState(index, PLOT_STATES.HARVESTABLE)
          } else {
            console.log(`土地 ${index} 状态已改变，当前状态: ${plot.state}，不更新为可收获状态`)
          }
        }, 5000)
      } else if (this.farmState === FARM_STATES.HARVESTING) {
        console.log(`当前为收获状态，尝试收获土地 ${index}`)
        if (plot.state !== PLOT_STATES.HARVESTABLE) {
          console.log(`土地 ${index} 没有可收获的作物，当前状态: ${plot.state}`)
          uni.showToast({ title: '没有可以收获的花朵', icon: 'none' })
          return
        }
        console.log(`收获土地 ${index} 成功，状态更新为空地`)
        this.updatePlotState(index, PLOT_STATES.EMPTY)
        plot.plantedAt = null
        console.log(`发送收获完成事件`)
        this.$emit('harvest-complete')
      } else {
        console.log(`当前为空闲状态，点击土地 ${index} 无效，请先选择操作模式`)
      }
    },
    onContainerClick() {
      if (this.farmState !== FARM_STATES.IDLE) {
        console.log(`点击空白区域，从${this.farmState}状态切换为空闲状态`)
        this.farmState = FARM_STATES.IDLE
      }
    },
    getPlotStateText(state) {
      const stateTexts = {
        [PLOT_STATES.LOCKED]: '未解锁',
        [PLOT_STATES.EMPTY]: '空地',
        [PLOT_STATES.GROWING]: '生长中',
        [PLOT_STATES.HARVESTABLE]: '可收获'
      }
      return stateTexts[state]
    },
    getFarmStateText(state) {
      const stateTexts = {
        [FARM_STATES.IDLE]: '空闲',
        [FARM_STATES.PLANTING]: '播种状态',
        [FARM_STATES.HARVESTING]: '收获状态'
      }
      return stateTexts[state]
    }
  }
}
</script>

<style lang="scss">
@import './FarmDialog.scss';
</style> 