<script lang="ts" setup name="authManage_menuManage">
import {
  changeMenuStatus,
  deleteMenuRule,
  getMenu,
  updateMenuRule,
} from '#/api'
import XbTableClass from '#/utils/xbTable'

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

const filterData = ref({
  name: '',
  startTime: '',
  endTime: '',
})
const tableRef = ref()
const showDia = ref(false)
const diaTitle = ref('')
const diaData = ref({})
const xbTable = reactive(
  new XbTableClass({
    column: column({
      updateState,
      handleClick,
      updateKeepalive,
    }),
    page: {
      size: -1,
      current: 1,
      total: 0,
    },
    data: [],
  }),
)
provide('xbTable', xbTable)
async function getTableData() {
  xbTable.table.data = await getMenu()
}

async function updateState(row: anyObj) {
  row.loading = true
  try {
    let val = 0
    await changeMenuStatus({
      id: row.id,
      status: row.status === 0 ? (val = 1) : (val = 0),
    })
    row.status = val
  } catch {
    return false
  } finally {
    row.loading = false
  }
}

async function updateKeepalive(row: anyObj) {
  row.KLoading = true
  try {
    let val = 0
    await updateMenuRule({
      id: row.id,
      keepalive: row.keepalive === 0 ? (val = 1) : (val = 0),
    })
    row.keepalive = val
  } catch {
    return false
  } finally {
    row.KLoading = false
  }
}

function handleClick(type: Number, row: anyObj) {
  switch (type) {
    case 1: {
      showDia.value = true
      diaTitle.value = '编辑'
      diaData.value = row
      break
    }
    case 2: {
      deleteMenuRule(row.id).then(() => getTableData())
      break
    }
  }
}

function onFilterClick(type: string, value?: any) {
  switch (type) {
    case 'add': {
      showDia.value = true
      diaTitle.value = '新增'
      diaData.value = {}
      break
    }
    case 'refresh': {
      getTableData()
      break
    }
    case 'tableRows': {
      if (value) {
        xbTable.table.expandAll = true
      } else {
        xbTable.table.expandAll = false
        xbTable.foldAll()
      }
      break
    }
  }
}

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

onMounted(() => {
  xbTable.table.ref = tableRef.value
  getTableData()
  nextTick(() => {
    xbTable.dragSort()
  })
})
</script>

<template>
  <section class="page g-container">
    <Filter v-model="filterData" @handle-click="onFilterClick" />
    <Table
      ref="tableRef"
      class="page-table"
      :height="tableHeight"
      :pagination="false"
    />
    <Dia
      v-model:show-dia="showDia"
      :title="diaTitle"
      :dia-data="diaData"
      @on-refresh="getTableData"
    />
  </section>
</template>

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