<template>
  <CommonPage show-footer :title="$route.title">
    <div flex items-center justify-between>
      <div mr-20 flex>
        <div>游戏状态：</div>
        <n-switch
          v-model:value="val1"
          :checked-value="1"
          :unchecked-value="2"
          @update:value="handleUpdateValue1"
        />
      </div>
      <div flex items-center>
        <div ml-20 flex items-center>
          <div>开奖记录：</div>
          <n-button type="primary" @click="openData">预览</n-button>
        </div>
        <div ml-20 flex items-center>
          <div>本局记录：</div>
          <n-button type="primary" @click="openJl(1)">预览</n-button>
        </div>
        <div ml-20 flex items-center>
          <div>全部记录：</div>
          <n-button type="primary" @click="openJl(2)">预览</n-button>
        </div>
      </div>
    </div>

    <div flex>
      <div>
        预开期数：
        <span text-25>{{ list[0]?.Periods || 0 }}</span>
      </div>
      <div ml-20>
        剩余开奖时间：
        <span text-25>{{ time || 0 }}</span>
      </div>
      <div ml-20>
        本局总下注：
        <span text-25>{{ totalA || 0 }}</span>
      </div>
    </div>

    <div>
      <div>
        第
        <span text-25>{{ data[0]?.Periods || 0 }}</span>
        期开奖结果：
        <span text-20>{{ data[0]?.Name || 0 }}</span>
      </div>
    </div>

    <n-spin size="large" :show="show">
      <div flex flex-wrap justify-between>
        <n-card
          v-for="item in list"
          :key="item.ID"
          class="mb-10 mt-10 h-120 w-250 flex-shrink-0 cursor-pointer"
          :title="item.name"
        >
          <p text-25 op-60 :style="{ color: item.count === 0 ? 'green' : 'red' }">
            {{ item.count }}
          </p>
        </n-card>
        <div h-0 w-250></div>
        <div h-0 w-250></div>
      </div>
    </n-spin>
    <n-spin size="large" :show="show1">
      <div flex flex-wrap justify-between>
        <n-card
          v-for="item in list1"
          :key="item.ID"
          class="mb-10 mt-10 h-150 w-250 flex-shrink-0 cursor-pointer"
          :title="`${item.NumName}(${item.Name})`"
        >
          <p text-25 op-60 :style="{ color: item.Total === 0 ? 'green' : 'red' }">
            {{ item.Total }}
          </p>
          <n-popconfirm @positive-click="handleUpdateValue(item.ID)">
            <template #trigger>
              <n-button>你猜</n-button>
            </template>
            一切都将一去杳然，任何人都无法将其捕获。
          </n-popconfirm>
        </n-card>
        <div h-0 w-250></div>
        <div h-0 w-250></div>
        <div h-0 w-250></div>
        <div h-0 w-250></div>
      </div>
    </n-spin>
    <!-- 开奖记录 -->
    <n-modal v-model:show="showModal">
      <n-card
        style="width: 900px"
        title="开奖记录"
        :bordered="false"
        size="huge"
        role="dialog"
        aria-modal="true"
      >
        <n-data-table
          :loading="loading"
          :columns="columns"
          :data="data"
          :max-height="600"
          :pagination="false"
          :bordered="false"
          remote
        />
      </n-card>
    </n-modal>
    <!-- 游戏记录 -->
    <n-modal v-model:show="jlModal">
      <n-card
        style="width: 900px"
        :title="jlTitle"
        :bordered="false"
        size="huge"
        role="dialog"
        aria-modal="true"
      >
        <div>
          <span>
            总投注(豆子):
            <span text-red>{{ jlData.total_number }}</span>
          </span>
          <span ml-20>
            总积分:
            <span text-red>{{ jlData.total_integral }}</span>
          </span>
        </div>
        <n-data-table
          :loading="jlLoading"
          :columns="jlColumns"
          :data="jlData.data"
          :max-height="600"
          :pagination="false"
          :bordered="false"
          remote
          @update:sorter="handleSorterChange"
        />
      </n-card>
    </n-modal>
  </CommonPage>
</template>

<script setup>
import { h } from 'vue'
import api from '../../api'
import { getToken } from '@/utils'

const ws = new WebSocket(`wss://${import.meta.env.VITE_WS_URL}`)

const ws1 = new WebSocket(`wss://${import.meta.env.VITE_WS1_URL}`)

const list = ref([])
const list1 = ref([])

const val1 = ref(null)
// const val = ref(null)

const time = ref(null)

watch(time, (val) => {
  if (Number(val) === 0) {
    setTimeout(() => {
      get_kj_jl()
    }, 2500)
  }
})

const show = ref(true)
const show1 = ref(true)

ws.onopen = () => {
  console.log('1连接成功')
  setInterval(() => {
    ws.send('ping')
  }, 2500)
}

const totalA = ref(null)

ws.onmessage = (msg) => {
  const res = JSON.parse(msg.data)
  list.value = res.betting.sort((a, b) => b.Total - a.Total)
  show.value = false
  list1.value = res.list.sort((a, b) => b.Total - a.Total)
  show1.value = false
  totalA.value = res.total
}

ws1.onopen = () => {
  console.log('2连接成功')
  setInterval(() => {
    ws.send('ping')
  }, 2500)
}

ws1.onmessage = (msg) => {
  const res = JSON.parse(msg.data)
  switch (res.code) {
    case 200:
      // let num = res.data
      time.value = res.data
      break
    case 301:
      $message.error(res.msg)
      break
  }
}

onMounted(() => {
  // get_data()
  get_data1()
  get_kj_jl()
})

// const get_data = async () => {
//   const res = await api.getDS()
//   val.value = res.data.diceStatus
// }
const get_data1 = async () => {
  const res = await api.getData()
  val1.value = res.data.diceStart
}

onBeforeUnmount(() => {
  ws.close()
})

const handleUpdateValue = async (e) => {
  const res = await api.setDS({
    status: 1,
    id: e,
    user_id: getToken(),
    Periods: list.value[0]?.Periods,
  })
  $message.success(res.msg)
  // get_data()
}

const handleUpdateValue1 = async (e) => {
  const res = await api.setStatus({
    start: e,
  })
  $message.success(res.msg)
  get_data1()
}

const showModal = ref(false)
const loading = ref(false)
const columns = ref([
  {
    title: '期数',
    key: 'Periods',
    align: 'center',
  },
  {
    title: '开奖号码',
    key: 'Name',
    align: 'center',
  },
  {
    title: '开奖时间',
    key: 'DrawTime',
    align: 'center',
  },
  {
    title: '开奖号码',
    slot: 'Num',
    align: 'center',
    render: (row) => {
      return h('p', `${row.Start}-${row.End}`)
    },
  },
])
const data = ref([])
const openData = () => {
  showModal.value = true
  get_kj_jl()
}
const get_kj_jl = async () => {
  try {
    loading.value = true
    const res = await api.getKJList()
    console.log(res)
    data.value = res.data.data
    loading.value = false
  } catch (error) {
    $message.error(error.msg)
    throw error
  }
}

const jlModal = ref(false)
const jlTitle = ref('')

const jlData = ref({})

const jlColumns = ref([
  {
    title: '昵称',
    key: 'User',
    align: 'center',
  },
  {
    title: '电话',
    key: 'Phone',
    align: 'center',
  },
  {
    title: '期数',
    key: 'Periods',
    align: 'center',
  },
  {
    title: '下注豆子',
    key: 'TotalCount',
    align: 'center',
    sorter: true,
    sortOrder: false,
  },
  {
    title: '赢积分',
    key: 'NumberSum',
    align: 'center',
    sorter: true,
    sortOrder: false,
  },
  {
    title: '购买号码',
    key: 'PeriodsNum',
    align: 'center',
  },
  {
    title: '时间',
    key: 'DrawTime',
    align: 'center',
  },
])

const jlLoading = ref(false)

const openJl = async (e) => {
  try {
    jlModal.value = true
    jlTitle.value = e === 1 ? '本局游戏记录' : '全部游戏记录'
    jlLoading.value = true
    const res = e === 1 ? await api.nowUser() : await api.allUser()
    jlData.value = res.data
  } catch (error) {
    $message.error(error.msg)
  }
  jlLoading.value = false
}

const handleSorterChange = (sorter) => {
  if (!jlLoading.value) {
    jlLoading.value = true
    switch (sorter.columnKey) {
      case 'TotalCount':
        jlColumns.value[3].sortOrder = !sorter ? false : sorter.order
        jlData.value.data = jlData.value.data.sort((a, b) => {
          if (sorter.order === 'descend') return b.TotalCount - a.TotalCount
          return a.TotalCount - b.TotalCount
        })
        break
      case 'NumberSum':
        jlColumns.value[4].sortOrder = !sorter ? false : sorter.order
        jlData.value.data = jlData.value.data.sort((a, b) => {
          if (sorter.order === 'descend') return b.NumberSum - a.NumberSum
          return a.NumberSum - b.NumberSum
        })
        break
    }
    jlLoading.value = false
  }
}
</script>

<style lang="scss" scoped></style>
