<template>
  <div class="link-path-editor">

    <DatabaseOutlined class="icon" />

    <a-input
      :value="displayPath"
      readonly
      placeholder="点击设置跳转路径"
      class="path-trigger"
      @click="openModal"
    >
      <template #suffix>
        <EditOutlined class="trigger-icon" @click.stop="openModal" />
      </template>
    </a-input>

    <a-modal
      v-model:open="modalVisible"
      title="编辑跳转路径"
      :width="720"
      @cancel="onModalCancel"
      @ok="onModalOk"
    >
      <a-form layout="vertical" class="modal-form">
        <a-form-item label="路径类型">
          <div class="path-selector">
            <a-select 
              v-model:value="pathType" 
              style="width: 120px; margin-right: 8px"
            >
              <a-select-option v-if="!props.noParams" value="dynamic-list">动态列表页面</a-select-option>
              <a-select-option v-if="!props.noParams" value="dynamic-detail">动态详情页面</a-select-option>
              <a-select-option value="internal">程序内置页面</a-select-option>
              <a-select-option value="custom">自定义输入</a-select-option>
            </a-select>
            
            <!-- 动态页面地址 -->
            <a-select 
              v-if="pathType === 'dynamic-list' || pathType === 'dynamic-detail'"
              v-model:value="localPageConfigName"
              style="flex: 1"
              placeholder="请选择动态页面"
            >
              <a-select-option 
                v-for="page in pageListFiltered" 
                :key="page.name" 
                :value="page.name"
              >
                {{ page.title }} ({{ page.name }})
              </a-select-option>
            </a-select>
            
            <!-- 程序内置页面 -->
            <a-select 
              v-else-if="pathType === 'internal'"
              v-model:value="linkPath"
              style="flex: 1"
              placeholder="请选择内置页面"
            >
              <a-select-option 
                v-for="page in internalPages" 
                :key="page.path" 
                :value="page.path"
              >
                {{ page.path }}
              </a-select-option>
            </a-select>
            
            <!-- 自定义输入 -->
            <a-textarea
              v-else-if="pathType === 'custom'"
              v-model:value="linkPath"
              placeholder="请输入跳转路径, 可用表达式，请参考源码设置表达式"
              style="flex: 1"
              :auto-size="{ minRows: 2, maxRows: 5 }"
            />
          </div>
        </a-form-item>
        <a-form-item v-if="!props.noParams && pathType !== 'dynamic-list' && pathType !== 'dynamic-detail'" label="参数设置">
          <KeyValueEditor
            :modelValue="localParams"
            :forceOneLevel="true"
            :defaultCreateTemplate="{ key: '', value: '', type: 'string' }"
            @update:modelValue="localParams = $event"
          />
        </a-form-item>
      </a-form>
    </a-modal>

  </div>
</template>

<script setup lang="ts">
import { inject, ref, watch, computed, type Ref } from 'vue';
import { EditOutlined, DatabaseOutlined } from '@ant-design/icons-vue';
import KeyValueEditor from './KeyValueEditor.vue';
import type { IHomeCommonCategoryDefine } from '@/pages/article/data/CommonCategoryDefine';
import PagesJson from '@/pages.json';
import { CommonCategoryDetailPath, CommonCategoryListPath } from '@/pages/article/data/CommonCategoryPathDefine';

/** 从 URL 字符串中解析路径和 ? 后面的查询参数 */
function parseUrlParams(url: string): { path: string; params: Record<string, string> } {
  if (!url || typeof url !== 'string') return { path: '', params: {} };
  const i = url.indexOf('?');
  if (i === -1) return { path: url.trim(), params: {} };
  const path = url.slice(0, i).trim();
  const search = url.slice(i + 1);
  const params: Record<string, string> = {};
  for (const pair of search.split('&')) {
    const eq = pair.indexOf('=');
    const key = eq === -1 ? pair : pair.slice(0, eq);
    const value = eq === -1 ? '' : pair.slice(eq + 1);
    if (key) {
      try {
        params[decodeURIComponent(key.trim())] = decodeURIComponent(value);
      } catch {
        params[key.trim()] = value;
      }
    }
  }
  return { path, params };
}

/** 根据路径和参数对象拼接成 URL 字符串（? 后面部分） */
function buildUrlWithParams(path: string, params: Record<string, string>): string {
  const pathTrim = (path || '').trim();
  const keys = Object.keys(params).filter(
    (k) => k != null && String(params[k]) !== ''
  );
  if (keys.length === 0) return pathTrim;
  const search = keys
    .map((k) => encodeURIComponent(k) + '=' + encodeURIComponent(params[k]))
    .join('&');
  return pathTrim + '?' + search;
}

// 定义props
const props = defineProps<{
  /** 跳转路径，可为带查询参数的完整 URL 字符串（? 后部分会被解析为参数） */
  modelValue?: string | undefined;
  /**
   * 是否禁用参数设置
   * @default false
   */
  noParams?: boolean | undefined;
}>();
const emit = defineEmits<{
  (e: 'update:modelValue', value: string): void;
}>();

const pageList = inject<Ref<(IHomeCommonCategoryDefine['page'][0])[]>>('pageList', ref([]));
const pageListFiltered = computed(() => {
  if (!pageList.value) 
    return [];
  switch (pathType.value) {
    case 'dynamic-list':
      return pageList.value.filter((page) => page.content.type === 'CommonList');
    case 'dynamic-detail':
      return pageList.value.filter((page) => page.content.type === 'Details');
    default:
      return [];
  }
});
const modalVisible = ref(false);

// 触发框显示文案：有值时显示路径，否则占位
const displayPath = computed(() => {
  const v = props.modelValue;
  if (v == null || String(v).trim() === '') return '';
  return String(v).trim();
});

// 跳转路径类型
const pathType = ref<'dynamic-list' | 'dynamic-detail' | 'internal' | 'custom'>('custom');
// 跳转路径
const linkPath = ref('');
const localPageConfigName = ref('');
const localParams = ref<Record<string, string>>({});

// 从PagesJson中提取内置页面
const internalPages = computed(() => {
  if (!PagesJson || !PagesJson.pages) {
    return [];
  }
  return PagesJson.pages.map((page: any) => ({
    path: "/" + page.path
  }));
});

// 监听 modelValue：从 URL 字符串解析路径与 ? 后参数
watch(
  () => props.modelValue,
  (newValue) => {
    const urlStr = typeof newValue === 'string' ? newValue : '';
    const { path, params } = parseUrlParams(urlStr);
    linkPath.value = path;
    localParams.value = params;
    if (linkPath.value === CommonCategoryListPath) {
      pathType.value = 'dynamic-list';
      localPageConfigName.value = localParams.value.pageConfigName || '';
    } else if (linkPath.value === CommonCategoryDetailPath) {
      pathType.value = 'dynamic-detail';
      localPageConfigName.value = localParams.value.pageConfigName || '';
    } else  if (linkPath.value.startsWith('/pages/')) {
      pathType.value = 'internal';
    } else {
      pathType.value = 'custom';
    }
  },
  { deep: true, immediate: true }
);

// 根据 modelValue 重置本地状态（取消时恢复）
function resetFromModelValue() {
  const urlStr = typeof props.modelValue === 'string' ? props.modelValue : '';
  const { path, params } = parseUrlParams(urlStr);
  linkPath.value = path;
  localParams.value = params;
  if (linkPath.value === CommonCategoryListPath) {
    pathType.value = 'dynamic-list';
    localPageConfigName.value = localParams.value.pageConfigName || '';
  } else if (linkPath.value === CommonCategoryDetailPath) {
    pathType.value = 'dynamic-detail';
    localPageConfigName.value = localParams.value.pageConfigName || '';
  } else if (linkPath.value.startsWith('/pages/')) {
    pathType.value = 'internal';
  } else {
    pathType.value = 'custom';
  }
}

// 更新链接：输出为带 ? 参数的完整 URL 字符串
const updateLink = () => {
  if (props.noParams) {
    emit('update:modelValue', linkPath.value);
    return;
  }
  if (pathType.value === 'dynamic-list') {
    localParams.value = {
      pageConfigName: localPageConfigName.value || '',
    };
    linkPath.value = CommonCategoryListPath;
  } else if (pathType.value === 'dynamic-detail') {
    localParams.value = {
      pageConfigName: localPageConfigName.value || '',
    };
    linkPath.value = CommonCategoryDetailPath;
  }
  emit('update:modelValue', buildUrlWithParams(linkPath.value, localParams.value));
};

function openModal() {
  modalVisible.value = true;
}

function onModalCancel() {
  resetFromModelValue();
  modalVisible.value = false;
}

function onModalOk() {
  updateLink();
  modalVisible.value = false;
}
</script>

<style lang="scss" scoped>
.link-path-editor {
  display: flex;
  align-items: center;
  gap: 8px;

  .icon {
    color: #006cc5;
    font-size: 16px;
  }

  .path-trigger {
    cursor: pointer;
    :deep(.ant-input) {
      cursor: pointer;
    }
    .trigger-icon {
      cursor: pointer;
      color: rgba(0, 0, 0, 0.45);
      &:hover {
        color: var(--ant-primary-color);
      }
    }
  }
}
.modal-form .path-selector {
  display: flex;
  align-items: center;
}
</style>