<template>
  <!-- 添加或修改菜单抽屉 -->
  <el-drawer v-model="visibleProxy" :title="title" size="55%" append-to-body :close-on-click-modal="false" @closed="resetForm">
    <el-card shadow="always" class="box-card" style="padding-top: 10px">
      <el-form ref="menuFormRef" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <!-- ========== 基础信息区域 ========== -->
          <el-col :span="24">
            <el-divider content-position="left">
              <span class="section-title">基础信息</span>
            </el-divider>
          </el-col>

          <el-col :span="24">
            <el-form-item label="上级菜单">
              <el-tree-select
                v-model="form.parentId"
                :data="menuOptions"
                :props="{ value: 'menuId', label: 'menuName', children: 'children' }"
                value-key="menuId"
                placeholder="选择上级菜单"
                check-strictly
              />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="菜单类型" prop="menuType">
              <el-radio-group v-model="form.menuType" @change="handleMenuTypeChange">
                <el-radio value="M">目录</el-radio>
                <el-radio value="C">菜单</el-radio>
                <el-radio value="F">按钮</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="菜单名称" prop="menuName">
              <el-input v-model="form.menuName" placeholder="请输入菜单名称" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="显示排序" prop="orderNum">
              <el-input-number v-model="form.orderNum" controls-position="right" :min="0" :max="100000" />
            </el-form-item>
          </el-col>

          <el-col v-if="form.menuType !== 'F'" :span="12">
            <el-form-item label="菜单图标" prop="icon">
              <!-- 图标选择器 -->
              <icon-select v-model="form.icon" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item>
              <template #label>
                <span>
                  <el-tooltip content="选择停用则路由将不会出现在侧边栏，也不能被访问" placement="top">
                    <el-icon>
                      <question-filled />
                    </el-icon>
                  </el-tooltip>
                  菜单状态
                </span>
              </template>
              <el-radio-group v-model="form.status">
                <el-radio v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.value">
                  {{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <!-- ========== 菜单归属区域（仅菜单类型为C时显示）========== -->
          <template v-if="form.menuType === 'C'">
            <el-col :span="24">
              <el-divider content-position="left">
                <span class="section-title">归属配置</span>
              </el-divider>
            </el-col>

            <el-col :span="12">
              <el-form-item label="菜单归属" prop="menuCategory">
                <el-select v-model="form.menuCategory" placeholder="请选择菜单归属" clearable>
                  <el-option
                    v-for="dict in sys_user_role_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
                <div class="form-tip">
                  <small
                  ><el-icon><InfoFilled /></el-icon>菜单归属决定了哪些角色类型可以访问此菜单</small
                  >
                </div>
              </el-form-item>
            </el-col>

            <!-- <el-col :span="12">
              <el-form-item label="所属渠道">
                <i-select v-model="form.branchType" dict-type="branchtype" placeholder="请选择渠道" clearable />
                <div class="form-tip">
                  <small
                  ><el-icon><InfoFilled /></el-icon>所属渠道决定了该菜单在哪些渠道下可见</small
                  >
                </div>
              </el-form-item>
            </el-col> -->
          </template>

          <!-- ========== 路由配置区域 ========== -->
          <template v-if="form.menuType !== 'F'">
            <el-col :span="24">
              <el-divider content-position="left">
                <span class="section-title">路由配置</span>
              </el-divider>
            </el-col>

            <el-col :span="12">
              <el-form-item>
                <template #label>
                  <span>
                    <el-tooltip content="选择是外链则路由地址需要以`http(s)://`开头" placement="top">
                      <el-icon>
                        <question-filled />
                      </el-icon> </el-tooltip
                    >是否外链
                  </span>
                </template>
                <el-radio-group v-model="form.isFrame">
                  <el-radio label="0">是</el-radio>
                  <el-radio label="1">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item>
                <template #label>
                  <span>
                    <el-tooltip content="选择隐藏则路由将不会出现在侧边栏，但仍然可以访问" placement="top">
                      <el-icon>
                        <question-filled />
                      </el-icon>
                    </el-tooltip>
                    显示状态
                  </span>
                </template>
                <el-radio-group v-model="form.visible">
                  <el-radio v-for="dict in sys_show_hide" :key="dict.value" :label="dict.value">{{ dict.label }} </el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item prop="path">
                <template #label>
                  <span>
                    <el-tooltip content="访问的路由地址，如：`user`，如外网地址需内链访问则以`http(s)://`开头" placement="top">
                      <el-icon>
                        <question-filled />
                      </el-icon>
                    </el-tooltip>
                    路由地址
                  </span>
                </template>
                <el-input v-model="form.path" placeholder="请输入路由地址" />
              </el-form-item>
            </el-col>
          </template>

          <!-- 组件路径（仅菜单类型为C时显示，整行显示）-->
          <el-col v-if="form.menuType === 'C'" :span="24">
            <el-form-item prop="component">
              <template #label>
                <span>
                  <el-tooltip content="访问的组件路径，如：`system/user/index`，默认在`views`目录下" placement="top">
                    <el-icon>
                      <question-filled />
                    </el-icon>
                  </el-tooltip>
                  组件路径
                </span>
              </template>
              <el-input v-model="form.component" placeholder="请输入组件路径" />
            </el-form-item>
          </el-col>

          <!-- ========== 权限配置区域 ========== -->
          <template v-if="form.menuType !== 'M'">
            <el-col :span="24">
              <el-divider content-position="left">
                <span class="section-title">权限配置</span>
              </el-divider>
            </el-col>

            <el-col :span="24">
              <el-form-item>
                <el-input v-model="form.perms" placeholder="请输入权限标识" maxlength="100" />
                <template #label>
                  <span>
                    <el-tooltip content="控制器中定义的权限字符，如：@SaCheckPermission('system:user:list')" placement="top">
                      <el-icon>
                        <question-filled />
                      </el-icon>
                    </el-tooltip>
                    权限字符
                  </span>
                </template>
              </el-form-item>
            </el-col>
          </template>

          <!-- 路由参数（仅菜单类型为C时显示，整行显示）-->
          <el-col v-if="form.menuType === 'C'" :span="24">
            <el-form-item>
              <el-input v-model="form.queryParam" placeholder="请输入路由参数" maxlength="255" />
              <template #label>
                <span>
                  <el-tooltip content='访问路由的默认传递参数，如：`{"id": 1, "name": "ry"}`' placement="top">
                    <el-icon>
                      <question-filled />
                    </el-icon>
                  </el-tooltip>
                  路由参数
                </span>
              </template>
            </el-form-item>
          </el-col>

          <!-- ========== 高级配置区域（仅菜单类型为C时显示）========== -->
          <template v-if="form.menuType === 'C'">
            <el-col :span="24">
              <el-divider content-position="left">
                <span class="section-title">高级配置</span>
              </el-divider>
            </el-col>

            <el-col :span="12">
              <el-form-item>
                <template #label>
                  <span>
                    <el-tooltip content="选择是则会被`keep-alive`缓存，需要匹配组件的`name`和地址保持一致" placement="top">
                      <el-icon>
                        <question-filled />
                      </el-icon>
                    </el-tooltip>
                    是否缓存
                  </span>
                </template>
                <el-radio-group v-model="form.isCache">
                  <el-radio label="0">缓存</el-radio>
                  <el-radio label="1">不缓存</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item>
                <template #label>
                  <span>
                    <el-tooltip content="用于关联帮助文档和视频的业务代码" placement="top">
                      <el-icon>
                        <question-filled />
                      </el-icon>
                    </el-tooltip>
                    帮助代码
                  </span>
                </template>
                <el-input v-model="form.helpCode" placeholder="请输入帮助代码" maxlength="50" />
              </el-form-item>
            </el-col>
          </template>
        </el-row>
      </el-form>
    </el-card>
    <template #footer>
      <div class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
import { addMenu, getMenu, updateMenu, listMenu } from '@/api/system/menu';
import { MenuForm, MenuVO } from '@/api/system/menu/types';
import { MenuTypeEnum } from '@/enums/MenuTypeEnum';
import { InfoFilled, QuestionFilled } from '@element-plus/icons-vue';
import ISelect from '@/views/modules/common/ISelect.vue';

interface MenuOptionsType {
  menuId: number;
  menuName: string;
  children: MenuOptionsType[] | undefined;
}

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  editType: {
    type: String,
    default: 'add'
  },
  rowData: {
    type: Object as PropType<MenuVO | null>,
    default: null
  }
});

const emit = defineEmits(['update:visible', 'save']);

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
// 添加字典引用
const { sys_show_hide, sys_normal_disable, sys_user_role_type } = toRefs<any>(
  proxy?.useDict('sys_show_hide', 'sys_normal_disable', 'sys_user_role_type')
);

// 可见性的双向绑定
const visibleProxy = computed({
  get: () => props.visible,
  set: (val) => emit('update:visible', val)
});

// 根据编辑类型决定标题
const title = computed(() => (props.editType === 'add' ? '添加菜单' : '修改菜单'));

// 按钮loading
const buttonLoading = ref(false);

// 表单ref
const menuFormRef = ref<ElFormInstance>();

// 菜单树选项
const menuOptions = ref<MenuOptionsType[]>([]);

// 初始化表单数据
const initFormData: MenuForm = {
  path: '',
  menuId: undefined,
  parentId: 0,
  menuName: '',
  icon: '',
  menuType: MenuTypeEnum.M,
  orderNum: 1,
  isFrame: '1',
  isCache: '0',
  visible: '0',
  status: '0',
  branchType: '', // 渠道
  helpCode: '', // 帮助代码
  menuCategory: '' // 菜单归属
};

// 表单数据
const form = ref<MenuForm>({ ...initFormData });

// 表单校验规则
const rules = ref({
  menuName: [{ required: true, message: '菜单名称不能为空', trigger: 'blur' }],
  orderNum: [{ required: true, message: '菜单顺序不能为空', trigger: 'blur' }],
  path: [{ required: true, message: '路由地址不能为空', trigger: 'blur' }],
  // 动态校验规则：只有菜单类型为C时才校验菜单归属
  menuCategory: [
    {
      required: false,
      validator: (rule: any, value: any, callback: any) => {
        if (form.value.menuType === 'C' && !value) {
          callback(new Error('菜单归属不能为空'));
        } else {
          callback();
        }
      },
      trigger: 'change'
    }
  ]
});

/**
 * 菜单类型变化处理
 */
const handleMenuTypeChange = (value: string) => {
  // 当菜单类型不是C时，清空菜单归属、渠道和帮助代码
  if (value !== 'C') {
    form.value.menuCategory = '';
    form.value.branchType = '';
    form.value.helpCode = '';
  }

  // 触发表单验证，确保校验规则更新
  nextTick(() => {
    menuFormRef.value?.clearValidate(['menuCategory']);
  });
};

/** 取消按钮 */
const cancel = () => {
  visibleProxy.value = false;
};

/** 表单重置 */
const resetForm = () => {
  form.value = { ...initFormData };
  menuFormRef.value?.resetFields();
};

/** 查询菜单下拉树结构 */
const getTreeselect = async () => {
  menuOptions.value = [];
  const response = await listMenu();
  const menu: MenuOptionsType = { menuId: 0, menuName: '主类目', children: [] };
  menu.children = proxy?.handleTree<MenuOptionsType>(response.data, 'menuId');
  menuOptions.value.push(menu);
};

/** 提交按钮 */
const submitForm = () => {
  menuFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      try {
        const formData = { ...form.value };

        // 如果菜单类型不是C，确保清空相关字段
        if (formData.menuType !== 'C') {
          formData.menuCategory = '';
          formData.branchType = '';
          formData.helpCode = '';
        }

        if (formData.menuId) {
          await updateMenu(formData);
        } else {
          await addMenu(formData);
        }
        proxy?.$modal.msgSuccess('操作成功');
        emit('save');
        visibleProxy.value = false;
      } finally {
        buttonLoading.value = false;
      }
    }
  });
};

// 修改操作时的数据处理
watch(
  [() => props.visible, () => props.editType, () => props.rowData],
  async ([visible, type, data]) => {
    if (visible) {
      resetForm();
      await getTreeselect();

      if (type === 'add') {
        // 新增操作，如果有父菜单数据，设置父菜单ID
        if (data && data.menuId) {
          form.value.parentId = data.menuId;
        } else {
          form.value.parentId = 0;
        }
      } else if (type === 'edit' && data) {
        // 修改操作
        const res = await getMenu(data.menuId);
        Object.assign(form.value, res.data);
      }
    }
  },
  { immediate: true }
);
</script>

<style scoped>
:deep(.el-select) {
  width: 100%;
}

:deep(.el-tree-select) {
  width: 100%;
}

.form-tip {
  margin-top: 5px;
  color: #606266;
  font-size: 12px;
  line-height: 1.4;
  display: flex;
  align-items: center;
}

.form-tip .el-icon {
  margin-right: 4px;
  vertical-align: middle;
}

.section-title {
  font-weight: 600;
  color: #409eff;
  font-size: 14px;
}

:deep(.el-divider__text) {
  padding: 0 15px;
}

:deep(.el-divider--horizontal) {
  margin: 20px 0 15px 0;
}
</style>
