<template>
  <view class="scoring-page">
    <!-- 顶部导航 -->
    <view class="nav-bar">
      <view class="nav-back" @click="goBack">
        <uni-icons type="arrowleft" size="24" color="#fff"></uni-icons>
      </view>
      <view class="nav-title">
        {{ isEditMode ? '修改' : '第' + currentRound + '局' }}
        <text v-if="isEditMode">第{{ currentRound }}局</text>
      </view>
      <view class="nav-actions">
        <uni-icons type="more" size="24" color="#fff"></uni-icons>
      </view>
    </view>

    <!-- 玩家计分表格 -->
    <view class="player-table">
      <view class="table-header">
        <text>玩家</text>
        <text>胜负</text>
        <text>得分</text>
      </view>
      
      <!-- 动态渲染每个玩家的计分行 -->
      <view class="table-row" v-for="(player, index) in players" :key="player.id">
        <view class="player-info">
          <image class="player-avatar" :src="player.avatar" mode="aspectFit"></image>
          <text class="player-name">{{ player.name }}</text>
          <view v-if="player.isSelf" class="self-tag">自己</view>
        </view>
        <view class="win-lose">
          <button class="win-btn" :class="{ active: player.isWin }" @click="setWinStatus(index, true)">胜</button>
          <button class="lose-btn" :class="{ active: !player.isWin }" @click="setWinStatus(index, false)">负</button>
        </view>
        <view class="score-input">
          <input 
            type="text" 
            v-model="player.currentScore" 
            placeholder="0" 
            class="score-text" 
            @focus="setCurrentPlayer(index)"
            @input="checkTotalScore"
          />
          <button class="sum-btn" @click="calculateTotalScore(index)">∑ 合分</button>
        </view>
      </view>
    </view>

    <!-- 总分检查提示 -->
    <view v-if="showScoreWarning" class="score-warning">
      对局分数相加不为0,请检查！
    </view>

    <!-- 数字键盘 -->
    <view class="keypad">
      <view class="keypad-row">
        <button class="keypad-btn" @click="inputNumber(1)">1</button>
        <button class="keypad-btn" @click="inputNumber(2)">2</button>
        <button class="keypad-btn" @click="inputNumber(3)">3</button>
        <button class="keypad-btn" @click="inputOperator('+')">+</button>
        <button class="keypad-btn" @click="deleteLast">⌫</button>
      </view>
      <view class="keypad-row">
        <button class="keypad-btn" @click="inputNumber(4)">4</button>
        <button class="keypad-btn" @click="inputNumber(5)">5</button>
        <button class="keypad-btn" @click="inputNumber(6)">6</button>
        <button class="keypad-btn" @click="inputOperator('-')">-</button>
        <button class="keypad-btn submit-btn" :class="{ disabled: !canSubmit }" @click="submitScore" :disabled="!canSubmit">
          {{ isEditMode ? '更新' : '提交' }}
        </button>
      </view>
      <view class="keypad-row">
        <button class="keypad-btn" @click="inputNumber(7)">7</button>
        <button class="keypad-btn" @click="inputNumber(8)">8</button>
        <button class="keypad-btn" @click="inputNumber(9)">9</button>
        <button class="keypad-btn" @click="inputNumber(0)">0</button>
        <button class="keypad-btn clear-btn" @click="clearScore">清空</button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'

// 玩家数据
const players = ref([])
// 当前操作的玩家索引
const currentPlayerIndex = ref(0)
// 当前对局数
const currentRound = ref(1)
// 是否显示分数警告
const showScoreWarning = ref(false)
// 是否可以提交
const canSubmit = ref(false)
// 是否为编辑模式
const isEditMode = ref(false)
// 编辑的对局索引
const editRoundIndex = ref(-1)

// 使用 onMounted 替代 onLoad
onMounted(() => {
  // 获取页面参数
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  const options = currentPage.options || {}
  
  // 判断是否为编辑模式
  isEditMode.value = options.mode === 'edit'
  if (isEditMode.value && options.roundIndex) {
    editRoundIndex.value = parseInt(options.roundIndex)
  }
  
  if (options.players) {
    try {
      const playerData = JSON.parse(decodeURIComponent(options.players))
      // 初始化每个玩家的胜负状态和得分
      players.value = playerData.map(player => ({
        ...player,
        // 编辑模式下使用传入的胜负状态和得分，新增模式下使用默认值
        isWin: player.isWin !== undefined ? player.isWin : true,
        currentScore: player.currentScore || '0',
        finalScore: player.finalScore || 0
      }))
    } catch (e) {
      console.error('解析玩家数据失败:', e)
      setDefaultPlayers()
    }
  } else {
    setDefaultPlayers()
  }
  
  // 获取当前对局数
  if (options.round) {
    currentRound.value = parseInt(options.round)
  }
  
  // 初始化时检查总分
  checkTotalScore()
})

// 设置默认玩家数据
const setDefaultPlayers = () => {
  players.value = [
    {
      id: 1,
      name: '玩家80061',
      avatar: 'https://ts1.tc.mm.bing.net/th/id/OIP-C.QQG4bvcAR3CJ0WeQULA9UQAAAA?w=275&h=211&c=8&rs=1&qlt=90&o=6&cb=ucfimgc1&dpr=1.5&pid=3.1&rm=2',
      totalScore: 0,
      isSelf: true,
      isWin: true,
      currentScore: '0',
      finalScore: 0
    },
    {
      id: 2,
      name: '玩家2',
      avatar: 'https://tse2-mm.cn.bing.net/th/id/OIP-C.Pbhgd_vCFFNQWXi7y-HynAAAAA?w=209&h=209&c=7&r=0&o=7&cb=ucfimgc2&dpr=1.5&pid=1.7&rm=3',
      totalScore: 0,
      isSelf: false,
      isWin: true,
      currentScore: '0',
      finalScore: 0
    }
  ]
}

// 安全计算表达式（只支持加减法）
const safeCalculate = (expression) => {
  if (!expression || expression === '0') return 0
  
  try {
    // 移除所有空格
    const cleanExpr = expression.replace(/\s+/g, '')
    
    // 验证表达式只包含数字和加减号
    if (!/^[\d+\-]+$/.test(cleanExpr)) {
      console.warn('表达式包含非法字符:', expression)
      return 0
    }
    
    // 分割数字和运算符
    const numbers = cleanExpr.split(/[+\-]/).map(num => parseInt(num) || 0)
    const operators = cleanExpr.split(/\d+/).filter(op => op !== '')
    
    // 如果没有运算符，直接返回数字
    if (operators.length === 0) {
      return numbers[0] || 0
    }
    
    // 从第一个数字开始计算
    let result = numbers[0]
    
    // 遍历运算符进行计算
    for (let i = 0; i < operators.length; i++) {
      const operator = operators[i]
      const nextNumber = numbers[i + 1] || 0
      
      if (operator === '+') {
        result += nextNumber
      } else if (operator === '-') {
        result -= nextNumber
      }
    }
    
    return result
  } catch (error) {
    console.error('计算表达式失败:', error, expression)
    return 0
  }
}

// 检查总分是否为0
const checkTotalScore = () => {
  let total = 0
  
  // 计算所有玩家的得分总和
  players.value.forEach(player => {
    const score = safeCalculate(player.currentScore)
    const finalScore = player.isWin ? score : -score
    total += finalScore
  })
  
  // 检查总和是否为0
  showScoreWarning.value = total !== 0
  canSubmit.value = total === 0
}

// 设置胜负状态
const setWinStatus = (index, isWin) => {
  players.value[index].isWin = isWin
  checkTotalScore()
}

// 设置当前操作的玩家
const setCurrentPlayer = (index) => {
  currentPlayerIndex.value = index
}

// 数字键盘输入逻辑
const inputNumber = (num) => {
  const player = players.value[currentPlayerIndex.value]
  if (player.currentScore === '0') {
    player.currentScore = num.toString()
  } else {
    player.currentScore += num.toString()
  }
  checkTotalScore()
}

const inputOperator = (op) => {
  const player = players.value[currentPlayerIndex.value]
  // 确保不会连续输入运算符
  const lastChar = player.currentScore.slice(-1)
  if (lastChar !== '+' && lastChar !== '-') {
    player.currentScore += op
    checkTotalScore()
  }
}

const deleteLast = () => {
  const player = players.value[currentPlayerIndex.value]
  if (player.currentScore.length > 1) {
    player.currentScore = player.currentScore.slice(0, -1)
  } else {
    player.currentScore = '0'
  }
  checkTotalScore()
}

const clearScore = () => {
  players.value[currentPlayerIndex.value].currentScore = '0'
  checkTotalScore()
}

// 计算合分 - 将输入的分数归零
const calculateTotalScore = (index) => {
  // 将当前玩家的输入分数归零
  players.value[index].currentScore = '0'
  
  // 显示提示信息
  uni.showToast({
    title: '分数已归零',
    icon: 'success',
    duration: 1000
  })
  
  // 重新检查总分
  checkTotalScore()
}

// 提交分数并跳转至结算页
const submitScore = () => {
  if (!canSubmit.value) {
    uni.showToast({
      title: '对局分数相加不为0,请检查！',
      icon: 'none'
    })
    return
  }
  
  // 计算每个玩家的最终得分
  const roundScores = players.value.map(player => {
    // 使用安全的方式计算表达式
    const scoreChange = safeCalculate(player.currentScore)
    
    // 根据胜负决定分数正负
    const finalScore = player.isWin ? scoreChange : -scoreChange
    
    return {
      playerId: player.id,
      score: finalScore
    }
  })
  
  // 获取现有的对局记录
  const existingRounds = uni.getStorageSync('gameRounds') || []
  
  if (isEditMode.value && editRoundIndex.value >= 0) {
    // 编辑模式：更新指定索引的对局记录
    existingRounds[editRoundIndex.value] = roundScores
    
    uni.showToast({
      title: '对局分数已更新',
      icon: 'success'
    })
  } else {
    // 新增模式：添加新的对局记录
    existingRounds.push(roundScores)
    
    uni.showToast({
      title: '对局分数已保存',
      icon: 'success'
    })
  }
  
  // 保存到本地存储
  uni.setStorageSync('gameRounds', existingRounds)
  
  // 添加短暂延迟，确保数据保存完成
  setTimeout(() => {
    // 返回房间页面
    uni.navigateBack({
      success: () => {
        console.log('返回房间页面，数据已更新')
      }
    })
  }, 500)
}

// 返回上一页
const goBack = () => {
  uni.navigateBack()
}
</script>

<style lang="less" scoped>
.scoring-page {
  background-color: #f5f5f5;
  min-height: 100vh;
}

.nav-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 30rpx;
  background-color: #41479b;
  color: #fff;

  .nav-back, .nav-actions {
    width: 60rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .nav-title {
    font-size: 32rpx;
    font-weight: 500;
    display: flex;
    flex-direction: column;
    align-items: center;
    
    text {
      font-size: 24rpx;
      margin-top: 5rpx;
    }
  }
}

.player-table {
  margin: 20rpx;
  background-color: #fff;
  border-radius: 12rpx;
  overflow: hidden;
}

.table-header {
  display: flex;
  justify-content: space-around;
  padding: 20rpx;
  background-color: #f8f8f8;
  border-bottom: 1rpx solid #eee;

  text {
    flex: 1;
    text-align: center;
    font-size: 28rpx;
    font-weight: 500;
  }
}

.table-row {
  display: flex;
  padding: 20rpx;
  border-bottom: 1rpx solid #eee;

  &:last-child {
    border-bottom: none;
  }

  .player-info {
    display: flex;
    align-items: center;
    flex: 1;

    .player-avatar {
      width: 60rpx;
      height: 60rpx;
      border-radius: 50%;
      margin-right: 10rpx;
    }

    .player-name {
      font-size: 28rpx;
      color: #000;
      margin-right: 10rpx;
    }

    .self-tag {
      background-color: #007aff;
      color: #fff;
      font-size: 20rpx;
      padding: 2rpx 8rpx;
      border-radius: 10rpx;
    }
  }

  .win-lose {
    display: flex;
    flex: 1;

    .win-btn, .lose-btn {
      flex: 1;
      height: 60rpx;
      line-height: 60rpx;
      border-radius: 8rpx;
      font-size: 28rpx;
      margin: 0 5rpx;
    }

    .win-btn {
      background-color: #fff;
      color: #007aff;
      border: 1rpx solid #007aff;
      
      &.active {
        background-color: #007aff;
        color: #fff;
        border: none;
      }
    }

    .lose-btn {
      background-color: #fff;
      color: #ff3b30;
      border: 1rpx solid #ff3b30;
      
      &.active {
        background-color: #ff3b30;
        color: #fff;
        border: none;
      }
    }
  }

  .score-input {
    flex: 1;
    display: flex;
    align-items: center;

    .score-text {
      width: 100rpx;
      height: 60rpx;
      border: 1rpx solid #eee;
      border-radius: 8rpx;
      text-align: center;
      font-size: 32rpx;
    }

    .sum-btn {
      margin-left: 10rpx;
      height: 60rpx;
      line-height: 60rpx;
      padding: 0 20rpx;
      background-color: #41479b;
      color: #fff;
      border-radius: 8rpx;
      font-size: 24rpx;
    }
  }
}

.score-warning {
  text-align: center;
  color: #ff3b30;
  font-size: 28rpx;
  margin: 20rpx;
  padding: 10rpx;
  background-color: #ffe6e6;
  border-radius: 8rpx;
}

.keypad {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 20rpx;

  .keypad-row {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20rpx;

    &:last-child {
      margin-bottom: 0;
    }
  }

  .keypad-btn {
    width: 120rpx;
    height: 120rpx;
    border-radius: 12rpx;
    background-color: #f8f8f8;
    font-size: 36rpx;
    font-weight: 500;
    
    &.submit-btn {
      background-color: #41479b;
      color: #fff;
      
      &.disabled {
        background-color: #ccc;
        color: #999;
      }
    }
    
    &.clear-btn {
      background-color: #ff3b30;
      color: #fff;
      font-size: 28rpx;
    }
  }
}
</style>