<template>
  <el-form
    :model="formParams"
    :rules="rules"
    ref="formRef"
    label-placement="left"
    :label-width="100"
    require-mark-placement="left"
  >
    <el-divider border-style="dashed" class="mt-0 mb-10">基本设置</el-divider>

    <el-form-item label="上级菜单" prop="parentId">
      <el-tree-select
        rowKey="key"
        :data="getPermissionList"
        clearable
        check-strictly
        v-model="formParams.parentId"
      />
    </el-form-item>

    <el-row :gutter="24">
      <el-col :span="12">
        <el-form-item label="菜单名称" prop="menuName">
          <el-input placeholder="菜单名称" v-model="formParams.menuName" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="菜单图标" prop="icon">
          <template #label>
            <div class="flex items-center">
              <el-tooltip trigger="hover">
                <el-icon :size="18" class="mr-1 text-gray-400 cursor-pointer">
                  <QuestionCircleOutlined />
                </el-icon>
                <template #content>
                  菜单图标，填写图标组件名称，需在 `src\router\router-icons.ts` 中导入并映射
                </template>
              </el-tooltip>
              <span>菜单图标</span>
            </div>
          </template>
          <el-input placeholder="菜单图标映射名称" v-model="formParams.icon" />
        </el-form-item>
      </el-col>
    </el-row>

    <el-row :gutter="24">
      <el-col :span="12">
        <el-form-item prop="routeUrl">
          <template #label>
            <div class="flex items-center">
              <el-tooltip trigger="hover">
                <el-icon :size="18" class="mr-1 text-gray-400 cursor-pointer">
                  <QuestionCircleOutlined />
                </el-icon>
                <template #content> 路由地址，如：user </template>
              </el-tooltip>
              <span>路由地址</span>
            </div>
          </template>
          <el-input placeholder="路由地址" v-model="formParams.routeUrl" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item prop="routeName">
          <template #label>
            <div class="flex items-center">
              <el-tooltip trigger="hover">
                <el-icon :size="18" class="mr-1 text-gray-400 cursor-pointer">
                  <QuestionCircleOutlined />
                </el-icon>
                <template #content>
                  对应路由配置文件中 `name` 只能是唯一性，配置 `http(s)://` 开头地址 则会新窗口打开
                </template>
              </el-tooltip>
              <span>路由名称</span>
            </div>
          </template>
          <el-input placeholder="路由名称" v-model="formParams.routeName" />
        </el-form-item>
      </el-col>
    </el-row>

    <el-row :gutter="24">
      <el-col :span="12">
        <el-form-item prop="redirect">
          <template #label>
            <div class="flex items-center">
              <el-tooltip trigger="hover">
                <el-icon :size="18" class="mr-1 text-gray-400 cursor-pointer">
                  <QuestionCircleOutlined />
                </el-icon>
                <template #content>
                  默认跳转路由地址，如：`/system/menu/menu` 多级路由情况下适用
                </template>
              </el-tooltip>
              <span>默认路由</span>
            </div>
          </template>
          <el-input placeholder="默认跳转路由地址" v-model="formParams.redirect" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="显示排序" prop="orderNum">
          <el-input-number placeholder="显示排序" v-model="formParams.orderNum" class="w-full" />
        </el-form-item>
      </el-col>
    </el-row>

    <el-row :gutter="24">
      <el-col>
        <el-form-item prop="component">
          <template #label>
            <div class="flex items-center">
              <el-tooltip trigger="hover">
                <el-icon :size="18" class="mr-1 text-gray-400 cursor-pointer">
                  <QuestionCircleOutlined />
                </el-icon>
                <template #content>
                  访问的组件路径，如：`/system/menu/menu`，默认在`views`目录下，默认 `LAYOUT`
                  如果是多级菜单 `ParentLayout`
                </template>
              </el-tooltip>
              <span>组件路径</span>
            </div>
          </template>
          <el-input placeholder="组件路径" v-model="formParams.component" />
        </el-form-item>
      </el-col>
    </el-row>

    <el-divider border-style="dashed" class="mb-10">功能设置</el-divider>

    <el-row :gutter="24">
      <el-col :span="12">
        <el-form-item prop="status">
          <template #label>
            <div class="flex items-center">
              <el-tooltip trigger="hover">
                <el-icon :size="18" class="mr-1 text-gray-400 cursor-pointer">
                  <QuestionCircleOutlined />
                </el-icon>
                <template #content>选择停用则路由将不会出现在侧边栏，也不能被访问</template>
              </el-tooltip>
              <span>菜单状态</span>
            </div>
          </template>
          <el-radio-group v-model="formParams.isDisabled">
            <el-radio-button :label="0">正常</el-radio-button>
            <el-radio-button :label="1">停用</el-radio-button>
          </el-radio-group>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="根路由" prop="isRoot">
          <template #label>
            <div class="flex items-center">
              <el-tooltip trigger="hover">
                <el-icon :size="18" class="mr-1 text-gray-400 cursor-pointer">
                  <QuestionCircleOutlined />
                </el-icon>
                <template #content>如果使用 `顶部混合菜单`，必须传 true，否则左侧会显示异常</template>
              </el-tooltip>
              <span>根路由</span>
            </div>
          </template>
          <el-switch v-model="formParams.isRoot" :active-value="1" :inactive-value="0" />
        </el-form-item>
      </el-col>
    </el-row>

    <el-row :gutter="24">
      <el-col :span="12">
        <el-form-item>
          <template #label>
            <div class="flex items-center">
              <el-tooltip trigger="hover">
                <el-icon :size="18" class="mr-1 text-gray-400 cursor-pointer">
                  <QuestionCircleOutlined />
                </el-icon>
                <template #content>选择隐藏则路由将不会出现在侧边栏，但仍然可以访问</template>
              </el-tooltip>
              <span>显示状态</span>
            </div>
          </template>
          <el-radio-group v-model="formParams.isHidden">
            <el-radio-button :label="0">显示</el-radio-button>
            <el-radio-button :label="1">隐藏</el-radio-button>
          </el-radio-group>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item prop="isCache">
          <template #label>
            <div class="flex items-center">
              <el-tooltip trigger="hover">
                <el-icon :size="18" class="mr-1 text-gray-400 cursor-pointer">
                  <QuestionCircleOutlined />
                </el-icon>
                <template #content
                  >选择是则会被`keep-alive`缓存，需要匹配组件的`name`和地址保持一致</template
                >
              </el-tooltip>
              <span>是否缓存</span>
            </div>
          </template>
          <el-radio-group v-model="formParams.isCache" name="isCacheGroup">
            <el-radio-button :label="0">不缓存</el-radio-button>
            <el-radio-button :label="1">缓存</el-radio-button>
          </el-radio-group>
        </el-form-item>
      </el-col>
    </el-row>

    <el-row :gutter="24">
      <el-col :span="12">
        <el-form-item label="是否外链" prop="isFrame">
          <template #label>
            <div class="flex items-center">
              <el-tooltip trigger="hover">
                <el-icon :size="18" class="mr-1 text-gray-400 cursor-pointer">
                  <QuestionCircleOutlined />
                </el-icon>
                <template #content>选择是外部地址需以`http(s)://`开头</template>
              </el-tooltip>
              <span>是否外链</span>
            </div>
          </template>
          <el-radio-group v-model="formParams.isFrame">
            <el-radio-button :label="0">否</el-radio-button>
            <el-radio-button :label="1">是</el-radio-button>
          </el-radio-group>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="简化路由" prop="alwaysShow">
          <template #label>
            <div class="flex items-center">
              <el-tooltip trigger="hover">
                <el-icon :size="18" class="mr-1 text-gray-400 cursor-pointer">
                  <QuestionCircleOutlined />
                </el-icon>
                <template #content
                  >取消自动计算根路由模式
                  开启之后，当菜单子菜单只有1个的时候，会直接显示子菜单</template
                >
              </el-tooltip>
              <span>简化路由</span>
            </div>
          </template>
          <el-switch v-model="formParams.isAlwaysShow" :active-value="1" :inactive-value="0" />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row :gutter="24">
      <el-col>
        <el-form-item label="外部地址" prop="frameSrc" v-if="formParams.isFrame === 1">
          <el-input placeholder="内联外部地址" v-model="formParams.frameSrc" />
        </el-form-item>
      </el-col>
    </el-row>

    <el-form-item v-if="isShowSubmit">
      <el-button type="primary" :loading="subLoading" @click="formSubmit">保存修改</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
  import { ref, computed } from 'vue';
  import { ElMessage, FormInstance } from 'element-plus';
  import { addMenu, editMenu } from '@/api/system/menu';
  import { QuestionCircleOutlined } from '@vicons/antd';
  import { replaceParams } from '@/utils/helper/treeHelper';
  import { cloneDeep } from 'lodash-es';
  import { MenuDetail } from '@/types/menu/type';

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

  const props = defineProps({
    permissionList: {
      type: Array,
      defalut: () => [],
    },
    isShowSubmit: {
      type: Boolean,
      defalut: false,
    },
  });

  const formRef = ref<FormInstance>();
  const subLoading = ref(false);

  const defaultFormParams: MenuDetail = {
    id: null,
    parentId: null,
    menuName: '',
    menuCode: '',
    routeName: '',
    routeUrl: '',
    component: '',
    redirect: '',
    orderNum: null,
    icon: '',
    isHidden: 0,
    isDisabled: 0,
    isAlwaysShow: 0,
    isRoot: 0,
    isAffix: 0,
    isCache: 0,
    isFrame: 0,
    frameSrc: '',
    openType: 1, 
    query: '',
    children: []
  };

  const formParams = ref({ ...defaultFormParams });

  const getPermissionList = computed(() => {
    // 可根据需要是否需要嵌套这个 避免出现选择器出现 0 的情况
    return [
      {
        label: '顶级目录',
        value: 0,
        children: replaceParams(cloneDeep(props.permissionList || []), 'label', 'key'),
      },
    ];
  });

  const rules = {
    menuName: {
      required: true,
      message: '菜单名称',
      trigger: 'blur',
    },
    routeUrl: {
      required: true,
      message: '路由地址不能为空',
      trigger: 'blur',
    },
    component: {
      required: true,
      message: '组件路径不能为空',
      trigger: 'blur',
    },
    routeName: {
      required: true,
      message: '路由名称不能为空',
      trigger: 'blur',
    },
    frameSrc: {
      required: true,
      message: '外部地址不能为空',
      trigger: 'blur',
    },
  };

  function setData(data: MenuDetail) {
    formParams.value = data;
    formRef.value?.resetFields();
  }

  function formSubmit() {
    subLoading.value = true;
    formRef.value?.validate((valid) => {
      if (valid) {
        if (!formParams.value.id) {
          addMenu(formParams.value)
            .then(() => {
              subLoading.value = false;
              ElMessage.success('添加成功');
              handleReset();
              emit('change');
            })
            .catch(() => {
              subLoading.value = false;
            });
        } else {
          editMenu(formParams.value)
            .then(() => {
              subLoading.value = false;
              ElMessage.success('修改成功');
              handleReset();
              emit('change');
            })
            .catch(() => {
              subLoading.value = false;
            });
        }
      } else {
        subLoading.value = false;
        ElMessage.error('请填写完整信息');
      }
    });
  }

  function handleReset() {
    formRef.value?.resetFields();
    formParams.value = Object.assign(formParams.value, defaultFormParams);
  }

  defineExpose({
    formSubmit,
    handleReset,
    setData,
  });
</script>

<style lang="scss" sctep>
  .submit-form-item {
    margin-left: 100px;
  }
</style>
