<script lang="ts" setup>
import type { ACTION_TYPE } from '#/components/Filter'

import { deleteLevel, getLevelListApi, getStageList, updateLevel } from '#/api'
import hud from '#/utils/hud.js'
import XbTableClass from '#/utils/xbTable'

import AddLevel from './AddLevel.vue'
import column from './column.jsx'
import Dia from './Dia.vue'

const xbTable = reactive(
  new XbTableClass(
    {
      column: column({ updateState, handleClick }),
      page: {
        size: 50,
        current: 1,
        total: 0,
      },
      data: [],
    },
    {
      handlePageSize,
      handlePageCurrent,
    },
  ),
)
provide('xbTable', xbTable)
// 分页处理
function handlePageSize({ size }: { size: number }) {
  xbTable.table.page.size = size
  init()
}
function handlePageCurrent({ current }: { current: number }) {
  xbTable.table.page.current = current
  init()
}
async function init() {
  const data = await getLevelListApi({
    ...xbTable.table.page,
    ...filterData.value,
    date: null,
  })
  xbTable.table.page.total = data.totalRows
  xbTable.table.data = data.rows
}
async function updateState(row: anyObj) {
  row.loading = true
  try {
    let val = 0
    await updateLevel({
      id: row.id,
      status: row.status === 0 ? (val = 1) : (val = 0),
    })
    row.status = val
  } catch {
    return false
  } finally {
    row.loading = false
  }
}
function handleClick(val: anyObj, type = 0) {
  switch (type) {
    case 0: {
      showWordDia.value = true
      diaData.value = val
      diaTitle.value = `编辑第${val.levelNum}关`
      break
    }
    case 1: {
      deleteLevel(val.id).then(() => {
        xbTable.table.page.current = 1
        init()
      })
      break
    }
  }
}

const showDia = ref(false)
const showWordDia = ref(false)
const diaTitle = ref('新增关卡')
const diaData = ref<anyObj>({})
function handleAdd() {
  showDia.value = true
  diaData.value = {}
  diaTitle.value = '新增关卡'
}

const tableRef = ref()
const tableHeight = computed(() => {
  if (tableRef.value && tableRef.value.getBox) {
    const { top, pageHeight } = tableRef.value!.getBox()
    return `${window.innerHeight - top - pageHeight}px`
  }
  return '600px'
})

// 筛选功能
const filterData = ref({
  stageId: '',
})
const config = computed(() => {
  return [
    {
      comName: 'el-select',
      label: '阶段',
      prop: 'stageId',
      clearable: true,
      options: stageListOptions.value,
      selectConfig: {
        label: 'name',
        value: 'id',
      },
    },
  ]
})
// 过滤
const handleFilterData = (type: ACTION_TYPE) => {
  switch (type.value) {
    case 'reset': {
      xbTable.table.page.current = 1
      init()
      break
    }
    case 'search': {
      init()
      break
    }
  }
}
const stageListOptions = ref([] as any[])

function openDetail(val: any) {
  diaData.value = val
  diaTitle.value = `编辑第${val.levelNum}关`
  showWordDia.value = true
  handlePageCurrent({ current: Number(xbTable.table.page.current) })
}

function check() {
  hud.toastLoad({
    task: async () => {
      let exit = false
      for (const stage of stageListOptions.value) {
        if (exit) {
          break
        }
        const res = await getLevelListApi({
          stageId: stage.id,
          size: 1000,
          current: 1,
        })
        for (let i = 0; i < res.totalRows; i++) {
          if (res.rows[i].wordList?.length !== 4) {
            hud.alert(`${stage.name} - 第${i + 1}关的单词数不是4个`)
            exit = true
            break
          }
        }
      }
      if (!exit) {
        hud.success('所有检查没问题')
      }
    },
    option: '检查',
  })
}

onMounted(() => {
  init()
  // TODO 临时改为1000
  getStageList({ current: 1, size: 300, status: 0 }).then((res) => {
    stageListOptions.value = res.rows
  })
  document.addEventListener('visibilitychange', (_) => {
    if (document.visibilityState === 'visible') {
      handlePageCurrent({ current: Number(xbTable.table.page.current) })
    }
  })
})
onActivated(() => {
  handlePageCurrent({ current: Number(xbTable.table.page.current) })
})
</script>

<template>
  <div class="page g-container">
    <Filter
      v-model="filterData"
      :config="config"
      @handle-action="handleFilterData"
    />
    <Table ref="tableRef" class="page-table" :height="tableHeight">
      <template #neck>
        <div class="btn">
          <el-button type="primary" @click="handleAdd"> 新增 </el-button>
          <el-button type="primary" @click="check"> 检查 </el-button>
        </div>
      </template>
    </Table>
    <AddLevel
      v-model="showDia"
      :title="diaTitle"
      :dia-data="diaData"
      :stage-list="stageListOptions"
      @on-refresh="openDetail"
    />
    <Dia
      v-model="showWordDia"
      :title="diaTitle"
      :dia-data="diaData"
      @on-refresh="
        handlePageCurrent({ current: Number(xbTable.table.page.current) })
      "
    />
  </div>
</template>

<style lang="scss" scoped>
@include xbj_table;
@include cell_user;

.page {
  .btn {
    margin-bottom: $box-mt;

    .el-button {
      padding: 6px 8px;
    }

    .icon-add {
      margin-right: 6px;
    }
  }
}
</style>
<style lang="scss">
.texts {
  color: red;
  text-decoration: none;
}

.wordImgPopover {
  position: fixed !important;
  inset: 0 50% 0 0 !important;

  .image-grid {
    display: grid;
    grid-template-rows: repeat(2, 1fr);
    grid-template-columns: repeat(2, 1fr);
    gap: 4px;
    width: 100%;
    height: 100%;

    .box-card {
      box-sizing: border-box;
      width: 100%;
      height: 100%;
    }

    .el-card__body {
      box-sizing: border-box;
      display: flex;
      flex-direction: column;
      width: 100%;
      height: 100%;
    }

    .img {
      display: flex;
      flex: 1;
      align-items: center;
      justify-content: center;
      max-height: 317px;
      overflow: hidden;

      .el-image {
        width: 100%;
        height: 100%;
      }

      .image-slot {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 100%;
        height: 100%;
        font-size: 30px;
        color: var(--el-text-color-secondary);
        background: var(--el-fill-color-light);
      }
    }

    .footer {
      box-sizing: border-box;
      flex-shrink: 0;
      margin-top: 20px;
      font-size: 24px;
      text-align: center;
    }
  }
}
</style>
