<template>
  <a-button
    v-if="props.isCreate"
    v-permission="['system:menu:create']"
    type="primary"
    @click="handleClick"
  >
    <template #icon><icon-plus /></template>
    新建
  </a-button>
  <a-button
    v-if="!props.isCreate"
    v-permission="['system:menu:update']"
    type="outline"
    size="small"
    :style="{ marginRight: '10px', padding: '7px' }"
    @click="handleClick"
  >
    <template #icon><icon-edit /></template>
    编辑
  </a-button>
  <a-modal
    width="700px"
    :visible="visible"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <template #title>{{ modalTitle }}</template>
    <a-form ref="createEditRef" :model="formData" :style="{ width: '650px' }">
      <a-form-item field="pid" label="父级菜单名称">
        <a-tree-select
          v-model="formData.pid"
          :data="props.menuData"
          :field-names="{
            key: 'id',
            title: 'name',
            children: 'children',
          }"
          :allow-clear="true"
          placeholder="请输入父级菜单名称"
        />
      </a-form-item>
      <a-form-item
        field="type"
        label="类型"
        :validate-trigger="['change', 'input']"
        :rules="[{ required: true, message: '请选择类型' }]"
      >
        <a-select
          v-model="formData.type"
          :options="typeOptions"
          placeholder="请选择类型"
        />
      </a-form-item>
      <a-form-item
        field="name"
        label="名称"
        :validate-trigger="['change', 'input']"
        :rules="[{ required: true, message: '请输入名称' }]"
      >
        <a-input v-model="formData.name" placeholder="请输入名称" />
      </a-form-item>
      <a-form-item
        field="path"
        label="路径"
        :validate-trigger="['change', 'input']"
        :rules="[{ required: true, message: '请输入路径' }]"
      >
        <a-input v-model="formData.path" placeholder="请输入路径" />
      </a-form-item>
      <a-form-item field="icon" label="图标">
        <a-input v-model="formData.icon" placeholder="请输入图标" />
      </a-form-item>
      <a-form-item
        field="locale"
        label="应用区域"
        :validate-trigger="['change', 'input']"
        :rules="[{ required: true, message: '应用区域' }]"
      >
        <a-input v-model="formData.locale" placeholder="请输入应用区域" />
      </a-form-item>
      <a-form-item field="requiresAuth" label="认证">
        <a-switch
          v-model="formData.requiresAuth"
          :checked-value="true"
          :unchecked-value="false"
        />
      </a-form-item>
      <a-form-item field="hideInMenu" label="隐藏">
        <a-switch
          v-model="formData.hideInMenu"
          :checked-value="true"
          :unchecked-value="false"
        />
      </a-form-item>
      <a-form-item
        field="menuOrder"
        label="菜单排序"
        :validate-trigger="['change', 'input']"
        :rules="[{ required: true, message: '请选择菜单排序' }]"
      >
        <a-input
          :model-value="String(formData.menuOrder)"
          placeholder="请输入菜单排序"
        />
      </a-form-item>
      <a-form-item
        field="permissions"
        label="权限"
        :validate-trigger="['change', 'input']"
        :rules="[{ required: true, message: '请输入权限' }]"
      >
        <a-input v-model="formData.permissions" placeholder="请输入权限" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang="ts" setup>
  import useVisible from '@/hooks/visible';
  import { computed, PropType, ref } from 'vue';
  import { FormInstance } from '@arco-design/web-vue/es/form';
  import { Message } from '@arco-design/web-vue';
  import {
    createMenu,
    MenuRecord,
    MenuUpdateRecord,
    queryMenuDetail,
    updateMenu,
  } from '@/api/menu';

  const props = defineProps({
    menuData: {
      type: Object as PropType<MenuRecord>,
    },
    isCreate: Boolean,
    id: {
      type: Number,
      default: -1,
    },
  });
  const modalTitle = computed(() => {
    return props.isCreate ? '新建菜单' : '编辑菜单';
  });
  const { visible, setVisible } = useVisible(false);
  const createEditRef = ref<FormInstance>();

  const formData = ref<MenuUpdateRecord>({
    type: '',
    name: '',
    path: '',
    locale: '',
    icon: '',
    requiresAuth: true,
    hideInMenu: false,
    menuOrder: 0,
    permissions: '',
  });
  const typeOptions = computed(() => [
    {
      label: '页面',
      value: 'PAGE',
    },
    {
      label: '操作',
      value: 'OPERATION',
    },
  ]);

  const emit = defineEmits(['refresh']);

  // 组件被点击
  const handleClick = () => {
    setVisible(true);
    if (!props.isCreate) {
      queryMenuDetail(props.id).then((res) => {
        formData.value = res.data;
      });
    }
  };

  // 提交
  const handleSubmit = async () => {
    const valid = await createEditRef.value?.validate();
    if (!valid) {
      // 新增
      if (props.isCreate) {
        const res = await createMenu(formData.value);
        if (res.status === 200) {
          Message.success({
            content: '新建成功',
            duration: 5 * 1000,
          });
        }
        createEditRef.value?.resetFields();
      } else {
        // 编辑
        const res = await updateMenu(formData.value);
        if (res.status === 200) {
          Message.success({
            content: '编辑成功',
            duration: 5 * 1000,
          });
        }
      }
      emit('refresh');
      setVisible(false);
    }
  };

  // 关闭
  const handleCancel = async () => {
    createEditRef.value?.resetFields();
    setVisible(false);
  };
</script>
