<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 class="level">积分: {{ `${jfStr}w` || 0 }}</view>
                </view>
            </view>
            <view class="right">
                <view class="image"></view>
                <!-- <text>{{ dzStr || 0 }}w</text> -->
                <text>{{ userInfo.pulse || 0 }}</text>
            </view>
            <!-- <view class="game_btn" @click="handleRule">游戏规则</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="turntable">
            <view class="num-box">
                <view
                    class="item"
                    v-for="(item, index) in nums"
                    :key="index"
                    :style="{
                        color: item.active ? '#ff0000' : '#833E16',
                        backgroundColor: item.optActive ? '#FBEDBC' : '#ffeeee',
                    }"
                    @click="handleClick(item)"
                >
                    <text>{{ item.value }}</text>
                </view>
            </view>
            <view class="bet-btn" @click="handleBet">
                <view>点击</view>
                <view>投注</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"
                :style="{
                    backgroundColor: item.isActive ? '#FBDD36' : '#fbedbc',
                }"
                @click="handleBetOpt(item)"
            >
                {{ item.value }}豆子
            </view>
        </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([
    {
        isActive: false,
        value: 100,
    },
    {
        isActive: false,
        value: 500,
    },
    {
        isActive: false,
        value: 1000,
    },
    {
        isActive: false,
        value: 2000,
    },
    {
        isActive: false,
        value: 3000,
    },
    {
        isActive: false,
        value: 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 offColorChange = ref(false)

const time_i = ref<NodeJS.Timeout>()

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

    isKj.value = m === 0 && s < 40 ? true : false

    if (m === 0 && s < 40 && !offColorChange.value) {
        startColorFn()
    }

    if (m === 0 && s === 0) {
        clearInterval(timeId.value)
        clearInterval(time_i.value)
        offColorChange.value = true
        setTimeout(() => {
            get_list()
            get_info()
        }, 3000)
    }
}

const startColorFn = () => {
    nums.value.forEach((item) => {
        item.active = false
    })

    // 随机选中一个
    const randomNum = Math.floor(Math.random() * nums.value.length)
    nums.value[randomNum].active = true
}
const dzStr = ref('')
const jfStr = ref('')

const get_info = async () => {
    const res = await get_user_info(Taro.getStorageSync('uid'))

    userInfo.value = res.data.data || {}

    dzStr.value = String((userInfo.value.pulse / 10000).toFixed(2))
    jfStr.value = String((userInfo.value.integral / 10000).toFixed(2))
}

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

const handleBetOpt = (item) => {
    betOpts.value.forEach((item) => {
        item.isActive = false
    })
    item.isActive = true
}

const handleBet = () => {
    const newNums = nums.value.filter((item) => item.optActive === true)
    if (newNums.length === 0)
        return Taro.showToast({
            title: '请选择投注项',
            icon: 'none',
        })
    const item = betOpts.value.filter((item) => item.isActive === true)
    if (item.length === 0)
        return Taro.showToast({
            title: '请选择投注豆子',
            icon: 'none',
        })
    Taro.showModal({
        title: '确认投注吗？',
        content: `投注豆子：${item[0].value}`,
        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[0].value,
                    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>
