<template>
  <view class="container">
    <view class="header">
      <view class="left">公告：开奖结果同步傲拾</view>
      <view class="right">
        <view class="btn" @click="toPage(2)">投注记录</view>
        <view class="btn" @click="toPage(1)">开奖记录</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',
            backgroundImage: `url(${item.optActive ? require('../../../static/dz.png') : 'none'})`,
          }"
          @click="handleClick(item)"
        >
          <text>{{ item.value }}</text>
          <!-- <image class="icon" v-show="item.optActive" 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">
      <text v-if="isKj">正在开奖中，已停止投注!!!</text>
      <text v-else>
        {{ Number(kjData.nowPeriods) + 1 || 0 }}期开奖还剩: {{ timeStr || '0分0秒' }}
      </text>
    </view>
    <view class="bet-opt">
      <view class="item" v-for="(item, index) in betOpts" :key="index" @click="handleBet(item)">
        {{ item }}豆子
      </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>({})

interface NumsType {
  ID: number
  name: string
  optActive?: boolean
  active?: boolean
  value?: string
  list?: number[]
}

const nums = ref<NumsType[]>([])

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

const betOpts = ref([100, 500, 1000, 2000, 3000, 5000])

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))

  nums.value = kjData.value.list.map((item) => ({
    optActive: false,
    active: false,
    value: item.name,
    ID: item.ID,
    list: item.list.split(/[,-.]/).map((item: string) => Number(item)),
  }))

  nums.value.forEach((item) => {
    item.list?.forEach((itm) => {
      if (itm === Number(kjData.value.drawNumber)) {
        item.active = true
      }
    })
  })
  timeId.value = setInterval(() => {
    countdownFn()
  }, 1000)
}

const timeStr = ref('')

const isKj = ref(false)

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) {
    clearInterval(timeId.value)
    setTimeout(() => {
      get_list()
      get_info()
    }, 3000)
  }
  isKj.value = m === 0 && s < 40 ? true : false
}

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: number) => {
  const newNums = nums.value.filter((item) => item.optActive === true)
  if (newNums.length === 0)
    return Taro.showToast({
      title: '请选择投注项',
      icon: 'none',
    })
  Taro.showModal({
    title: '确认投注吗？',
    content: `投注豆子：${item}`,
    success: async (res) => {
      if (res.confirm) {
        const game_info = Taro.getStorageSync('gameItem')
        const uid = Taro.getStorageSync('uid')
        const res = await turntable_bet({
          uid: uid,
          aid: nums.value.filter((item) => item.optActive === true)[0].ID,
          number: item,
          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>
