<template>
  <view class="compare-result-page">
    <view class="page-header">
      <text class="page-title">产品对比</text>
      <button class="toggle-btn" @click="showOnlyDiff = !showOnlyDiff">
        <text>{{ showOnlyDiff ? '显示全部' : '只看不同' }}</text>
      </button>
    </view>
    
    <!-- 已选产品 -->
    <view class="selected-products">
      <view class="product-item" v-for="(product, index) in productPKInfoList" :key="product.planBizId">
        <view class="product-info">
          <view class="product-name">{{ product.name }} </view>
          <view class="company-name">{{ product.companyName }}</view>
        <view><uni-tag :text="product.categoryName" size="small" type="primary"></uni-tag></view>
        </view>
		<view class="change-product" @click="navigateToPKPage">
			<uni-icons type="loop" size="16" color="#20269B"></uni-icons>
			<view
          v-if="productPKInfoList.length > 1">更换</view>
		</view>
      </view>
    </view>
    
    <!-- 对比内容（按group分组展示） -->
    
    <!-- 对比内容：从 productPKInfoList.basicInfos 提取分组渲染 -->
<view class="compare-content" v-if="productPKInfoList.length > 0 && renderGroups.length > 0">
  <view 
    class="compare-section" 
    v-for="group in renderGroups" 
    :key="group.groupCode"
  >
    <view class="section-header">
      <uni-icons 
        :type="getGroupIcon(group.groupCode)" 
        size="22" 
        :color="getGroupColor(group.groupCode)"
      ></uni-icons>
      <text class="section-title">{{ group.groupName }}</text>
    </view>
    <view class="section-content">
      <view 
        class="compare-item" 
        :class="{ 'hidden-item': shouldHide(field.fieldBizId) }" 
        v-for="field in group.fields" 
        :key="field.fieldBizId"
      >
        <text class="item-label">{{ field.label }}</text>
        <view class="item-values">
          <view class="item-value" v-for="product in productPKInfoList" :key="product.planBizId">
            {{ getProductFieldValue(product, field.fieldBizId) || '-' }}
          </view>
        </view>
      </view>
    </view>
  </view>


      <!-- 产品彩页分组（单独处理，从 planFiles 提取） -->
      <view class="compare-section" id="product-file-group">
        <view class="section-header">
          <uni-icons type="image" size="22" color="#cc66ff"></uni-icons>
          <text class="section-title">产品彩页</text>
        </view>
        <view class="section-content">
          <view class="compare-item" >
            <text class="item-label">产品文件</text>
            <view class="item-values">
              <view class="product-file-list" v-for="product in productPKInfoList" :key="product.planBizId">
                <view class="no-file" v-if="!product.planFiles || product.planFiles.length === 0">
                  -
                </view>
                <view 
                  class="file-item" 
                  v-for="(file, idx) in (product.planFiles || [])" 
                  :key="idx"
                  @click="getUrl(file.fileUrl)"
                >
                  <uni-icons type="file-pdf" size="18" color="#cc66ff"></uni-icons>
                  <text class="file-name">{{ file.fileName }}</text>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 无产品时的空状态 -->
    <view class="empty-state" v-else>
      <uni-icons type="empty" size="60" color="#ccc"></uni-icons>
      <text class="empty-text">暂无对比产品数据</text>
    </view>
  </view>
  <!-- 放在 </view> 最后，</template> 之前 -->
  <!-- PDF 查看弹窗 -->
  <!-- 调试用 -->
  <view v-if="showPdfModal">Debug URL: {{ currentPdfUrl }}</view>
  <uni-popup 
    ref="pdfPopupRef" 
    :mask-click="true" 
    type="bottom" 
    @change="onPopupChange"
  >
    <view class="pdf-modal-container">
      <!-- 关闭按钮 -->
      <view class="modal-header">
        <button class="close-btn" @click="closePdfModal">✕</button>
      </view>
      
      <!-- PDF 查看器 -->
		<view class="pdf-viewer-wrapper" v-if="showPdfModal && currentPdfUrl">
		  <PdfViewer 
			:pdfInfo="{ url: currentPdfUrl }"
			:autoLoad="true"
			:lazyLoad="false"
			:maxRetryCount="2"
			@loadComplete="handlePdfLoadComplete"
			@loadError="handlePdfLoadError"
			@pageChange="handlePageChange"
		  />
		</view>
    </view>
  </uni-popup>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import common from '@/common/common';
import api from '@/api/api';
import PdfViewer from '@/components/pdf-viewer/pdf-viewer.vue';
import { onBeforeUnmount } from 'vue';
import uniPopup from '@dcloudio/uni-ui/lib/uni-popup/uni-popup.vue';
import { hshare } from '@/util/fiveshare';

const pdfPopupRef = ref();
const router = useRouter();
const route = useRoute();

// 原始数据
const resultData = ref({});
const configList = ref([]); // ← 新增：用于定义页面结构
const productPKInfoList = ref([]);
const showOnlyDiff = ref(false);
const currentPdfUrl = ref('');
const showPdfModal = ref(false);

// 【✅ 关键修正1：构建 fieldBizId → 字段元信息 的映射】
const fieldMetaMap = ref(new Map()); // fieldBizId => { cnName, groupCode }

// 【✅ 关键修正2：初始化 configList 并构建映射】
const initConfigStructure = (configs) => {
  configList.value = configs;
  const map = new Map();
  configs.forEach(group => {
    group.fieldList.forEach(field => {
      map.set(field.fieldBizId, {
        cnName: field.fieldCnName,
        groupCode: group.groupCode,
        groupName: group.groupName
      });
    });
  });
  fieldMetaMap.value = map;
};

// 【✅ 关键修正3：获取标准化的分组+字段结构（用于渲染）】
const renderGroups = computed(() => {
  return configList.value.map(group => ({
    groupCode: group.groupCode,
    groupName: group.groupName,
    fields: group.fieldList.map(field => ({
      fieldBizId: field.fieldBizId,
      label: field.fieldCnName
    }))
  }));
});

// 【✅ 关键修正4：根据 fieldBizId 获取产品值】
const getProductFieldValue = (product, fieldBizId) => {
  for (const basicInfo of product.basicInfos || []) {
    const factor = basicInfo.factors?.find(f => f.type === fieldBizId);
    if (factor) return factor.content || '';
  }
  return ''; // 未找到返回空
};

// 【✅ 关键修正5：判断是否应隐藏（只看不同）】
const shouldHide = (fieldBizId) => {
  if (!showOnlyDiff.value || productPKInfoList.value.length <= 1) return false;

  const normalize = (val) => (val === '' || val === '/' ? '无数据' : val);
  const baseValue = normalize(getProductFieldValue(productPKInfoList.value[0], fieldBizId));

  return productPKInfoList.value.every(product => {
    return normalize(getProductFieldValue(product, fieldBizId)) === baseValue;
  });
};

// 其余方法保持不变（图标、颜色、PDF、分享等）
const getGroupIcon = (groupCode) => {
  const iconMap = { A: 'info', B: 'auth', C: 'star', D: 'image' };
  return iconMap[groupCode] || 'help';
};
const getGroupColor = (groupCode) => {
  const colorMap = { A: '#20269B', B: '#00cc66', C: '#ff9900', D: '#cc66ff' };
  return colorMap[groupCode] || '#999';
};

const wxShare = (productIds, categoryId) => {
  const shareLink = `${window.location.origin}/myPackageA/compare-result/compare-result?categoryId=${categoryId}&productIds=${productIds}`;
  const shareTitle = `多款产品对比结果`;
  const shareDesc = `包含核心参数对比，快速了解差异`;
  const shareIcon = `${window.location.origin}/static/mypoint_pic.png`;
  let data = { title: shareTitle, desc: shareDesc, link: shareLink, imgUrl: shareIcon };
  let url = window.location.href.split('#')[0];
  let ua = navigator.userAgent.toLowerCase();
  let isWeixin = ua.indexOf('micromessenger') !== -1;
  if (isWeixin) {
    let isiOS = /(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent);
    if (isiOS && window.sessionStorage.getItem('firstEntryUrl')) {
      url = window.sessionStorage.getItem('firstEntryUrl').split('#')[0];
    }
  }
  hshare(data, url);
};

const navigateToPKPage = () => {
  uni.navigateBack();
};

const getUrl = (fileUrl) => {
  if (!fileUrl) {
    uni.showToast({ title: '暂无文档', icon: 'none' });
    return;
  }
  uni.showLoading({ title: '加载PDF中...' });
  currentPdfUrl.value = fileUrl;
  showPdfModal.value = true;
  setTimeout(() => {
    pdfPopupRef.value?.open?.();
    uni.hideLoading();
  }, 100);
};

const closePdfModal = () => {
  showPdfModal.value = false;
  setTimeout(() => pdfPopupRef.value?.close?.(), 100);
};

const onPopupChange = (e) => {
  if (!e.show && showPdfModal.value) showPdfModal.value = false;
};

onBeforeUnmount(() => {
  if (pdfPopupRef.value) pdfPopupRef.value.close();
});

// 【✅ 关键修正6：初始化时同时处理 configList 和 productPKInfoList】
onMounted(() => {
  const { productIds, categoryId } = route.query;
  if (!productIds || !categoryId) {
    uni.showToast({ title: '缺少对比参数', icon: 'none' });
    return;
  }

  const params = {
    category: categoryId,
    planBizIdList: productIds.split(',')
  };

  let ua = navigator.userAgent.toLowerCase();
  let isWeixin = ua.indexOf('micromessenger') !== -1;

  api.getProductPKInfo(params).then(res => {
    if (res.success && res.data) {
      // ✅ 同时保存 configList 和 product 列表
      initConfigStructure(res.data.configList || []);
      productPKInfoList.value = res.data.productPKInfoList || [];

      if (isWeixin) wxShare(productIds, categoryId);
    } else {
      common.errorDialog(1, res.message || '获取对比数据失败');
    }
  });
});
</script>

<style scoped>
/* 基础样式与之前保持一致，重点适配数据展示 */
.compare-result-page {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 120rpx; /* 预留底部空间 */
}

/* 页面头部 */
.page-header {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20rpx;
  background-color: #fff;
  border-bottom: 1px solid #eee;
  position: relative;
}


.page-title {
  font-size: 34rpx;
  font-weight: bold;
  color: #333;
}

.toggle-btn {
  position: absolute;
  right: 20rpx;
  background: transparent;
  color: #20269B;
  font-size: 26rpx;
  padding: 0 10rpx;
}

/* 已选产品 */
.selected-products {
  background-color: #fff;
  padding: 15rpx;
  border-bottom: 1px solid #eee;
  overflow-x: auto;
  white-space: nowrap;
}

.product-item {
  display: inline-flex;
  align-items: flex-end;
  padding: 10rpx 15rpx;
  border-radius: 10rpx;
  background-color: #f5f7fa;
  margin-right: 15rpx;
}

.product-name {
  font-size: 26rpx;
  font-weight: 500;
  color: #333;
  margin-right: 10rpx;
  max-width: 260rpx;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.company-name {
  font-size: 22rpx;
  color: #666;
  margin-right: 10rpx;
}


.change-product{
	display: flex;
	align-items: center;
	font-size: 24rpx;
	color: #20269B;
}
/* 对比内容 */
.compare-content {
  padding: 15rpx;
}

.compare-section {
  background-color: #fff;
  border-radius: 15rpx;
  margin-bottom: 15rpx;
  overflow: hidden;
}

.section-header {
  display: flex;
  align-items: center;
  padding: 20rpx;
  background-color: #f5f7fa;
  border-bottom: 1px solid #eee;
}

.section-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-left: 10rpx;
}

.section-content {
  padding: 10rpx 0;
}

.compare-item {
  display: flex;
  padding: 20rpx;
  border-bottom: 1px solid #eee;
}

.compare-item:last-child {
  border-bottom: none;
}

.hidden-item {
  display: none; /* "只看不同"时隐藏相同项 */
}

.item-label {
  width: 200rpx;
  font-size: 26rpx;
  color: #666;
  font-weight: 500;
}

.item-values {
  flex: 1;
  display: flex;
  justify-content: space-between;
    gap: 10rpx;
}

.item-value {
  flex: 1;
  font-size: 26rpx;
  color: #333;
  padding: 0 10rpx;
  word-break: break-word;
  line-height: 1.5; /* 多行文本时更美观 */
}

/* 产品彩页按钮样式 */
.item-value:has(.brochure-btn) {
  display: flex;
  justify-content: center;
  align-items: center;
}

.brochure-btn {
  background-color: #20269B;
  color: #fff;
  font-size: 24rpx;
  padding: 8rpx 15rpx;
  border-radius: 5rpx;
}

.brochure-btn:disabled {
  background-color: #ccc;
}

.product-info{
	display: flex;
	flex-direction: column;
}
.mini-btn{
	white-space: nowrap;
}
#product-file-group {
  margin-top: 15rpx; /* 与其他分组保持间距 */
}
.product-file-list {
  flex: 1;
  padding: 0 10rpx;
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}
.file-item {
  display: flex;
  align-items: center;
  gap: 8rpx;
  padding: 6rpx 0;
  color: #20269B;
  font-size: 24rpx;
  cursor: pointer;
  word-break: break-all;
}
.no-file {
  flex: 1;
  padding: 0 10rpx;
  color: #999;
  font-size: 24rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}
.pdf-modal-container {
  width: 100vw;
  height: 90vh; /* 占屏 90% */
  background: #fff;
  border-top-left-radius: 20rpx;
  border-top-right-radius: 20rpx;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.modal-header {
  padding: 20rpx;
  text-align: right;
}

.close-btn {
  width: 60rpx;
  height: 60rpx;
  font-size: 36rpx;
  background: #f5f5f5;
  border-radius: 50%;
  border: none;
  color: #999;
  display: flex;
  justify-content: center;
	align-items: center;
}

.pdf-viewer-wrapper {
  flex: 1;
  width: 100%;
  overflow: hidden;
}
</style>