<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="showSellConfirm">售卖</view>
        </view>
      </view>
    </view>
  <!-- 确认出售对话框 -->
  <view class="confirm-dialog" v-if="showSellDialog">
    <view class="dialog-content">
      <view class="dialog-title">确认出售</view>
      <view class="dialog-text">是否出售{{selectedItem ? selectedItem.count : 0}}个{{selectedItem ? selectedItem.name : ''}}，获得铃钱：{{selectedItem ? selectedItem.count * selectedItem.price : 0}}？</view>
      <view class="dialog-buttons">
        <view class="btn-cancel" @click="cancelSell">取消</view>
        <view class="btn-confirm" @click="confirmSell">确认</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,
      showSellDialog: 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])
      }
    },
    // 显示确认出售对话框
    showSellConfirm() {
      if(!this.selectedItem) return
      this.showSellDialog = true
    },
    // 取消出售
    cancelSell() {
      this.showSellDialog = false
    },
    // 确认出售
    confirmSell() {
      if(!this.selectedItem) return
      
      const item = this.selectedItem
      
      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'
          })
        }
      })
      
      this.showSellDialog = false
    }
  }
}
</script>

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

// 添加确认对话框样式
.confirm-dialog {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 999;

  .dialog-content {
    width: 500rpx;
    background: #FDDEC1;
    border-radius: 20rpx;
    overflow: hidden;
    box-shadow: 0 4rpx 10rpx rgba(0, 0, 0, 0.1);
    border: 2rpx solid #d06262;

    .dialog-title {
      text-align: center;
      color: #683830;
      font-size: 34rpx;
      font-weight: bold;
      padding: 20rpx 0;
      border-bottom: 0rpx solid #d06262;
      position: relative;
    }

    .dialog-text {
      padding: 40rpx 30rpx;
      text-align: center;
      font-size: 30rpx;
      color: #987453;
      border-radius: 0 0 12rpx 12rpx;
      position: relative;
    }

    .dialog-buttons {
      display: flex;
      justify-content: space-around;
      padding: 30rpx;

      .btn-cancel,
      .btn-confirm {
        width: 180rpx;
        height: 80rpx;
        border-radius: 40rpx;
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 32rpx;
        font-weight: bold;
        width: 184rpx;
        height: 80rpx;
        background: url('/static/island/huatian/zx_btn_queren.png');
        background-size: 184rpx 80rpx;
      }

      .btn-cancel {
        color: white;
        position: relative;
        width: 184rpx;
        height: 80rpx;
        background: url('/static/island/huatian/zx_btn_quxiao.png');
        background-size: 184rpx 80rpx;
      }

      .btn-confirm {
        color: white;
        position: relative;
      }
    }
  }
}
</style> 