<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="extendedMenuTree"
        clearable
        check-strictly
        v-model="formParams.parentId"
        :disabled="isEditing"
      />
    </el-form-item>

    <el-form-item label="菜单名称" required>
      <el-tree-select
        v-if="isCreating"
        rowKey="key"
        :data="routeViewList"
        clearable
        check-strictly
        v-model="routeViewValue"
      />
      <el-input v-else v-model="formParams.menuName" disabled />
    </el-form-item>


    <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" disabled />
        </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" disabled />
        </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" disabled />
        </el-form-item>
      </el-col>
    </el-row>

    <el-row :gutter="24">
      <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" disabled />
        </el-form-item>
      </el-col>
      <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" disabled />
        </el-form-item>
      </el-col>
    </el-row>



    <el-row :gutter="24">
      <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-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="正常" :value="0" />
            <el-radio-button label="停用" :value="1" />
          </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="显示" :value="0" />
            <el-radio-button label="隐藏" :value="1" />
          </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="不缓存" :value="0" />
            <el-radio-button label="缓存" :value="1" />
          </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="否" :value="0" />
            <el-radio-button label="是" :value="1" />
          </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, watch, shallowRef } from 'vue';
  import { ElMessage, FormInstance, FormRules } 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 { MenuDetailItem, MenuTree, Menu } from '@/types/menu/type';
  import { getChildRoutesView, _RouteViewItem, getRouteByName } from '@/router/full-routes';
  import { getTreeItem } from '@/utils';

  const props = defineProps<{
    parentMenuTree: MenuTree; // "上级菜单"树
    isShowSubmit?: boolean;
    isCreating?: boolean;
  }>();

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

  const formRef = ref<FormInstance>();
  const rules: FormRules = {
    parentId: {
      required: true,
      message: '上级菜单',
      trigger: 'change',
    },
    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',
    },
  };


  const subLoading = ref(false);

  const defaultFormParams: MenuDetailItem = {
    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: '',
  };
  const formParams = ref({ ...defaultFormParams });

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

  const isEditing = computed(() => !props.isCreating);
  const routeViewValue = ref('');
  const routeViewList = shallowRef<_RouteViewItem[]>([]);


  // 根据 "上级菜单"，生成可选的"当前菜单"
  watch(
    () => formParams.value.parentId,
    (newVal) => {
      // 编辑模式下，只是展示，不需要计算数据。
      if (isEditing.value) return;

      // 若清除选项
      if (newVal == null) {
        routeViewList.value = [];
        return;
      } 

      // 若选择顶级目录, 返回路由表的 leve1 列表
      if (newVal === 0) {
        routeViewList.value = getChildRoutesView(null);
        return;
      } 

      // 否则展示 parent 下的 子路由
      const { routeName } = getTreeItem(props.parentMenuTree!, newVal, 'id') as Menu;
      if (routeName) {
        routeViewList.value = getChildRoutesView(routeName);
      } else {
        ElMessage.error('无法获取可用路由列表');
      }
    }
  );

  // 根据 routeViewValue，即 routeName，将菜单其余信息补充
  watch(routeViewValue, (val) => {
    if (!val) {
      handleReset();
      return;
    }

    const currentRoute = getRouteByName(val);
    formParams.value.routeName = currentRoute.name;
    formParams.value.routeUrl = currentRoute.path;
    formParams.value.component = currentRoute.component;
    formParams.value.icon = currentRoute.meta.icon as string;
    formParams.value.menuName = currentRoute.meta.title as string;
  });

  function setData(data: MenuDetailItem) {
    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 = { ...defaultFormParams };
    routeViewValue.value = '';
  }

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

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