<script setup lang="tsx">
import { computed, ref, watch } from 'vue';
import type { SelectOption, TreeSelectOption } from 'naive-ui';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import { $t } from '@/locales';
import { menuIconTypeOptions, specialEnableStatusOptions } from '@/constants/business';
import SvgIcon from '@/components/custom/svg-icon.vue';
import { getLocalIcons } from '@/utils/icon';
import { fetchAddMenu, fetchGetMenuList, fetchUpdateMenu } from '@/service/api/system/menu';
import { handleTree } from '@/utils/ruoyi';
import {
  getLayoutAndPage,
  getPathParamFromRoutePath,
  getRoutePathByRouteName,
  getRoutePathWithParam,
  transformLayoutAndPageToComponent
} from './shared';

defineOptions({
  name: 'MenuOperateModal'
});

export type OperateType = NaiveUI.TableOperateType | 'addChild';

interface Props {
  /** the type of operation */
  operateType: OperateType;
  /** the edit menu data or the parent menu data when adding a child menu */
  rowData?: Api.SystemManage.Menu | null;
  /** all pages */
  allPages: string[];
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const { formRef, validate, restoreValidation } = useNaiveForm();
const { defaultRequiredRule } = useFormRules();

const title = computed(() => {
  const titles: Record<OperateType, string> = {
    add: $t('page.manage.menu.addMenu'),
    addChild: $t('page.manage.menu.addChildMenu'),
    edit: $t('page.manage.menu.editMenu')
  };
  return titles[props.operateType];
});

type Model = Pick<
  Api.SystemManage.Menu,
  | 'menuType'
  | 'menuName'
  | 'routeName'
  | 'routePath'
  | 'component'
  | 'order'
  | 'orderNum'
  | 'i18nKey'
  | 'icon'
  | 'iconType'
  | 'status'
  | 'parentId'
  | 'keepAlive'
  | 'constant'
  | 'href'
  | 'hideInMenu'
  | 'activeMenu'
  // | 'multiTab'
  // | 'fixedIndexInTab'
  | 'perms'
  | 'path'
> & {
  // query: NonNullable<Api.SystemManage.Menu['query']>;
  // buttons: NonNullable<Api.SystemManage.Menu['buttons']>;
  layout: string;
  page: string;
  pathParam: string;
};

const model = ref<Api.SystemManage.Menu>(createDefaultModel());

function createDefaultModel(): any {
  return {
    menuId: null,
    menuType: 'M',
    menuName: '',
    routeName: '',
    // routePath: '',
    pathParam: '',
    path: '',
    component: '',
    // layout: '',
    // page: '',
    // i18nKey: null,
    icon: '',
    iconType: '1',
    parentId: 0,
    status: '0',
    keepAlive: false,
    constant: false,
    // order: 0,
    orderNum: 0,
    href: null,
    hideInMenu: false,
    // activeMenu: null,
    // multiTab: false,
    // fixedIndexInTab: null,
    // query: [],
    // buttons: [],
    perms: '' // 权限标识
  };
}

type RuleKey = Extract<keyof Model, 'menuName' | 'status' | 'routeName' | 'routePath' | 'path'>;

const rules: Record<RuleKey, App.Global.FormRule> = {
  menuName: defaultRequiredRule,
  status: defaultRequiredRule,
  routeName: defaultRequiredRule,
  routePath: defaultRequiredRule,
  path: defaultRequiredRule
};

const disabledMenuType = computed(() => props.operateType === 'edit');

const localIcons = getLocalIcons();
const localIconOptions = localIcons.map<SelectOption>(item => ({
  label: () => (
    <div class="flex-y-center gap-16px">
      <SvgIcon localIcon={item} class="text-icon" />
      <span>{item}</span>
    </div>
  ),
  value: item
}));

const showLayout = computed(() => model.value.parentId === 0);

const showPage = computed(() => model.value.menuType === 'C');

const showButton = computed(() => model.value.menuType === 'F');

// 菜单
const pageOptions = computed(() => {
  const allPages = [...props.allPages];

  if (model.value.routeName && !allPages.includes(model.value.routeName)) {
    allPages.unshift(model.value.routeName);
  }

  const opts: CommonType.Option[] = allPages.map(page => ({
    label: page,
    value: page
  }));

  return opts;
});

const layoutOptions: CommonType.Option[] = [
  {
    label: 'base',
    value: 'base'
  },
  {
    label: 'blank',
    value: 'blank'
  }
];
// 菜单类型选项
const menuTypeOptions: CommonType.Option[] = [
  { label: '目录', value: 'M' },
  { label: '菜单', value: 'C' },
  { label: '按钮', value: 'F' }
];

// 选择上级菜单
const menuOptions = ref<TreeSelectOption[]>([]);
/** 查询菜单下拉树结构 */
function getTreeselect() {
  fetchGetMenuList<Api.SystemManage.Menu[]>().then(response => {
    menuOptions.value = [];
    const menu: { menuId: number; menuName: string; children: TreeSelectOption[] } = {
      menuId: 0,
      menuName: '主类目',
      children: []
    };
    menu.children = handleTree(response.data as Api.SystemManage.Menu[], 'menuId') as TreeSelectOption[];
    menuOptions.value.push(menu);
  });
}

function handleInitModel() {
  model.value = createDefaultModel();
  if (!props.rowData) return;
  if (props.operateType === 'add') {
    // if (props.rowData?.menuId) {
    //   const { menuId } = props.rowData;
    //   Object.assign(model, { parentId: menuId, menuId: '' });
    // } else {
    //   model.parentId = 0;
    // }
  }
  if (props.operateType === 'addChild') {
    if (props.rowData?.menuId) {
      const { menuId } = props.rowData;
      // Object.assign(model, { parentId: menuId, menuId: '' });
      model.value.parentId = menuId;
      model.value.menuId = null;
    } else {
      model.value.parentId = 0;
    }
  }

  if (props.operateType === 'edit') {
    const { component, ...rest } = props.rowData;

    const { layout, page } = getLayoutAndPage(component);
    const { path, param } = getPathParamFromRoutePath(rest.path as string);

    Object.assign(model.value, rest, { layout, page, routePath: path, pathParam: param });
  }
  //
  // if (!model.query) {
  //   model.query = [];
  // }
  // if (!model.buttons) {
  //   model.buttons = [];
  // }
}

function closeDrawer() {
  visible.value = false;
}

function handleUpdateRoutePathByRouteName() {
  if (model.value.routeName) {
    model.value.routePath = getRoutePathByRouteName(model.value.routeName);
    model.value.path = getRoutePathByRouteName(model.value.routeName);
  } else {
    model.value.routePath = '';
    model.value.path = '';
  }
}

function handleUpdateI18nKeyByRouteName() {
  if (model.value.routeName) {
    model.value.i18nKey = `route.${model.value.routeName}` as App.I18n.I18nKey;
  } else {
    model.value.i18nKey = null;
  }
}

function getSubmitParams() {
  const { layout, page, pathParam, ...params } = model.value;

  const component = transformLayoutAndPageToComponent(layout, page);
  const routePath = getRoutePathWithParam(model.value.path, pathParam);

  params.component = component;
  // params.routePath = routePath;
  params.path = routePath;

  return params;
}

// 代表选择的主类目
function handleUpdateParentId() {
  if (showLayout.value && !showPage.value) {
    model.value.page = '';
  } else if (!showLayout.value && showPage.value) {
    model.value.layout = '';
  }
}

// 提交表单
async function handleSubmit() {
  await validate();
  const params = getSubmitParams();
  if (props.operateType === 'edit') {
    const { error } = await fetchUpdateMenu(params);
    if (!error) {
      window.$message?.success($t('common.updateSuccess'));
      closeDrawer();
      emit('submitted');
    }
  }
  if (props.operateType === 'add' || props.operateType === 'addChild') {
    const { error } = await fetchAddMenu(params);
    if (!error) {
      window.$message?.success($t('common.updateSuccess'));
      closeDrawer();
      emit('submitted');
    }
  }
}

watch(visible, () => {
  if (visible.value) {
    handleInitModel();
    restoreValidation();
    getTreeselect();
  }
});

watch(
  () => model.value.routeName,
  () => {
    handleUpdateRoutePathByRouteName();
    handleUpdateI18nKeyByRouteName();
  }
);
</script>

<template>
  <NModal v-model:show="visible" :title="title" preset="card" class="w-800px">
    <NScrollbar class="h-480px pr-20px">
      <NForm ref="formRef" :model="model" :rules="rules" label-placement="left" :label-width="100">
        <NGrid responsive="screen" item-responsive>
          <NFormItemGi span="24" label="上级菜单" path="parentId">
            <NTreeSelect
              v-model:value="model.parentId"
              :options="menuOptions"
              key-field="menuId"
              label-field="menuName"
              :default-value="0"
              @update:value="handleUpdateParentId"
            />
          </NFormItemGi>
          <NFormItemGi span="24 m:12" :label="$t('page.manage.menu.menuType')" path="menuType">
            <NRadioGroup v-model:value="model.menuType" :disabled="disabledMenuType">
              <NRadio v-for="item in menuTypeOptions" :key="item.value" :value="item.value" :label="item.label" />
            </NRadioGroup>
          </NFormItemGi>
          <NFormItemGi span="24 m:12" :label="$t('page.manage.menu.menuName')" path="menuName">
            <NInput v-model:value="model.menuName" :placeholder="$t('page.manage.menu.form.menuName')" />
          </NFormItemGi>
          <NFormItemGi v-if="!showButton" span="24 m:12" :label="$t('page.manage.menu.routeName')" path="routeName">
            <NInput v-model:value="model.routeName" :placeholder="$t('page.manage.menu.form.routeName')" />
          </NFormItemGi>
          <NFormItemGi v-if="!showButton" span="24 m:12" :label="$t('page.manage.menu.routePath')" path="path">
            <NInput v-model:value="model.path" disabled :placeholder="$t('page.manage.menu.form.path')" />
          </NFormItemGi>
          <!--   pathParam、 layout和page 不参与提交，只用于构造component      -->
          <NFormItemGi
            v-if="model.menuType !== 'F'"
            span="24 m:12"
            :label="$t('page.manage.menu.pathParam')"
            path="pathParam"
          >
            <NInput v-model:value="model.pathParam" :placeholder="$t('page.manage.menu.form.pathParam')" />
          </NFormItemGi>
          <NFormItemGi v-if="showLayout" span="24 m:12" :label="$t('page.manage.menu.layout')" path="layout">
            <NSelect
              v-model:value="model.layout"
              :options="layoutOptions"
              :placeholder="$t('page.manage.menu.form.layout')"
            />
          </NFormItemGi>
          <NFormItemGi v-if="showPage" span="24 m:12" :label="$t('page.manage.menu.page')" path="page">
            <NSelect
              v-model:value="model.page"
              :options="pageOptions"
              :placeholder="$t('page.manage.menu.form.page')"
            />
          </NFormItemGi>
          <NFormItemGi span="24 m:12" :label="$t('page.manage.menu.order')" path="orderNum">
            <NInputNumber
              v-model:value="model.orderNum"
              class="w-full"
              :placeholder="$t('page.manage.menu.form.order')"
            />
          </NFormItemGi>
          <NFormItemGi v-if="!showButton" span="24 m:12" :label="$t('page.manage.menu.iconTypeTitle')" path="iconType">
            <NRadioGroup v-model:value="model.iconType">
              <NRadio
                v-for="item in menuIconTypeOptions"
                :key="item.value"
                :value="item.value"
                :label="$t(item.label)"
              />
            </NRadioGroup>
          </NFormItemGi>
          <NFormItemGi v-if="!showButton" span="24 m:12" :label="$t('page.manage.menu.icon')" path="icon">
            <template v-if="model.iconType === '1'">
              <NInput v-model:value="model.icon" :placeholder="$t('page.manage.menu.form.icon')" class="flex-1">
                <template #suffix>
                  <SvgIcon v-if="model.icon" :icon="model.icon" class="text-icon" />
                </template>
              </NInput>
            </template>
            <template v-if="model.iconType === '2'">
              <NSelect
                v-model:value="model.icon"
                :placeholder="$t('page.manage.menu.form.localIcon')"
                :options="localIconOptions"
              />
            </template>
          </NFormItemGi>
          <NFormItemGi span="24 m:12" :label="$t('page.manage.menu.perms')" path="perms">
            <NInput v-model:value="model.perms" :placeholder="$t('page.manage.menu.form.perms')" />
          </NFormItemGi>
          <NFormItemGi v-if="!showButton" span="24 m:12" :label="$t('page.manage.menu.menuStatus')" path="status">
            <NRadioGroup v-model:value="model.status">
              <NRadio
                v-for="item in specialEnableStatusOptions"
                :key="item.value"
                :value="item.value"
                :label="$t(item.label)"
              />
            </NRadioGroup>
          </NFormItemGi>
          <NFormItemGi v-if="!showButton" span="24 m:12" :label="$t('page.manage.menu.keepAlive')" path="keepAlive">
            <NRadioGroup v-model:value="model.keepAlive">
              <NRadio :value="true" :label="$t('common.yesOrNo.yes')" />
              <NRadio :value="false" :label="$t('common.yesOrNo.no')" />
            </NRadioGroup>
          </NFormItemGi>
          <!--          <NFormItemGi span="24 m:12" :label="$t('page.manage.menu.constant')" path="constant">-->
          <!--            <NRadioGroup v-model:value="model.constant">-->
          <!--              <NRadio :value="true" :label="$t('common.yesOrNo.yes')" />-->
          <!--              <NRadio :value="false" :label="$t('common.yesOrNo.no')" />-->
          <!--            </NRadioGroup>-->
          <!--          </NFormItemGi>-->
          <NFormItemGi v-if="!showButton" span="24 m:12" :label="$t('page.manage.menu.href')" path="href">
            <NInput v-model:value="model.href" :placeholder="$t('page.manage.menu.form.href')" />
          </NFormItemGi>
          <NFormItemGi v-if="!showButton" span="24 m:12" :label="$t('page.manage.menu.hideInMenu')" path="hideInMenu">
            <NRadioGroup v-model:value="model.hideInMenu">
              <NRadio :value="true" :label="$t('common.yesOrNo.yes')" />
              <NRadio :value="false" :label="$t('common.yesOrNo.no')" />
            </NRadioGroup>
          </NFormItemGi>
          <NFormItemGi
            v-if="model.hideInMenu"
            span="24 m:12"
            :label="$t('page.manage.menu.activeMenu')"
            path="activeMenu"
          >
            <NSelect
              v-model:value="model.activeMenu"
              :options="pageOptions"
              clearable
              :placeholder="$t('page.manage.menu.form.activeMenu')"
            />
          </NFormItemGi>
        </NGrid>
      </NForm>
    </NScrollbar>
    <template #footer>
      <NSpace justify="end" :size="16">
        <NButton @click="closeDrawer">{{ $t('common.cancel') }}</NButton>
        <NButton type="primary" @click="handleSubmit">{{ $t('common.confirm') }}</NButton>
      </NSpace>
    </template>
  </NModal>
</template>

<style scoped></style>
