<template>
  <custom-dialog 
    :visible.sync="dialogVisible" 
    title="" 
    content-width="720rpx" 
    closeImg="/static/island/UI/btn_close.png" 
    closeImgTop="120rpx" 
    background-color="transparent"
    @close="onClose"
  >
    <view class="backpack-content">
      <view class="backpack-name">背包</view>
      <view class="backpack-items">
        <view 
          class="backpack-grid" 
          v-for="index in 80" 
          :key="index"
          @click="onGridClick(index-1)"
        >
          <view 
            class="item-grid"
            :class="{'selected': selectedIndex === index-1 && items[index-1]}"
          >
            <template v-if="items[index-1]">
              <text class="count-text">{{items[index-1].count}}</text>
              <image class="item-icon" :src="items[index-1].icon" mode="aspectFit"></image>
              <text class="item-name">{{items[index-1].name}}</text>
            </template>
          </view>
        </view>
      </view>
      <view class="backpack-bottom">
        <view class="bottom-info">
          <text>{{selectedItem ? selectedItem.description : '请选择道具查看详情'}}</text>
        </view>
        <view class="bottom-actions">
          <view class="coin-info">
            <image class="currency-icon" src="/static/island/UI/wd_icon_xingyuan.png" mode="aspectFit"></image>
            <text>{{selectedItem ? selectedItem.price : 0}}</text>
          </view>
          <view class="sell-btn" :class="{'disabled': !selectedItem}" @click="onSellClick">售卖</view>
        </view>
      </view>
    </view>
  </custom-dialog>
</template>

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

export default {
  name: 'BackpackDialog',
  components: {
    CustomDialog
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      dialogVisible: false,
      selectedIndex: -1,
      items: [],
      loading: false
    }
  },
  computed: {
    selectedItem() {
      return this.selectedIndex >= 0 && this.selectedIndex < this.items.length 
        ? this.items[this.selectedIndex] 
        : null
    }
  },
  watch: {
    visible(val) {
      this.dialogVisible = val
      if(val) {
        this.fetchBagList()
      }
    },
    dialogVisible(val) {
      this.$emit('update:visible', val)
    }
  },
  methods: {
    fetchBagList() {
      this.loading = true
      uni.request({
        url: this.$apiHost + '/Game/get_bag_list',
        method: 'GET',
        data: {
          uuid: getApp().globalData.uuid,
        },
          header: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'sign': getApp().globalData.headerSign,
          },
        success: (res) => {
          if (res.data.code === 0) {
            this.items = res.data.data.bagList.map(item => ({
              id: item.id,
              tid: item.tid,
              type: item.type,
              count: item.num,
              name: item.name,
              icon: item.image,
              description: `这是一个${item.name}，数量：${item.num}`,
              price: item.price // 这里可以根据实际需求设置价格
            }))
            // 默认选中第一个有道具的格子
            this.selectedIndex = this.items.length > 0 ? 0 : -1
          } else {
            uni.showToast({
              title: res.data.msg || '获取背包数据失败',
              icon: 'none'
            })
          }
        },
        fail: (err) => {
          console.error('获取背包数据失败:', err)
          uni.showToast({
            title: '获取背包数据失败',
            icon: 'none'
          })
        },
        complete: () => {
          this.loading = false
        }
      })
    },
    onClose() {
      this.dialogVisible = false
    },
    onGridClick(index) {
      if(this.items[index]) {
        this.selectedIndex = index
        this.$emit('select', this.items[index])
      }
    },
    onSellClick() {
      if(!this.selectedItem) return
      
      const item = this.selectedItem
      const totalPrice = item.count * item.price
      
      uni.showModal({
        title: '确认出售',
        content: `出售${item.count}个${item.name}，会获得铃钱：${totalPrice},\n确定出售吗？`,
        confirmText: '确定',
        cancelText: '取消',
        success: (res) => {
          if(res.confirm) {
            uni.request({
              url: this.$apiHost + '/Game/sell_bag_item',
              method: 'POST',
              data: {
                uuid: getApp().globalData.uuid,
                bag_id: item.id
              },
              header: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'sign': getApp().globalData.headerSign,
              },
              success: (res) => {
                if (res.data.code === 0) {
                  uni.showToast({
                    title: '出售成功',
                    icon: 'success'
                  })
                  // 刷新背包列表
                  this.fetchBagList()
                  // 通知父组件更新铃钱
                  this.$emit('money-change', res.data.data.money)
                } else {
                  uni.showToast({
                    title: res.data.msg || '出售失败',
                    icon: 'none'
                  })
                }
              },
              fail: (err) => {
                console.error('出售失败:', err)
                uni.showToast({
                  title: '出售失败',
                  icon: 'none'
                })
              }
            })
          }
        }
      })
    }
  }
}
</script>

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