<template>
  <custom-dialog 
    :visible.sync="dialogVisible" 
    title="" 
    content-width="720rpx" 
    closeImg="/static/island/UI/btn_close.png" 
    closeImgTop="50rpx" 
    background-color="transparent"
    @close="onClose"
  >
    <view class="shop-content">
      <!-- <view class="shop-tabs">
        <view 
          v-for="(tab, index) in tabs" 
          :key="index"
          class="tab-item"
          :class="{'active': currentTab === index}"
          @click="currentTab = index"
        >
          {{tab}}
        </view>
      </view> -->
      <view class="shop-header"></view>
      <view class="shop-name">{{shopName}}</view>
      <view class="shop-items">
        <view class="shop-item" v-for="(item, index) in shopItems" :key="index" @click="onItemClick(item)">
          <view class="item-card">
            <view class="new-tag" v-if="item.isNew">新品</view>
            <view class="item-left">
              <view class="item-grid">
                <image class="item-icon" :src="item.image || defaultImage" mode="aspectFit"></image>
                <text class="owned-text">已有: {{item.num || 0}}</text>
              </view>
            </view>
            <view class="item-center">
              <text class="item-name">{{item.name}}</text>
              <view class="item-details">
                <text class="detail-text">{{getItemDetail(item)}}</text>
              </view>
            </view>
            <view class="item-right">
              <view class="buy-btn" @click.stop="buyItem(item)">
                <view class="item-price">
                  <image class="currency-icon" src="/static/island/UI/wd_icon_xingyuan.png" mode="aspectFit"></image>
                  <text>{{item.price}}</text>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
  </custom-dialog>
</template>

<script>
import CustomDialog from '../CustomDialog/CustomDialog.vue' 

export default {
  name: 'ShopDialog',
  components: {
    CustomDialog
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    shopName: {
      type: String,
      default: '商店'
    }
  },
  data() {
    return {
      dialogVisible: false,
      currentTab: 0,
      tabs: ['种子', '道具', '钻石'],
      shopItems: [],
      defaultImage: '/static/island/items/default.png',
      shopType: 'main', // 默认商店类型
      userMoney: 0, // 用户铃钱
      loading: false
    }
  },
  computed: {
    currentItems() {
      return this.items[this.currentTab]
    }
  },
  watch: {
    visible(val) {
      this.dialogVisible = val
      if (val) {
        // this.fetchShopData()
      }
    },
    dialogVisible(val) {
      this.$emit('update:visible', val)
    },
    shopName: {
      immediate: true,
      handler(val) {
        console.log("shopName",val)
        if (val === '材料商店') {
          this.shopType = 'main'
        } else if (val === '花店') {
          this.shopType = 'huatian'
        } else {
          this.shopType = 'main'
        }
        // 如果对话框可见，则重新获取数据
        if (this.dialogVisible) {
        }
        this.fetchShopData()
      }
    }
  },
  methods: {
    onClose() {
      this.dialogVisible = false
    },
    onItemClick(item) {
      this.$emit('buy', item)
    },
    // 获取商店数据
    async fetchShopData() {
      if (this.loading) return
      this.loading = true
      console.log("shoptype",this.shopType)
      try {
        uni.request({
          url: this.$apiHost + '/Game/get_shop_list',
          method: 'GET',
          data: {
            uuid: getApp().globalData.uuid,
            type: this.shopType
          },
          header: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'sign': getApp().globalData.headerSign,
          },
          success: (res) => {
            console.log("res",res.data)
            if (res.data && res.data.code === 0) {
              this.shopItems = res.data.list || []
              
              // 获取用户铃钱
              this.getUserMoney()
            } else {
              uni.showToast({
                title: res.data?.msg || '获取商店数据失败',
                icon: 'none'
              })
            }
          },
          fail: (err) => {
            console.error('获取商店数据异常', err)
            uni.showToast({
              title: '网络异常，请重试',
              icon: 'none'
            })
          },
          complete: () => {
            this.loading = false
          }
        })
      } catch (error) {
        console.error('获取商店数据异常', error)
        uni.showToast({
          title: '网络异常，请重试',
          icon: 'none'
        })
        this.loading = false
      }
    },
    // 获取用户铃钱
    getUserMoney() {
      uni.request({
        url: this.$apiHost + '/User/getinfo',
        method: 'GET',
        data: {
          uuid: getApp().globalData.uuid
        },
        header: {
          'Content-Type': 'application/x-www-form-urlencoded',
          'sign': getApp().globalData.headerSign,
        },
        success: (res) => {
          if (res.data && res.data.code === 0) {
            this.userMoney = res.data.num_gmg || 0
          }
        }
      })
    },
    // 购买物品
    buyItem(item) {
      if (this.userMoney < item.price) {
        uni.showToast({
          title: '铃钱不足',
          icon: 'none'
        })
        return
      }
      
      uni.request({
        url: this.$apiHost + '/Game/buy_shop_item',
        method: 'POST',
        data: {
          uuid: getApp().globalData.uuid,
          shop_id: item.id
        },
        header: {
          'Content-Type': 'application/x-www-form-urlencoded',
          'sign': getApp().globalData.headerSign,
        },
        success: (res) => {
          if (res.data && res.data.code === 0) {
            uni.showToast({
              title: '购买成功',
              icon: 'success'
            })
            
            // 更新用户铃钱
            this.userMoney = res.data.data.money
            
            // 更新物品数量
            const index = this.shopItems.findIndex(i => i.id === item.id)
            if (index !== -1) {
              this.shopItems[index].num = (this.shopItems[index].num || 0) + 1
            }
            
            // 通知父组件购买成功
            this.$emit('buy-success', item)
          } else {
            uni.showToast({
              title: res.data?.msg || '购买失败',
              icon: 'none'
            })
          }
        },
        fail: (err) => {
          console.error('购买物品异常', err)
          uni.showToast({
            title: '网络异常，请重试',
            icon: 'none'
          })
        }
      })
    },
    // 获取物品详情
    getItemDetail(item) {
      if (this.shopType === 'huatian') {
        return `收获期: ${item.limit_time}时\n产量: ${item.num_out}`
      } else {
        return item.content || '暂无描述'
      }
    }
  }
}
</script>

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