<template>
  <div class="main-content">
    <BaseTable
      :tableHeader="tableHeader"
      :tableData="tableData"
      :tableOperate="tableOperate"
      :searchParams="searchParams"
      :search="false"
      :many="false"
      :moreOperation="false"
      :isPage="false"
      rowKey="id"
      :treeProps="{ children: 'children', hasChildren: 'hasChildren' }"
      @searchFn="searchFn"
      @addFn="addFn"
    />

    <el-dialog :title="formDialog.title" v-model="formDialog.visible" :close-on-click-modal="false">
      <el-form ref="formRef" size="small" label-width="120px" :model="formDialog.formData" :rules="formDialog.formRules">
        <el-form-item label="菜单名称" prop="name">
          <el-input v-model.trim="formDialog.formData.name" />
        </el-form-item>
        <el-form-item label="路由地址" prop="path">
          <el-input v-model.trim="formDialog.formData.path" />
        </el-form-item>
        <el-form-item label="组件路径" prop="component">
          <el-input v-model.trim="formDialog.formData.component" />
        </el-form-item>
        <el-form-item label="图标" prop="icon">
          <el-input v-model.trim="formDialog.formData.icon" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="formDialog.formData.sort" :min="0" />
        </el-form-item>
        <el-form-item label="父级菜单" prop="parentId">
          <el-input v-model.trim="formDialog.formData.parentId" placeholder="0为顶级菜单" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" :loading="formDialog.loading" @click="submitFn">确定</el-button>
        <el-button @click="cancelFn">取消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, computed, h } from 'vue'
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus'
import { queryMenuPage, createMenu, updateMenu, removeMenu } from '@/api/menu'
import { formatDict } from '@/utils/global'
import { useAppStore } from '@/stores/app'
import type { FormInstance, FormRules } from 'element-plus'

const appStore = useAppStore()
const formRef = ref<FormInstance>()

const searchParams = reactive({})

const dictYesOrNo = computed(() => appStore.dict.dictYesOrNo || [])

const tableHeader = [
  { label: '名称', prop: 'title', align: 'left' as const, minWidth: 200 },
  {
    label: '图标', align: 'center' as const, width: 80, type: 'render' as const,
    render: (_h: any, params: any) => h('i', { class: params.row.icon })
  },
  { label: '排序号', prop: 'ord', align: 'center' as const, width: 80 },
  {
    label: '隐藏菜单', align: 'center' as const, width: 100, type: 'render' as const,
    render: (_h: any, params: any) => h('el-tag', { size: 'small', type: params.row.hidden === '1' ? 'success' : 'danger' }, formatDict(dictYesOrNo.value, params.row.hidden))
  },
  {
    label: '路由缓冲', align: 'center' as const, width: 100, type: 'render' as const,
    render: (_h: any, params: any) => h('el-tag', { size: 'small', type: params.row.keepAlive === '1' ? 'success' : 'danger' }, formatDict(dictYesOrNo.value, params.row.keepAlive))
  },
  { label: '组件', prop: 'component', align: 'left' as const, minWidth: 150 },
  {
    label: '权限', align: 'left' as const, minWidth: 150, type: 'render' as const,
    render: (_h: any, params: any) => {
      const tags = (params.row.permissions || []).map((p: any) =>
        h('el-tag', { size: 'small', style: { marginLeft: '5px' } }, p.permissionName + ' ')
      )
      return h('span', tags)
    }
  }
]

const tableData = ref<any[]>([])

const tableOperate = [
  { label: '编辑', type: 'primary', icon: 'el-icon-edit', func: (row: any) => editFn(row) },
  { label: '删除', type: 'danger', icon: 'el-icon-delete', func: (row: any) => delFn(row) }
]

const formDialog = reactive({
  title: '',
  visible: false,
  loading: false,
  formData: {} as any,
  formRules: {
    name: [{ required: true, message: '请输入菜单名称', trigger: 'blur' }],
    path: [{ required: true, message: '请输入路由地址', trigger: 'blur' }]
  } as FormRules
})

function searchFn(_isReset = false) {
  queryMenuPage({ scope: '1' }).then(
    (res: any) => { tableData.value = res.data || [] },
    (error: any) => ElNotification.error({ title: error?.data?.msg || '', message: error?.data?.data || '' })
  )
}

function addFn() {
  formDialog.title = '新增'
  formDialog.visible = true
  formDialog.loading = false
  formDialog.formData = { sort: 0, parentId: '0' }
}

function editFn(row: any) {
  formDialog.title = '编辑'
  formDialog.formData = { ...row }
  formDialog.visible = true
}

function cancelFn() {
  formDialog.visible = false
  formDialog.formData = {}
  formRef.value?.resetFields()
}

function submitFn() {
  if (!formRef.value) return
  formDialog.loading = true
  formRef.value.validate((valid: boolean) => {
    if (!valid) { formDialog.loading = false; return }
    const api = formDialog.formData.id ? updateMenu : createMenu
    api(formDialog.formData).then(
      () => {
        ElMessage.success(formDialog.formData.id ? '修改成功' : '新增成功')
        formDialog.visible = false
        formDialog.loading = false
        searchFn()
      },
      (error: any) => {
        ElNotification.error({ title: error?.data?.msg || '', message: error?.data?.data || '' })
        formDialog.loading = false
      }
    )
  })
}

function delFn(row: any) {
  ElMessageBox.confirm('此操作将删除该记录, 是否继续?', '提示', { type: 'warning' }).then(() => {
    removeMenu({ id: row.id }).then(
      () => { ElMessage.success('删除成功'); searchFn() },
      (error: any) => ElNotification.error({ title: error?.data?.msg || '', message: error?.data?.data || '' })
    )
  })
}

searchFn()
</script>
