<script lang="ts" setup name="checkpointManage_stageManage">
import { deleteStage, getStageList, updateStage } from '#/api'
import XbTableClass from '#/utils/xbTable'

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

const xbTable = reactive(
  new XbTableClass(
    {
      column: column({ updateState, handleClick }),
      page: {
        size: 20,
        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 res = await getStageList({
    ...xbTable.table.page,
    date: null,
  })
  xbTable.table.page.total = res.totalRows
  xbTable.table.data = res.rows
}
async function updateState(row: anyObj) {
  row.loading = true
  try {
    let val = 0
    await updateStage({
      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: {
      showDia.value = true
      diaData.value = val
      diaTitle.value = '编辑'
      break
    }
    case 1: {
      deleteStage(val.id).then(() => {
        xbTable.table.page.current = 1
        init()
      })
      break
    }
  }
}

const showDia = 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'
})

onMounted(() => {
  init()
})
</script>

<template>
  <div class="page g-container">
    <Table ref="tableRef" class="page-table" :height="tableHeight">
      <template #neck>
        <div class="btn">
          <el-button type="primary" @click="handleAdd"> 新增 </el-button>
        </div>
      </template>
    </Table>
    <Dia
      v-model="showDia"
      :title="diaTitle"
      :dia-data="diaData"
      @on-refresh="handlePageCurrent({ current: 1 })"
    />
  </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>
