<template>
  <view class="container">
    <view class="header">
      <view class="left">公告：开奖结果同步傲拾</view>
      <view class="right">
        <view class="btn" @click="toPage(1)">投注记录</view>
        <view class="btn" @click="toPage(2)">开奖记录</view>
      </view>
    </view>
    <view class="user-info">
      <view class="left">
        <view class="avatar">
          <image :src="userInfo.avatarUrl || require('../../../static/tx.png')" />
        </view>
        <view class="info">
          <view class="name">{{ userInfo.nickName || '用户' }}</view>
          <view class="level">积分: {{ userInfo.integral || 0 }}</view>
        </view>
      </view>
      <view class="right">豆子：{{ userInfo.pulse || 0 }}</view>
    </view>
    <view class="turntable">
      <view class="num-box">
        <view
          class="item"
          v-for="(item, index) in nums"
          :key="index"
          :style="{
            color: item.active ? '#ff0000' : '#000',
          }"
          @click="handleClick(item)"
        >
          <text>{{ item.value }}</text>
          <image v-show="item.optActive" class="icon" src="../../../static/dz.png" />
        </view>
      </view>
    </view>
    <view class="kj-box">
      <view class="title">
        第
        <text class="num">{{ kjData.nowPeriods || 0 }}</text>
        期已开奖:
      </view>
      <view class="title-sub">
        <view class="item" v-for="(item, index) in kjNums" :key="index">
          {{ item }}
        </view>
      </view>
    </view>
    <view class="countdown">
      {{ Number(kjData.nowPeriods) + 1 || 0 }}期开奖还剩: {{ timeStr || '0分0秒' }}
    </view>
    <view class="bet-opt">
      <view class="item" v-for="(item, index) in betOpts" :key="index" @click="handleBet(item)">
        {{ item.max }}豆子
      </view>
    </view>
    <view class="rule-box" @click="handleRule">| 游戏规则 |</view>
  </view>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { get_turntable_list, get_user_info, turntable_bet } from '@/api'
import Taro from '@tarojs/taro'
import * as dayjs from 'dayjs'

const userInfo = ref<any>({})

const nums = ref([
  {
    optActive: false,
    active: false,
    value: 1,
  },
  {
    optActive: false,
    active: false,
    value: 2,
  },
  {
    optActive: false,
    active: false,
    value: 4,
  },
  {
    optActive: false,
    active: false,
    value: 3,
  },
])

const kjNums = ref([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

interface BetOpts {
  ID?: number
  max?: number
  odds?: number
}

const betOpts = ref<BetOpts[]>([])

Taro.useDidShow(() => {
  get_info()
  get_list()
})

const kjData = ref<any>({})

const timeId = ref<NodeJS.Timeout>()

const get_list = async () => {
  const res = await get_turntable_list()
  kjData.value = res.data || {}
  kjNums.value = kjData.value.nowDraw.split(',').map((item) => Number(item))

  betOpts.value = kjData.value.list

  nums.value.forEach((item) => {
    if (item.value === kjData.value.drawNumber) {
      item.active = true
    } else {
      item.active = false
    }
  })
  timeId.value = setInterval(() => {
    countdownFn()
  }, 1000)
}

const timeStr = ref('')

const countdownFn = () => {
  const currentTimestamp = dayjs().valueOf()
  const timeLeft = kjData.value.drawTime * 1000 - currentTimestamp
  timeStr.value = dayjs(timeLeft).format('mm分ss秒')

  const m = Number(dayjs(timeLeft).format('mm'))
  const s = Number(dayjs(timeLeft).format('ss'))

  if (m === 0 && s === 0) {
    console.log('结束')
    clearInterval(timeId.value)
    get_list()
    get_info()
  }
}

const get_info = async () => {
  const res = await get_user_info(Taro.getStorageSync('uid'))
  userInfo.value = res.data.data || {}
}

const handleClick = (itemOpt) => {
  nums.value.forEach((item) => {
    item.optActive = false
  })
  itemOpt.optActive = true
}

const handleBet = (item: BetOpts) => {
  const newNums = nums.value.filter((item) => item.optActive === true)
  if (newNums.length === 0)
    return Taro.showToast({
      title: '请选择投注项',
      icon: 'none',
    })
  Taro.showModal({
    title: '确认投注吗？',
    content: `投注豆子：${item.max}`,
    success: async (res) => {
      if (res.confirm) {
        const game_info = Taro.getStorageSync('gameItem')
        const uid = Taro.getStorageSync('uid')
        const res = await turntable_bet({
          uid: uid,
          number: nums.value.filter((item) => item.optActive === true)[0].value,
          aid: item.ID,
          game_id: game_info.ID,
        })
        Taro.showToast({
          title: res.msg,
          icon: 'none',
        })
        setTimeout(() => {
          get_info()
        }, 2000)
      }
    },
  })
}

const handleRule = () => {
  Taro.showToast({
    title: '暂无规则',
    icon: 'none',
  })
}

// 前往开奖和投注记录
const toPage = (type: number) => {
  Taro.navigateTo({
    url: `/pages/aoshi/records/index?type=${type}`,
  })
}
</script>

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