<template>
  <div>
    <el-select v-model="jumpPageId" style="width: 300px;" placeholder="请选择跳转页面" @change="jumpPageIdChange">
      <el-option v-for="item in miniPageList" :key="item.id" :label="item.name" :value="item.id"></el-option>
    </el-select>
    <div class="tips">选填，轮播图点击后跳转的目标页面</div>
    <el-select v-model="goodsId" style="width: 300px;" placeholder="请选择具体菜品，可搜索" clearable filterable remote
      :remote-method="remoteMethod" :loading="loading" v-if="jumpPageId && isIncludeFlag" @change="goodsIdChange">
      <el-option v-for="item in goodsList" :key="item.id" :label="item.name" :value="item.id"></el-option>
    </el-select>
  </div>
</template>

<script setup>
import _ from 'lodash';
import { ref, onMounted, watch } from 'vue';
import { pointsGoodsPage } from '@/api/points/index.js'
import API from '@/views/application/list/advertisement/indexconfig/api';
import { packageGet, getGbWarePage } from '@/api/market/ware'
import productApi from '@/api/product';

const props = defineProps({
  includesNames: {
    type: Array,
    default: () => ([])
  }
});

const jumpPageId = defineModel({
  type: [String, Number],
  default: ''
});

const jumpPageName = ref('');
const isIncludeFlag = ref(false);

function checkIsInclude() {
  // 增加边界判断：避免includesNames为空或item.id不存在导致的错误
  if (!jumpPageId.value || !Array.isArray(props.includesNames) || props.includesNames.length === 0) {
    return false;
  }
  // 提取id数组并判断包含关系
  const idList = props.includesNames.map(item => item?.id); // 可选链避免item.id不存在
  return _.includes(idList, jumpPageId.value);
}

watch(jumpPageId, async (newVal, oldVal) => {
  if (newVal) {
    await nextTick()
    watchJumpPageIdChange(newVal)
  }
}, {
  immediate: true, // 可选：首次加载时立即执行一次（根据需求决定）
  deep: false // 无需深度监听，因为值是String/Number
})

const miniPageList = ref([]);

// 获取小程序跳转页面列表
async function getList() {
  try {
    const res = await API.miniAppPagesPage({ page: 1, size: 999 });
    miniPageList.value = res.records;
  } catch (error) {
    console.log(error);
  }
}

function jumpPageIdChange(value) {
  goodsId.value = '';
  extendParam.value = ''
  jumpPageName.value = miniPageList.value.find(item => item.id == value)?.name || '';
  // 清空具体菜品选择
  if (checkIsInclude()) {
    isIncludeFlag.value = true;
    getGoodsList()
  } else {
    isIncludeFlag.value = false;
  }
}

// watch监听jumpPageId变化
async function watchJumpPageIdChange(value) {
  if (miniPageList.value.length === 0) {
    await getList()
  }
  // 清空具体菜品选择
  if (checkIsInclude()) {
    jumpPageName.value = miniPageList.value.find(item => item.id == value)?.name || '';
    isIncludeFlag.value = true;
    getGoodsList()
  } else {
    isIncludeFlag.value = false;
  }
}

const loading = ref(false);
const goodsList = ref([]); // 具体菜品列表
const goodsId = defineModel('goodsId', {
  type: [String, Number],
  default: ''
});
const extendParam = defineModel('extendParam', {
  type: String,
  default: ''
});

// 监听extendParam的变化，解析并赋值给goodsId
watch(extendParam, async (newExtendParam, oldExtendParam) => {
  // console.log('extendParam变化：', newExtendParam);

  // 1. 空值判断：如果extendParam为空，重置goodsId
  if (!newExtendParam) {
    goodsId.value = '';
    return;
  }

  // 2. 解析字符串：匹配goodsId=xxx的格式
  // 正则表达式说明：匹配goodsId=后接任意字符（非空），直到字符串结束或遇到&等分隔符
  const reg = /goodsId=([^&]+)/;
  const matchResult = newExtendParam.match(reg);

  // 3. 提取值并赋值：匹配成功则赋值，否则重置
  if (matchResult && matchResult[1]) {
    let extractedGoodsId = matchResult[1];

    // 尝试将 id 转为数字（如果看起来像数字）以保持与后端 id 类型一致
    const numeric = Number(extractedGoodsId);
    const parsedId = !Number.isNaN(numeric) ? numeric : extractedGoodsId;

    // 确保 options 已加载，这样 el-select 能根据 value 匹配到对应的 label
    try {
      await getGoodsList();
    } catch (e) {
      // ignore
    }

    // 统一使用字符串类型的 id 以保证与 options 中的 value 匹配
    goodsId.value = String(parsedId);
  } else {
    goodsId.value = ''; // 匹配失败时清空
  }
}, {
  immediate: true, // 初始加载时立即执行一次解析
  deep: false // 字符串是基本类型，无需深度监听
});

// 具体菜品选择变化
function goodsIdChange(value) {
  // 设置扩展参数，处理清空情况以避免出现 'undefined'
  if (value === null || typeof value === 'undefined' || value === '') {
    extendParam.value = '';
    goodsId.value = '';
    return;
  }

  extendParam.value = `goodsId=${value}`;
}

function remoteMethod(value) {
  getGoodsList(value);
}

// 获取商品咧白哦
async function getGoodsList(value = '') {
  try {
    // 获取套餐列表
    loading.value = true;
    let list = [];
    if (jumpPageName.value == '套餐推广商品详情页') {
      const res = await packageGet({ page: 1, size: 999, packageName: value });
      list = res.records.map(item => ({
        id: String(item.id),
        name: item.packageName
      }));
    } else if (jumpPageName.value == '商品拼团详情页') {
      const res = await getGbWarePage({ page: 1, size: 999, wareName: value });
      list = res.records.map(item => ({
        id: String(item.id),
        name: item.wareName
      }));
    } else if (jumpPageName.value == '点餐商品详情弹窗页') {
      const res = await productApi.getPage({ name: value });
      list = res.records.map(item => ({
        id: String(item.id),
        name: item.name
      }));
    } else if (jumpPageName.value == '积分商品详情页面') {
      const res = await pointsGoodsPage({ page: 1, size: 999 });
      list = res.records.map(item => ({
        id: String(item.id),
        name: item.goodsName
      }));
    }
    goodsList.value = list;
    loading.value = false;
  } catch (error) {
    console.log(error);
    loading.value = false;
  }
}

onMounted(() => {
  getList()
})
</script>

<style scoped lang="scss">
.tips {
  font-size: 14px;
  color: #999;
}
</style>