<template>
  <div class="blackmarket-card">
    <div class="card-header">
      <img src="/icons/Ob7pyorzmHiJcbab2c25af264d0758b527bc1b61cc3b.png" alt="黑市购买" class="icon" />
      <div class="info">
        <h3>小号黑市购买</h3>
        <p>自动购买黑市宝箱</p>
      </div>
      <div class="status-indicator" :class="statusClass">
        <span>{{ statusText }}</span>
      </div>
    </div>

    <!-- 配置区域 -->
    <div class="config-section">
      <div class="config-title">购买配置</div>
      <div class="config-grid">
        <div class="config-item">
          <label>青铜宝箱</label>
          <div class="discount-input">
            <span class="prefix">低于</span>
            <n-input-number
              v-model:value="config.bronzeDiscount"
              :min="0"
              :max="10"
              :step="1"
              size="small"
              placeholder="0-10"
              class="discount-number"
            />
            <span class="suffix">折购买</span>
          </div>
          <div class="price-info">原价: 400金砖</div>
        </div>

        <div class="config-item">
          <label>黄金宝箱</label>
          <div class="discount-input">
            <span class="prefix">低于</span>
            <n-input-number
              v-model:value="config.goldDiscount"
              :min="0"
              :max="10"
              :step="1"
              size="small"
              placeholder="0-10"
              class="discount-number"
            />
            <span class="suffix">折购买</span>
          </div>
          <div class="price-info">原价: 375金砖</div>
        </div>

        <div class="config-item">
          <label>铂金宝箱</label>
          <div class="discount-input">
            <span class="prefix">低于</span>
            <n-input-number
              v-model:value="config.platinumDiscount"
              :min="0"
              :max="10"
              :step="1"
              size="small"
              placeholder="0-10"
              class="discount-number"
            />
            <span class="suffix">折购买</span>
          </div>
          <div class="price-info">原价: 625金砖</div>
        </div>
      </div>

      <div class="config-tips">
        <n-alert type="info" size="small">
          <template #icon>
            <n-icon><InformationCircle /></n-icon>
          </template>
          0折=不购买，10折=无视折扣直接购买，1-9折=小于等于该折扣才购买
        </n-alert>
      </div>
    </div>

    <!-- 当前资源显示 -->
    <div class="resource-section">
      <div class="resource-item">
        <span class="label">当前金砖:</span>
        <span class="value" :class="{ 'insufficient': currentDiamonds < 100 }">
          {{ formatNumber(currentDiamonds) }}
        </span>
      </div>
      <div v-if="estimatedCost > 0" class="resource-item">
        <span class="label">预估消耗:</span>
        <span class="value">{{ formatNumber(estimatedCost) }}</span>
      </div>
    </div>

    <!-- 执行状态 -->
    <div v-if="isExecuting" class="execution-status">
      <div class="status-header">
        <n-icon size="16" class="loading-icon"><Refresh /></n-icon>
        <span>{{ currentStep }}</span>
      </div>
      <n-progress
        :percentage="progress"
        :show-indicator="false"
        type="line"
        status="info"
        :height="6"
      />
    </div>

    <!-- 执行结果 -->
    <div v-if="executionResult" class="result-section">
      <div class="result-header">
        <n-icon size="16" :color="executionResult.success ? '#18a058' : '#d03050'">
          <CheckmarkCircle v-if="executionResult.success" />
          <CloseCircle v-else />
        </n-icon>
        <span>执行结果</span>
        <n-button text size="small" @click="clearResult">
          <n-icon><Close /></n-icon>
        </n-button>
      </div>
      <div class="result-content">
        <div v-if="executionResult.purchases.length > 0" class="purchase-summary">
          <div v-for="purchase in executionResult.purchases" :key="purchase.name" class="purchase-item">
            <span>{{ purchase.name }}: {{ purchase.count }}次</span>
          </div>
        </div>
        <div v-if="executionResult.totalCost > 0" class="cost-summary">
          总消耗: {{ formatNumber(executionResult.totalCost) }}金砖
        </div>
        <div v-if="executionResult.message" class="result-message">
          {{ executionResult.message }}
        </div>
      </div>
    </div>

    <!-- 操作按钮 -->
    <div class="actions">
      <n-button
        type="primary"
        :loading="isExecuting"
        :disabled="!canExecute"
        @click="startPurchase"
        block
      >
        {{ isExecuting ? '执行中...' : '开始购买' }}
      </n-button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useMessage } from 'naive-ui'
import { useTokenStore } from '@/stores/tokenStore'
import { 
  InformationCircle, 
  Refresh, 
  CheckmarkCircle, 
  CloseCircle, 
  Close 
} from '@vicons/ionicons5'

const message = useMessage()
const tokenStore = useTokenStore()

// 配置数据
const config = ref({
  bronzeDiscount: 8,   // 默认8折
  goldDiscount: 8,     // 默认8折
  platinumDiscount: 8  // 默认8折
})

// 商品信息
const GOODS_INFO = {
  1: { name: '青铜宝箱', price: 400 },
  2: { name: '黄金宝箱', price: 375 },
  3: { name: '铂金宝箱', price: 625 }
}

// 执行状态
const isExecuting = ref(false)
const currentStep = ref('')
const progress = ref(0)
const executionResult = ref(null)

// 当前金砖数量
const currentDiamonds = computed(() => {
  const gameData = tokenStore.gameData
  const role = gameData?.roleInfo?.role
  return role?.diamond ?? 0
})

// 预估消耗（按原价计算）
const estimatedCost = computed(() => {
  let cost = 0
  if (config.value.bronzeDiscount > 0) cost += GOODS_INFO[1].price * 2 // 两轮购买
  if (config.value.goldDiscount > 0) cost += GOODS_INFO[2].price * 2
  if (config.value.platinumDiscount > 0) cost += GOODS_INFO[3].price * 2
  cost += 100 // 刷新费用
  return cost
})

// 是否可以执行
const canExecute = computed(() => {
  return !isExecuting.value && 
         tokenStore.selectedToken && 
         tokenStore.getWebSocketStatus(tokenStore.selectedToken.id) === 'connected' &&
         (config.value.bronzeDiscount > 0 || config.value.goldDiscount > 0 || config.value.platinumDiscount > 0)
})

// 状态显示
const statusClass = computed(() => {
  if (isExecuting.value) return 'executing'
  if (!tokenStore.selectedToken) return 'no-token'
  if (tokenStore.getWebSocketStatus(tokenStore.selectedToken.id) !== 'connected') return 'disconnected'
  return 'ready'
})

const statusText = computed(() => {
  if (isExecuting.value) return '执行中'
  if (!tokenStore.selectedToken) return '未选择Token'
  if (tokenStore.getWebSocketStatus(tokenStore.selectedToken.id) !== 'connected') return '未连接'
  return '就绪'
})

// 格式化数字
const formatNumber = (num) => {
  const n = Number(num || 0)
  const yi = 100_000_000
  const wan = 10_000
  if (n >= yi) return (n / yi).toFixed(1) + '亿'
  if (n >= wan) return (n / wan).toFixed(1) + '万'
  return n.toLocaleString()
}

// 清除结果
const clearResult = () => {
  executionResult.value = null
}

// 延迟函数
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms))

// 发送命令（只要发送成功就视为成功）
const sendCommand = async (command, body) => {
  const tokenId = tokenStore.selectedToken.id
  
  try {
    // 直接发送命令，不等待响应
    const success = tokenStore.sendMessage(tokenId, command, body)
    if (success) {
      console.log(`✅ 命令 ${command} 发送成功`)
      return { success: true }
    } else {
      throw new Error('命令发送失败')
    }
  } catch (error) {
    console.error(`❌ 命令 ${command} 发送失败:`, error.message)
    throw error
  }
}

// 获取黑市折扣信息
const getMarketDiscounts = async () => {
  currentStep.value = '正在获取黑市折扣信息...'
  progress.value = 10
  
  try {
    await sendCommand('store_goodslist', { storeId: 1 })
    // 等待一下让服务器处理
    await delay(500)
    console.log('✅ 获取黑市折扣命令已发送')
  } catch (error) {
    console.warn('获取黑市折扣命令发送失败:', error.message)
  }
  
  // 返回默认折扣（所有商品都可购买）
  return {
    1: { discount: 1, buy_quantity: 0 },
    2: { discount: 1, buy_quantity: 0 },
    3: { discount: 1, buy_quantity: 0 }
  }
}

// 刷新黑市
const refreshMarket = async () => {
  currentStep.value = '正在刷新黑市...'
  progress.value = 30
  
  // 检查金砖是否足够刷新
  if (currentDiamonds.value < 100) {
    throw new Error(`金砖不足，无法刷新黑市（需要100金砖，当前${currentDiamonds.value}）`)
  }
  
  try {
    await sendCommand('store_refresh', { storeId: 1 })
    // 等待一下让服务器处理
    await delay(500)
    console.log('✅ 刷新黑市命令已发送')
    
    // 返回默认商品列表（刷新后所有商品都可购买）
    return {
      1: { discount: 1, buy_quantity: 0 },
      2: { discount: 1, buy_quantity: 0 },
      3: { discount: 1, buy_quantity: 0 }
    }
  } catch (error) {
    throw new Error(`刷新黑市命令发送失败: ${error.message}`)
  }
}

// 购买商品
const purchaseGoods = async (goodsId, goodsName, actualPrice) => {
  currentStep.value = `正在购买${goodsName}...`
  
  // 检查金砖是否足够
  if (currentDiamonds.value < actualPrice) {
    throw new Error(`金砖不足，无法购买${goodsName}（需要${actualPrice}金砖，当前${currentDiamonds.value}）`)
  }
  
  try {
    await sendCommand('store_buy', { goodsId })
    // 等待一下让服务器处理
    await delay(300)
    console.log(`✅ 购买${goodsName}命令已发送`)
    return true // 命令发送成功就视为购买成功
  } catch (error) {
    throw new Error(`购买${goodsName}命令发送失败: ${error.message}`)
  }
}

// 执行购买流程
const executePurchaseRound = async (goodsList, roundName) => {
  const purchases = []
  let totalCost = 0
  
  // 按顺序购买：青铜宝箱(1) -> 黄金宝箱(2) -> 铂金宝箱(3)
  for (const goodsId of [1, 2, 3]) {
    const goods = goodsList[goodsId]
    if (!goods) continue
    
    const goodsInfo = GOODS_INFO[goodsId]
    const configKey = goodsId === 1 ? 'bronzeDiscount' : 
                     goodsId === 2 ? 'goldDiscount' : 'platinumDiscount'
    const discountThreshold = config.value[configKey] / 10 // 转换为小数
    
    // 检查是否需要购买
    if (config.value[configKey] === 0) {
      console.log(`${roundName}: ${goodsInfo.name} 配置为不购买，跳过`)
      continue
    }
    
    // 检查折扣条件
    if (config.value[configKey] < 10 && goods.discount > discountThreshold) {
      console.log(`${roundName}: ${goodsInfo.name} 折扣${goods.discount}不满足条件(≤${discountThreshold})，跳过`)
      continue
    }
    
    // 检查是否已购买
    if (goods.buy_quantity > 0) {
      console.log(`${roundName}: ${goodsInfo.name} 已购买，跳过`)
      continue
    }
    
    const actualPrice = Math.ceil(goodsInfo.price * goods.discount)
    
    try {
      const success = await purchaseGoods(goodsId, goodsInfo.name, actualPrice)
      if (success) {
        purchases.push({ name: goodsInfo.name, count: 1 })
        totalCost += actualPrice
        console.log(`${roundName}: 成功购买${goodsInfo.name}，消耗${actualPrice}金砖`)
      }
    } catch (error) {
      console.warn(`${roundName}: ${error.message}`)
      // 继续购买下一个商品
    }
    
    await delay(100) // 购买间隔
  }
  
  return { purchases, totalCost }
}

// 开始购买
const startPurchase = async () => {
  if (!canExecute.value) return
  
  isExecuting.value = true
  progress.value = 0
  executionResult.value = null
  
  const allPurchases = []
  let totalCost = 0
  let errorMessage = ''
  
  try {
    // 检查WebSocket连接状态
    if (tokenStore.getWebSocketStatus(tokenStore.selectedToken.id) !== 'connected') {
      throw new Error('WebSocket连接已断开，请重新连接后再试')
    }
    // 第一步：获取黑市折扣信息
    let goodsList = await getMarketDiscounts()
    
    // 第二步：第一轮购买
    currentStep.value = '执行第一轮购买...'
    progress.value = 40
    
    const firstRound = await executePurchaseRound(goodsList, '第一轮')
    allPurchases.push(...firstRound.purchases)
    totalCost += firstRound.totalCost
    
    await delay(200)
    
    // 第三步：刷新黑市
    try {
      goodsList = await refreshMarket()
      totalCost += 100 // 刷新费用
    } catch (error) {
      errorMessage = error.message
      console.warn('刷新黑市命令发送失败:', error.message)
      
      // 如果是金砖不足，直接跳过后续购买
      if (error.message.includes('金砖不足')) {
        throw error
      }
      
      // 其他错误继续执行，使用原有商品列表
      console.warn('使用原有商品列表继续执行第二轮购买')
    }
    
    // 第四步：第二轮购买
    currentStep.value = '执行第二轮购买...'
    progress.value = 70
    
    const secondRound = await executePurchaseRound(goodsList, '第二轮')
    allPurchases.push(...secondRound.purchases)
    totalCost += secondRound.totalCost
    
    // 合并相同商品的购买次数
    const mergedPurchases = []
    const purchaseMap = {}
    
    allPurchases.forEach(purchase => {
      if (purchaseMap[purchase.name]) {
        purchaseMap[purchase.name] += purchase.count
      } else {
        purchaseMap[purchase.name] = purchase.count
      }
    })
    
    Object.entries(purchaseMap).forEach(([name, count]) => {
      mergedPurchases.push({ name, count })
    })
    
    // 完成
    progress.value = 100
    currentStep.value = '购买完成'
    
    executionResult.value = {
      success: true,
      purchases: mergedPurchases,
      totalCost,
      message: errorMessage ? 
        `黑市购买任务完成（${errorMessage}）` : 
        '黑市购买任务完成'
    }
    
    const totalPurchases = mergedPurchases.reduce((sum, p) => sum + p.count, 0)
    message.success(`黑市购买完成！成功购买${totalPurchases}个宝箱，消耗${formatNumber(totalCost)}金砖`)
    
  } catch (error) {
    console.error('黑市购买失败:', error)
    
    executionResult.value = {
      success: false,
      purchases: allPurchases,
      totalCost,
      message: error.message
    }
    
    message.error(`黑市购买失败: ${error.message}`)
  } finally {
    isExecuting.value = false
    currentStep.value = ''
    progress.value = 0
  }
}

// 保存配置到localStorage
const saveConfig = () => {
  try {
    localStorage.setItem('blackmarket_config', JSON.stringify(config.value))
  } catch (error) {
    console.warn('保存黑市配置失败:', error)
  }
}

// 加载配置从localStorage
const loadConfig = () => {
  try {
    const saved = localStorage.getItem('blackmarket_config')
    if (saved) {
      const parsed = JSON.parse(saved)
      config.value = { ...config.value, ...parsed }
    }
  } catch (error) {
    console.warn('加载黑市配置失败:', error)
  }
}

// 监听配置变化并保存
watch(config, saveConfig, { deep: true })

onMounted(() => {
  loadConfig()
})
</script>

<style scoped lang="scss">
.blackmarket-card {
  background: var(--bg-primary);
  border-radius: var(--border-radius-xl);
  padding: var(--spacing-lg);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  border-left: 4px solid #f59e0b;
}

.card-header {
  display: flex;
  align-items: center;
  gap: var(--spacing-md);
  margin-bottom: var(--spacing-lg);
  
  .icon {
    width: 32px;
    height: 32px;
    object-fit: contain;
  }
  
  .info {
    flex: 1;
    
    h3 {
      margin: 0 0 var(--spacing-xs) 0;
      font-size: var(--font-size-lg);
      font-weight: var(--font-weight-semibold);
      color: var(--text-primary);
    }
    
    p {
      margin: 0;
      color: var(--text-secondary);
      font-size: var(--font-size-sm);
    }
  }
  
  .status-indicator {
    padding: var(--spacing-xs) var(--spacing-sm);
    border-radius: var(--border-radius-small);
    font-size: var(--font-size-xs);
    font-weight: var(--font-weight-medium);
    
    &.ready {
      background: rgba(24, 160, 88, 0.1);
      color: var(--success-color);
    }
    
    &.executing {
      background: rgba(240, 160, 32, 0.1);
      color: var(--warning-color);
    }
    
    &.no-token, &.disconnected {
      background: rgba(208, 48, 80, 0.1);
      color: var(--error-color);
    }
  }
}

.config-section {
  margin-bottom: var(--spacing-lg);
  
  .config-title {
    font-size: var(--font-size-md);
    font-weight: var(--font-weight-semibold);
    color: var(--text-primary);
    margin-bottom: var(--spacing-md);
  }
  
  .config-grid {
    display: grid;
    gap: var(--spacing-md);
  }
  
  .config-item {
    background: var(--bg-secondary);
    border-radius: var(--border-radius-medium);
    padding: var(--spacing-md);
    
    label {
      display: block;
      font-weight: var(--font-weight-medium);
      color: var(--text-primary);
      margin-bottom: var(--spacing-sm);
    }
    
    .discount-input {
      display: flex;
      align-items: center;
      gap: var(--spacing-sm);
      margin-bottom: var(--spacing-xs);
      
      .prefix, .suffix {
        font-size: var(--font-size-sm);
        color: var(--text-secondary);
      }
      
      .discount-number {
        width: 80px;
      }
    }
    
    .price-info {
      font-size: var(--font-size-xs);
      color: var(--text-secondary);
    }
  }
  
  .config-tips {
    margin-top: var(--spacing-md);
  }
}

.resource-section {
  background: var(--bg-secondary);
  border-radius: var(--border-radius-medium);
  padding: var(--spacing-md);
  margin-bottom: var(--spacing-lg);
  
  .resource-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    &:not(:last-child) {
      margin-bottom: var(--spacing-xs);
    }
    
    .label {
      font-size: var(--font-size-sm);
      color: var(--text-secondary);
    }
    
    .value {
      font-weight: var(--font-weight-semibold);
      color: var(--text-primary);
      
      &.insufficient {
        color: var(--error-color);
      }
    }
  }
}

.execution-status {
  background: var(--bg-secondary);
  border-radius: var(--border-radius-medium);
  padding: var(--spacing-md);
  margin-bottom: var(--spacing-lg);
  
  .status-header {
    display: flex;
    align-items: center;
    gap: var(--spacing-sm);
    margin-bottom: var(--spacing-sm);
    
    .loading-icon {
      animation: spin 1s linear infinite;
    }
    
    span {
      font-size: var(--font-size-sm);
      color: var(--text-primary);
    }
  }
}

.result-section {
  background: var(--bg-secondary);
  border-radius: var(--border-radius-medium);
  padding: var(--spacing-md);
  margin-bottom: var(--spacing-lg);
  
  .result-header {
    display: flex;
    align-items: center;
    gap: var(--spacing-sm);
    margin-bottom: var(--spacing-sm);
    
    span {
      flex: 1;
      font-weight: var(--font-weight-medium);
      color: var(--text-primary);
    }
  }
  
  .result-content {
    .purchase-summary {
      margin-bottom: var(--spacing-sm);
      
      .purchase-item {
        font-size: var(--font-size-sm);
        color: var(--text-primary);
        margin-bottom: var(--spacing-xs);
      }
    }
    
    .cost-summary {
      font-size: var(--font-size-sm);
      color: var(--text-secondary);
      margin-bottom: var(--spacing-sm);
    }
    
    .result-message {
      font-size: var(--font-size-sm);
      color: var(--text-secondary);
    }
  }
}

.actions {
  display: flex;
  gap: var(--spacing-sm);
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

// 响应式设计
@media (max-width: 768px) {
  .blackmarket-card {
    padding: var(--spacing-md);
  }
  
  .config-grid {
    grid-template-columns: 1fr;
  }
  
  .discount-input {
    flex-wrap: wrap;
  }
}
</style>
