<script setup lang="ts" name="authManage_menuManage">
import type { FormInstance } from 'element-plus'

import { getPMenuTree, saveMenuRule, updateMenuRule } from '#/api'

const props = defineProps({
  showDia: {
    type: Boolean,
    default: false,
  },
  title: {
    type: String,
    default: '新增',
  },
  diaData: {
    type: Object,
    default: () => ({}),
  },
})
const emits = defineEmits(['update:showDia', 'onRefresh'])

const show = computed({
  get() {
    return props.showDia
  },
  set(val) {
    emits('update:showDia', val)
  },
})
const isUpdate = computed(() => props.title === '编辑')
const treeOption = ref([])
// 规则类型选项
const MENU_TYPE = [
  {
    label: '菜单目录',
    value: 0,
  },
  {
    label: '菜单项',
    value: 1,
  },
  {
    label: '页面按钮',
    value: 2,
  },
]
// 是否菜单目录
const isCatalogue = computed(() => form.type === 0)
// 是否菜单项
const isMenuItem = computed(() => form.type === 1)
// 是否页面按钮
const isButton = computed(() => form.type === 2)
// 根据选择的规则类型变更label
const name = computed(() => {
  if (isCatalogue.value) return '目录名称'
  if (isMenuItem.value) return '菜单名称'
  if (isButton.value) return '按钮名称'
})
const rules = computed(() => ({
  pid: {
    required: isButton.value,
    message: '上级菜单不能为空',
    trigger: 'blur',
  },
  name: {
    required: true,
    message: `${name.value}不能为空`,
    trigger: 'blur',
  },
  componentName: {
    required: true,
    message: '组件名称不能为空',
    trigger: 'blur',
  },
  componentPath: {
    required: true,
    message: '组件路径不能为空',
    trigger: 'blur',
  },
  path: {
    required: true,
    message: '路由路径不能为空',
    trigger: 'blur',
  },
  permission: {
    required: true,
    message: '权限标识不能为空',
    trigger: 'blur',
  },
  apiPermission: {
    required: true,
    message: '接口标识不能为空',
    trigger: 'blur',
  },
}))
const _form = {
  pid: '', // 父级菜单
  type: 0, // 规则类型
  name: '', // 标题
  componentName: '', // 组件名称
  componentPath: '', // 组件地址
  path: '', // 路由地址
  icon: '', // 路由图标
  sort: 0, // 排序
  keepalive: 1, // 是否开启缓存
  status: 0, // 是否启用 0 - 启用 1 - 禁用
  permission: '', // 权限标识
  apiPermission: '',
}
const form = reactive<anyObj>({
  ..._form,
})
const ruleFormRef = ref<FormInstance>()

function onOpen() {
  Object.assign(form, _form)
  if (isUpdate.value) {
    for (const i in form) {
      form[i] = props.diaData[i]
    }
  }
}

function getOpData() {
  getPMenuTree().then((res) => {
    treeOption.value = res
  })
}

async function handleSave() {
  if (!ruleFormRef.value) return
  await ruleFormRef.value.validate(async (valid, _) => {
    if (valid) {
      if (isUpdate.value) {
        updateMenuRule({
          id: props.diaData.id,
          ...form,
        }).then(() => {
          emits('onRefresh')
          show.value = false
        })
        return
      }
      saveMenuRule({
        ...form,
        pid: form.pid || '0',
      }).then(() => {
        emits('onRefresh')
        show.value = false
      })
    }
  })
}
</script>

<template>
  <el-dialog
    v-model="show"
    :title="title"
    width="600px"
    top="10vh"
    class="box"
    destroy-on-close
    @open="onOpen"
    @opened.once="getOpData"
  >
    <el-form
      ref="ruleFormRef"
      :model="form"
      :rules="rules"
      label-width="80px"
      :validate-on-rule-change="false"
    >
      <el-form-item label="上级菜单" prop="pid">
        <el-cascader
          v-model="form.pid"
          style="width: 100%"
          :options="treeOption"
          :props="{
            checkStrictly: true,
            emitPath: false,
            label: 'name',
            value: 'id',
          }"
          clearable
        />
      </el-form-item>
      <el-form-item label="规则类型" prop="type">
        <el-radio-group v-model="form.type">
          <el-radio
            v-for="item in MENU_TYPE"
            :key="item.value"
            :label="item.value"
            border
          >
            {{ item.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item :label="name" prop="name">
        <el-input v-model="form.name" v-select :placeholder="`请输入${name}`" />
      </el-form-item>

      <template v-if="isMenuItem">
        <el-form-item label="组件名称" prop="componentName">
          <el-input
            v-model="form.componentName"
            v-select
            placeholder="英文名称，如 `xxx`或`xxx_xxx`"
          />
        </el-form-item>
        <el-form-item label="组件路径" prop="componentPath">
          <el-input
            v-model="form.componentPath"
            v-select
            placeholder="英文路径，src下任意，不用/src开头，如`/modules/home/views/Home`"
          />
        </el-form-item>
        <el-form-item label="路由路径" prop="path">
          <el-input
            v-model="form.path"
            v-select
            placeholder="英文路径，如` /xxx`或`/xxx/xxx`"
          />
        </el-form-item>
      </template>

      <el-form-item v-if="!isButton" label="路由图标" prop="icon">
        <el-input
          v-model="form.icon"
          v-select
          placeholder="图标名称，存放在`src/assets/image/menu/*.png`"
        />
      </el-form-item>

      <template v-if="isButton">
        <el-form-item label="权限标识" prop="permission">
          <el-input
            v-model="form.permission"
            v-select
            placeholder="英文标识，如
                                                                                                                        `xxx`或`xxx_xxx`"
          />
        </el-form-item>
      </template>
      <template v-if="isButton">
        <el-form-item label="接口标识" prop="apiPermission">
          <el-input
            v-model="form.apiPermission"
            v-select
            placeholder="英文标识，如`xxx`或`xxx_xxx`"
          />
        </el-form-item>
      </template>

      <!-- 规则图标 -->
      <el-form-item label="排序" prop="sort">
        <el-input-number v-model="form.sort" :min="-1" :max="1000" />
      </el-form-item>
      <el-form-item v-if="isMenuItem" label="缓存" prop="firstName">
        <Switch
          v-model="form.keepalive"
          :inactive-value="0"
          :active-value="1"
        />
      </el-form-item>
      <el-form-item label="状态" prop="firstName">
        <Switch v-model="form.status" :inactive-value="1" :active-value="0" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="show = false">关闭</el-button>
        <el-button type="primary" @click="handleSave"> 保存 </el-button>
      </span>
    </template>
  </el-dialog>
</template>
