<template>
  <view class="container">
    <!-- 导航栏 -->
    <view class="navbar">
      <view class="navbar-left">
        <button class="back-button" @click="goBack">返回</button>
      </view>
      <view class="navbar-center">
        <text class="title">翻牌小游戏</text>
      </view>
      <view class="navbar-right"></view>
    </view>

    <!-- 用户信息 -->
    <view class="user-info">
      <view class="user-info-item">
        <text class="user-info-label">用户ID:</text>
        <text class="user-info-value">{{ userInfo.uid }}</text>
      </view>
      <view class="user-info-item">
        <text class="user-info-label">余额:</text>
        <text class="user-info-value">{{ userInfo.assets }}</text>
      </view>
    </view>

    <!-- 游戏板 -->
    <view class="game-board">
      <view class="card" :class="{ selected: card.selected, flipped: card.flipped }" v-for="(card, index) in cards" :key="index" @click="selectCard(index)">
        <image :src="card.image" mode="aspectFill"></image>
      </view>
    </view>

    <!-- 下注区域 -->
    <view class="bet-section">
      <view class="bet-options">
        <button :class="{ selected: betAmount === 5 }" @click="setBetAmount(5)">5货币</button>
        <button :class="{ selected: betAmount === 10 }" @click="setBetAmount(10)">10货币</button>
        <button :class="{ selected: betAmount === 15 }" @click="setBetAmount(15)">15货币</button>
        <button :class="{ selected: betAmount === 20 }" @click="setBetAmount(20)">20货币</button>
      </view>
      <button class="place-bet-button" @click="placeBet">下注</button>
      <button class="view-bet-history-button" @click="showBetHistory">查看下注记录</button>
    </view>
 <!-- 下注记录弹窗 -->
		<view class="lottery-description">
			<view class="description-box">
				<text class="description-title">游戏说明：<br></text>
				<text class="description-text" v-for="(item, index) in lotteryDescription"
					:key="index">{{ item }}<br></text>
			</view>
			</view>
    <!-- 下注记录弹窗 -->
    <view v-if="showHistoryModal" class="bet-history-modal">
      <view class="modal-content">
        <text class="bet-history-title">下注记录:</text>
		<view class="divider"></view>
        <view v-for="(bet, index) in paginatedBetHistory" :key="index" class="bet-history-item">
          <text>下注金额: {{ bet.amount }}元气</text><br>
          <text>下注日期: {{ bet.time }}</text><br>
          <text>是否中奖: {{ bet.is_winner ? '恭喜您中奖' : '抱歉~您没有中奖'}}</text><br>
          <text>开奖牌号是: {{ bet.winning_card }}号牌</text><br>
          <text>您下注牌号是: {{ bet.selected_card }}号牌</text><br>
          <view class="divider"></view>
        </view>
		
        <view class="pagination">
          <button @click="prevPage" :disabled="currentPage === 1">上一页</button>
          <text>{{ currentPage }} / {{ totalPages }}</text>
          <button @click="nextPage" :disabled="currentPage === totalPages">下一页</button>
        </view>
        <button class="close-button" @click="hideBetHistory">关闭</button>
      </view>
    </view>
  </view>
</template>

<script>
import { localStorage } from '../../js_sdk/mp-storage/mp-storage/index.js';

const STAR_URL = 'https://ye.lzchi.top/';
const API = {
	
  fpxyxgetLotteryDescriptio: function() {
    return STAR_URL + 'Plugins/sy_starpro/api.php?act=fpxyxgetLotteryDescriptio';
  },
  getUserInfo: function() {
    return STAR_URL + 'Plugins/sy_starpro/api.php?act=getUserInfo';
  },
  placeBet: function() {
    return STAR_URL + 'Plugins/sy_starpro/api.php?act=placeBet';
  },
  drawPrize: function() {
    return STAR_URL + 'Plugins/sy_starpro/api.php?act=drawPrize';
  },
  getBetHistory: function() {
    return STAR_URL + 'Plugins/sy_starpro/api.php?act=getBetHistory';
  },
};

export default {
  data() {
    return {
      userInfo: {
        uid: '',
        assets: 0,
      },
      betAmount: 0,
      cards: [
        { selected: false, flipped: false, image: '/static/fp/1.png', Card: 1 },
        { selected: false, flipped: false, image: '/static/fp/2.png', Card: 2 },
        { selected: false, flipped: false, image: '/static/fp/z.png', Card: 3 }
      ],
      betHistory: [],
      showHistoryModal: false,
      currentPage: 1,
      pageSize: 4, // 每页显示10条记录
      selectedCardIndex: null, 
	  lotteryDescription: []
    };
  },
		created() {
			this.fpxyxgetLotteryDescriptio();
		},
  computed: {
    paginatedBetHistory() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.betHistory.slice(start, end);
    },
    totalPages() {
      return Math.ceil(this.betHistory.length / this.pageSize);
    }
  },

  onLoad() {
    this.getUserInfo();
    this.getBetHistory();
  },

  methods: {
	  
	  fpxyxgetLotteryDescriptio() {
	  	const url = API.fpxyxgetLotteryDescriptio();
	  	uni.request({
	  		url: url,
	  		method: 'GET',
	  		success: (res) => {
	  			const data = res.data;
	  			console.log('Description API Response:', data);
	  			if (data.code === 200) {
	  				this.lotteryDescription = data.description;
	  			} else {
	  				alert(data.msg);
	  			}
	  		},
	  		fail: (err) => {
	  			console.error('Error fetching lottery description:', err);
	  			alert('获取抽奖说明失败，请重试');
	  		}
	  	});
	  },
	  
	  
    formatCustomDate(dateString) {
      const [month, day, hour, minute] = dateString.match(/\d+/g);
      const date = new Date();
      date.setMonth(parseInt(month) - 1);
      date.setDate(parseInt(day));
      date.setHours(parseInt(hour));
      date.setMinutes(parseInt(minute));
      date.setSeconds(0);
      date.setMilliseconds(0);
      return date.toLocaleString(); 
    },

    getUserInfo() {
      try {
        const uid = this.getUserUid();
        uni.request({
          url: `${API.getUserInfo()}&uid=${uid}`,
          method: 'GET',
          success: (res) => {
            if (res && res.data && res.data.code === 200) {
              this.userInfo = res.data.data;
            }
          },
          fail: (err) => {
            uni.showToast({
              title: '获取用户信息失败',
              icon: 'none'
            });
          }
        });
      } catch (error) {
        uni.showToast({
          title: '获取用户信息失败',
          icon: 'none'
        });
      }
    },

    setBetAmount(amount) {
      this.betAmount = amount;
    },

    placeBet() {
      try {
        const uid = this.getUserUid();
        const betAmount = this.betAmount;

        if (this.selectedCardIndex === null || this.selectedCardIndex === undefined) {
          uni.showToast({
            title: '请选择一张牌',
            icon: 'none'
          });
          return;
        }

        if (!uid || betAmount <= 0) {
          uni.showToast({
            title: '下注金额无效',
            icon: 'none'
          });
          return;
        }

        uni.request({
          url: `${API.placeBet()}&uid=${uid}&betAmount=${betAmount}&selectedCard=${this.selectedCardIndex}`,
          method: 'POST',
          success: (res) => {
            if (res && res.data && res.data.code === 200) {
              this.userInfo.assets = res.data.data.newAssets;
              this.getBetHistory();
              uni.showToast({
                title: '下注成功',
                icon: 'success'
              });

              // 翻开选择的牌
              const selectedCard = this.cards.find(card => card.Card === this.selectedCardIndex);
              if (selectedCard) {
                selectedCard.flipped = true;
                selectedCard.image = '/static/fp/3.png';
              }
            } else {
              uni.showToast({
                title: res && res.data ? res.data.msg : '未知错误',
                icon: 'none'
              });
            }
          },
          fail: (err) => {
            uni.showToast({
              title: '下注失败',
              icon: 'none'
            });
          }
        });
      } catch (error) {
        uni.showToast({
          title: '下注失败',
          icon: 'none'
        });
      }
    },

    getCardStatus() {
      const uid = this.getUserUid();
      uni.request({
        url: `${API.getCardStatus()}&uid=${uid}`,
        method: 'GET',
        success: (res) => {
          if (res && res.data && res.data.code === 200) {
            const cardStatus = res.data.data;
            this.cards.forEach((card, index) => {
              card.flipped = cardStatus[index].flipped;
            });
          }
        },
        fail: (err) => {
          uni.showToast({
            title: '获取卡牌状态失败',
            icon: 'none'
          });
        }
      });
    },

    drawPrize(uid) {
      uni.request({
        url: `${API.drawPrize()}&uid=${uid}`,
        method: 'GET',
        success: (res) => {
          if (res && res.data && res.data.code === 200) {
            this.userInfo.assets = res.data.data.newAssets;
            const prizeResults = res.data.data.prizeResults;
            prizeResults.forEach((result, index) => {
            });
            uni.showToast({
              title: '开奖成功',
              icon: 'success'
            });
          } else {
            uni.showToast({
              title: res && res.data ? res.data.msg : '未知错误',
              icon: 'none'
            });
          }
        },
        fail: (err) => {
          uni.showToast({
            title: '开奖失败',
            icon: 'none'
          });
        }
      });
    },

    getBetHistory() {
      try {
        const uid = this.getUserUid();
        uni.request({
          url: `${API.getBetHistory()}&uid=${uid}`,
          method: 'GET',
          success: (res) => {
            if (res && res.data && res.data.code === 200) {
              this.betHistory = res.data.data.map(bet => {
                return {
                  amount: bet.amount,
                  time: this.formatCustomDate(bet.time), // 使用自定义格式化方法
                  prize_amount: bet.prize_amount,
                  winning_card: bet.winning_card,
                  selected_card: bet.selected_card, // 新增显示下注的牌号
                  is_winner: bet.prize_amount > 0,
                };
              });
            } else {
              uni.showToast({
                title: res && res.data ? res.data.msg : '未知错误',
                icon: 'none'
              });
            }
          },
          fail: (err) => {
            uni.showToast({
              title: '获取下注记录失败',
              icon: 'none'
            });
          }
        });
      } catch (error) {
        uni.showToast({
          title: '获取下注记录失败',
          icon: 'none'
        });
      }
    },

    selectCard(index) {
      this.cards.forEach((card, i) => {
        if (i === index) {
          card.selected = true; // 确保选择的卡牌被选中
          this.selectedCardIndex = card.Card; // 更新选择的卡牌索引
        } else {
          card.selected = false; // 取消其他卡牌的选择
        }
      });
    },

    getUserUid() {
      const userInfo = JSON.parse(localStorage.getItem('userinfo'));
      if (userInfo && userInfo.uid) {
        return userInfo.uid;
      } else {
        throw new Error('用户UID未找到');
      }
    },

    goBack() {
      uni.navigateBack({
        delta: 1
      });
    },

    showBetHistory() {
      this.showHistoryModal = true;
    },

    hideBetHistory() {
      this.showHistoryModal = false;
    },

    prevPage() {
      if (this.currentPage > 1) {
        this.currentPage--;
      }
    },

    nextPage() {
      if (this.currentPage < this.totalPages) {
        this.currentPage++;
      }
    }
  }
};
</script>

<style>
/* 全局样式 */
body {
  background: linear-gradient(135deg, #ffd1dc, #ffb6c1);
  font-family: 'Arial', sans-serif;
  color: #333;
  margin: 0;
  padding: 0;
  height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.container {
  padding: 10px;
  width: 100%;
  max-width: 400px;
  box-sizing: border-box;
}

/* 导航栏样式 */
.navbar {
  width: 100%;
  height: 50px;
  background: linear-gradient(45deg, #ff6f61, #ff9500); 
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 5px;
  border-radius: 10px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2); 
  margin-bottom: 10px;
}

.navbar-left, .navbar-right {
  flex: 1;
}

.navbar-center {
  flex: 2;
  text-align: center;
}

.navbar .title {
  font-size: 20px;
  color: #fff;
  font-weight: bold;
}

.navbar .back-button {
  background: none;
  border: none;
  color: #fff;
  font-size: 14px;
  cursor: pointer;
}

/* 用户信息样式 */
.user-info {
  display: flex;
  justify-content: space-between;
  width: 100%;
  height: 40px; 
  margin-bottom: 10px;
  background: #fff;
  padding: 10px;
  border-radius: 10px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); 
}

.user-info-label {
  font-size: 14px;
  color: #555;
}

.user-info-value {
  font-size: 16px;
  color: #ff6f61;
  font-weight: bold;
}

/* 游戏板样式 */
.game-board {
  display: flex;
  justify-content: space-around;
  width: 100%;
  margin-bottom: 10px;
}

.card {
  width: 80px;
  height: 120px;
  border: 2px solid #ccc;
  border-radius: 10px;
  overflow: hidden;
  transition: border-color 0.3s ease;
  background: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); 
}

.card.selected {
  border: 3px solid #ff6f61;
}

.card image {
  width: 100%;
  height: 100%;
}

/* 下注区域样式 */
.bet-section {
  width: 100%;
}

.bet-options {
  display: flex;
  justify-content: space-around;
  margin-bottom: 10px;
}

.bet-options button {
  padding: 8px 12px;
  font-size: 14px;
  color: #fff;
  background: #007aff;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.bet-options button:hover {
  background: #005bb5;
}

.bet-options button.selected {
  background: #ff9500; 
}

.place-bet-button {
  padding: 8px 16px;
  font-size: 16px;
  color: #fff;
  background: linear-gradient(45deg, #ff6f61, #ff9500); 
  border: none;
  border-radius: 10px;
  cursor: pointer;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2); 
  transition: background 0.3s ease, transform 0.3s ease;
  margin-bottom: 10px;
  width: 100%;
}

.place-bet-button:hover {
  background: linear-gradient(45deg, #ff9500, #ff6f61); 
  transform: translateY(-2px); 
}

.view-bet-history-button {
  padding: 8px 16px;
  font-size: 16px;
  color: #fff;
  background: linear-gradient(45deg, #007aff, #005bb5); 
  border: none;
  border-radius: 10px;
  cursor: pointer;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2); 
  transition: background 0.3s ease, transform 0.3s ease;
  margin-bottom: 10px;
  width: 100%;
}

.view-bet-history-button:hover {
  background: linear-gradient(45deg, #005bb5, #007aff); 
  transform: translateY(-2px); 
}

/* 下注记录弹窗样式 */
.bet-history-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background: #fff;
  padding: 15px;
  border-radius: 10px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
  width: 90%;
  max-width: 350px;
  position: relative;
}

.bet-history-title {
  font-size: 16px;
  color: #555;
  margin-bottom: 10px;
}

.bet-history-item {
  margin-bottom: 10px;
}

.divider {
  height: 1px;
  background: #ccc;
  margin: 5px 0;
}

.close-button {
  position: absolute;
  top: 5px;
  right: 10px;
  background: none;
  border: none;
  font-size: 18px;
  color: #555;
  cursor: pointer;
}

.close-button:hover {
  color: #ff6f61;
}

/* 分页样式 */
.pagination {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
}

.pagination button {
  padding: 5px 10px;
  font-size: 12px;
  color: #fff;
  background: #007aff;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.pagination button:hover {
  background: #005bb5;
}

.pagination button:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.pagination text {
  font-size: 14px;
  color: #555;
}

/* 游戏说明样式 */
.lottery-description {
  margin-top: 30px;
  width: 100%;
  max-width: 800px;
}

.description-box {
  background-color: #f9f9f9;
  border: 1px solid #e0e0e0;
  border-radius: 10px;
  padding: 20px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
}

.description-title {
  font-size: 18px;
  color: #333;
  font-weight: bold;
  margin-bottom: 10px;
}

.description-text {
  font-size: 16px;
  color: #555;
  line-height: 1.5;
}

/* 媒体查询，适配不同屏幕尺寸 */
@media (max-width: 600px) {
  .container {
    max-width: 100%;
  }

  .navbar {
    height: 40px;
  }

  .navbar .title {
    font-size: 16px;
  }

  .navbar .back-button {
    font-size: 12px;
  }

  .user-info {
    height: 30px;
    padding: 5px;
  }

  .user-info-label, .user-info-value {
    font-size: 12px;
  }

  .card {
    width: 60px;
    height: 90px;
  }

  .bet-options button {
    padding: 6px 10px;
    font-size: 12px;
  }

  .place-bet-button, .view-bet-history-button {
    padding: 6px 12px;
    font-size: 14px;
  }

  .modal-content {
    max-width: 90%;
  }

  .bet-history-title {
    font-size: 14px;
  }

  .bet-history-item {
    font-size: 12px;
  }

  .pagination button {
    padding: 4px 8px;
    font-size: 10px;
  }

  .pagination text {
    font-size: 12px;
  }

  .description-title {
    font-size: 16px;
  }

  .description-text {
    font-size: 14px;
  }
}

@media (min-width: 601px) and (max-width: 1024px) {
  .container {
    max-width: 600px;
  }

  .navbar {
    height: 45px;
  }

  .navbar .title {
    font-size: 18px;
  }

  .navbar .back-button {
    font-size: 14px;
  }

  .user-info {
    height: 35px;
    padding: 8px;
  }

  .user-info-label, .user-info-value {
    font-size: 14px;
  }

  .card {
    width: 70px;
    height: 105px;
  }

  .bet-options button {
    padding: 7px 11px;
    font-size: 13px;
  }

  .place-bet-button, .view-bet-history-button {
    padding: 7px 14px;
    font-size: 15px;
  }

  .modal-content {
    max-width: 70%;
  }

  .bet-history-title {
    font-size: 15px;
  }

  .bet-history-item {
    font-size: 13px;
  }

  .pagination button {
    padding: 5px 9px;
    font-size: 11px;
  }

  .pagination text {
    font-size: 13px;
  }

  .description-title {
    font-size: 17px;
  }

  .description-text {
    font-size: 15px;
  }
}
</style>