<!--
 * @Author: xiejiang
 * @Date: 2024-11-11 09:38:40
 * @LastEditors: xiejiang
 * @LastEditTime: 2024-12-11 23:13:08
 * @Description: 菜单管理
 * Copyright（c）2024 by 好老师教育科技有限公司 All right Reserved.
-->
<template>
  <div class="h-full overflow-auto">
    <t-tabs class="!px-[16px]" v-model="tabValue" :on-change="onTabChange">
      <t-tab-panel :value="0" label="平台菜单" :destroy-on-hide="false" />
      <t-tab-panel :value="1" :disabled="true" label="机构菜单" :destroy-on-hide="false" />
    </t-tabs>

    <PageContainer
      row-key="menuId"
      :filter-conditions="filterConditions"
      :table-data="tableData"
      :columns="columns"
      :loading="loading"
      :pagination="pagination"
      :show-tree="true"
      @on-search="onSearch"
      @search-change="handleSearch"
      @page-change="handlePage"
      @clear="handleClear(true)"
      table-maxheight="550px"
      class="max-h-[calc(100%-50px)]"
    >
      <template #header-left>
        <SearchWithButton
          :loading="loading"
          placeholder="搜索菜单名称"
          v-model="condMenuName"
          @clear="handleClear(null)"
          @on-search="handleSearch(searchParams)"
      /></template>
      <template #header-right>
        <div class="flex items-center justify-end gap-2">
          <t-button variant="outline" @click="handleLog">
            <template #icon><RootListIcon /></template>操作日志</t-button
          >
          <t-button variant="outline" @click="handleSort">
            <template #icon><UnfoldMoreIcon /></template>菜单排序</t-button
          >
          <t-button theme="primary" @click="handleEdit(null)">
            <template #icon><AddIcon /></template>
            新增菜单</t-button
          >
        </div>
      </template>

      <!-- 表格操作列插槽，#colKey必须对应operation -->
      <template #menuStatus="{ row }">
        <div class="flex items-center gap-2">
          <div class="w-[6px] h-[6px] rounded-full" :class="row.menuStatus == 1 ? 'bg-success' : 'bg-danger'" />
          {{ row.menuStatus == 1 ? '启用' : '停用' }}
        </div>
      </template>
      <template #operation="{ row }">
        <div class="flex items-center">
          <operate-btn v-if="row.status != 2" content="启用" @click="handleStatus(row, 2)"> </operate-btn>
          <operate-btn content="编辑" @click="handleEdit(row)"> </operate-btn>
          <operate-btn v-if="row.status == 2" content="停用" @click="handleStatus(row, 1)"> </operate-btn>
          <operate-btn v-if="row.status != 2" content="删除" @click="handleDel(row)"></operate-btn>
        </div>
      </template>
    </PageContainer>

    <!-- 新增编辑菜单 -->
    <MenuEdit :tab-type="tabValue" ref="menuEditRef" @success="handleSearch(searchParams)" />

    <!-- 操作日志 -->
    <MenuLog ref="menuLogRef" />

    <!-- 菜单排序 -->
    <MenuSort ref="menuSortRef" />
  </div>
</template>

<script setup lang="tsx">
import { PrimaryTableCol, MessagePlugin } from 'tdesign-vue-next'
import type { filterItemProp } from '@/components/PageFilters/interface/index'
import type { Pagination } from '@/components/PageContainer/interface/index'
import { useBasic } from '@/hooks/useBasic'
import MessageBox from '@/utils/messageBox'
import { ResMenu } from '@/api/interface/menu/index'
import { getMenuList, getAllMenuGroup, postMenuDisable, postMenuEnable, postMenuRemove } from '@/api/modules/menu/index'
import { statusTxt } from '@/utils/status'
import { menuLevelTxt } from './utils'
import MenuEdit from './page/menu-edit.vue'
import MenuLog from './page/menu-log.vue'
import MenuSort from './page/menu-sort.vue'

defineOptions({
  name: 'sys-menu'
})

const { setBreadcrumb } = useBasic()
// 标签页
const tabValue = ref(0)

// 切换标签页
const onTabChange = () => {
  getData()
  GetAllMenuGroup()
}

// 初始加载
onMounted(() => {
  setBreadcrumb([
    {
      title: '系统配置'
    },
    {
      title: '菜单管理'
    }
  ])
})

onActivated(() => {
  getData()
  GetAllMenuGroup()
})
// 搜索参数类型
const filterConditions = ref<filterItemProp[]>([])
// 表格列配置
const columns: PrimaryTableCol[] = [
  {
    title: '序号',
    colKey: 'serial-number',
    width: 70
  },
  {
    title: '菜单层级',
    colKey: 'menuLevel',
    cell: (h, { row }) => {
      return (
        <div class='flex items-center'>
          <span>{menuLevelTxt(row.menuLevel)}</span>
        </div>
      )
    }
  },
  { title: '父级菜单', colKey: 'parentName' },
  { title: '菜单名称', colKey: 'menuName' },
  { title: '路由名称', colKey: 'router' },
  { title: 'icon', colKey: 'icon_' },
  { title: '菜单路径', colKey: 'menuPath' },
  {
    title: '状态',
    colKey: 'status',
    cell: (h, { row }) => {
      return (
        <div class='flex items-center'>
          <div class={'dot ' + statusTxt(row.status)?.class}></div>
          <span class={statusTxt(row.status)?.class}>{statusTxt(row.status)?.title}</span>
        </div>
      )
    }
  },
  { title: '创建时间', colKey: 'inputTime' },
  {
    title: '创建人',
    colKey: 'inputUserName',
    width: 120,
    cell: (h, { row }) => {
      return (
        <div class='flex items-center justify-between'>
          <t-tooltip content={row.inputUserName}>
            <div class={row.inputUserDelFlag ? 'w-[calc(100%-58px)] ellipsis' : ''}>
              <span>{row.inputUserName || '-'}</span>
            </div>
          </t-tooltip>
          {row.inputUserDelFlag ? <span class='inputUserName-del'>已删除</span> : ''}
        </div>
      )
    }
  },
  { title: '操作', colKey: 'operation', fixed: 'right', width: 160 }
]
// 标签页
// 表格数据
const tableData = ref<ResMenu[]>([])
// 加载状态
const loading = ref(false)
// 分页配置
const pagination = ref<Pagination>({ page: 1, limit: 10, total: 0 })

const condMenuName = ref('')

const searchParams = ref<Record<string, any>>({}) // 搜索筛选
// 处理搜索条件
const handleSearch = (params: Record<string, any>) => {
  pagination.value.page = 1
  searchParams.value = params
  getData()
}

// 清空搜索条件
const handleClear = (flge: boolean | null) => {
  if (flge) {
    searchParams.value = {}
  }
  condMenuName.value = ''
  pagination.value.page = 1
  getData()
}

const onSearch = (params: Record<string, any>) => {
  searchParams.value = params
}

// 分页变更
const handlePage = (pageInfo: { page: number; limit: number }) => {
  pagination.value = { ...pagination.value, ...pageInfo }
  getData()
}

// // 编辑新增
const menuEditRef = ref()
const handleEdit = (row: ResMenu | null) => {
  menuEditRef.value?.open(row)
}

// 状态
const handleStatus = (row: ResMenu, status: number) => {
  const submit = status == 2 ? postMenuEnable : postMenuDisable
  const dialog = MessageBox(status, {
    onConfirm: () => {
      // 请求成功后，销毁弹框
      dialog.update({ confirmBtn: { content: '确定', loading: true } })
      submit({
        menuId: row?.menuId as string
      })
        .then(() => {
          MessagePlugin.success('操作成功')
          getData()
          dialog.hide()
        })
        .catch(() => {
          MessagePlugin.error('操作失败')
        })
        .finally(() => {
          dialog.update({ confirmBtn: { content: '确定', loading: false } })
        })
    }
  })
}

// 删除
const handleDel = (row: ResMenu) => {
  const dialog = MessageBox(3, {
    onConfirm: () => {
      // 请求成功后，销毁弹框
      dialog.update({ confirmBtn: { content: '确定', loading: true } })
      postMenuRemove({
        menuId: row?.menuId as string
      })
        .then(() => {
          getData()
          dialog.hide()
        })
        .finally(() => {
          dialog.update({ confirmBtn: { content: '确定', loading: false } })
        })
    }
  })
}

// 获取菜单列表
const getData = () => {
  loading.value = true
  const postData = {
    ...pagination.value,
    condMenuName: condMenuName.value,
    tabType: tabValue.value,
    ...searchParams.value
  }
  getMenuList(postData)
    .then(res => {
      tableData.value = res.data.map(e => {
        return {
          ...e,
          icon_: e.icon
        }
      })
      pagination.value.total = res?.recordsFiltered as number
    })
    .catch(() => {
      tableData.value = []
      pagination.value.total = 0
    })
    .finally(() => {
      loading.value = false
    })
}

// 获取所有菜单组
const allMenuGroups = ref<{ label: string; value: string | number }[]>([])
const GetAllMenuGroup = () => {
  getAllMenuGroup({ tabType: tabValue.value }).then(res => {
    allMenuGroups.value = res.data.map(e => {
      return {
        label: e.topMenuName,
        value: e.topMenuId
      }
    })

    filterConditions.value = [
      {
        label: '菜单层级',
        prop: 'menuLevel',
        type: 'select',
        selectData: [
          { label: '一级菜单', value: 1 },
          { label: '二级菜单', value: 2 },
          { label: '按钮', value: 3 }
        ]
      },
      {
        label: '菜单组',
        prop: 'topMenuId',
        type: 'select',
        selectData: allMenuGroups.value
      },
      {
        label: '状态',
        prop: 'status',
        type: 'select',
        selectData: [
          { label: '编辑中', value: 1 },
          { label: '启用', value: 2 },
          { label: '停用', value: 3 }
        ]
      }
    ]
  })
}

// 操作记录
const menuLogRef = ref()
const handleLog = () => {
  menuLogRef.value?.open()
}

// 菜单排序
const menuSortRef = ref()
const handleSort = () => {
  menuSortRef.value?.open()
}
</script>
