<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">
      <!-- 核心：从第一个产品的 basicInfos 中遍历分组（A/B/C组） -->
      <view 
        class="compare-section" 
        v-for="group in getFirstProductGroups()" 
        :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">
          <!-- 遍历当前分组下的所有属性（factor） -->
          <view 
            class="compare-item" 
            :class="{ 'hidden-item': shouldHide(group.groupCode, factor.type) }" 
            v-for="factor in group.factors" 
            :key="factor.type"
          >
            <text class="item-label">{{ factor.typeName }}</text>
            <view class="item-values">
              <!-- 遍历所有产品，匹配当前分组+当前属性的内容 -->
              <view class="item-value" v-for="product in productPKInfoList" :key="product.planBizId">
                {{ getProductFactorValue(product, group.groupCode, factor.type) || '-' }}
              </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>
                <!-- 使用pdfjs打开 -->
                 <view class="popup" v-if="pdfShow">
                    <view class="popup-header">
                        <text>PDF预览</text>
                        <text class="close" @click="pdfShow = false">关闭</text>
                    </view>
                    <view class="popup-content">
                      <PdfViewer 
                        :pdfInfo="{
                          title: null,
                          url: viewFileUrl,
                          landscapeFlag:false
                        }"
                        :autoLoad="true" 
                        :lazyLoad="true"
                        :maxRetryCount="2"
                
                      />
                    </view>
            
                </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>
</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';
// 导入PDF查看器组件
import PdfViewer from '@/components/pdf-viewer/pdf-viewer.vue';
// 路由实例
const router = useRouter();
const route = useRoute();

// 后端返回的原始数据
const resultData = ref({});
// 配置分组列表（基本信息、适合人群等）
const configList = ref([]);
// 产品对比信息列表
const productPKInfoList = ref([]);
// 是否只看不同
const showOnlyDiff = ref(false);
// 查看文件的URL
const viewFileUrl = ref()
const pdfShow = ref(false)

// 根据分组编码获取对应的图标
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';
};
import {hshare} from '@/util/fiveshare';
const wxShare = (productIds,categoryId)=>{
	// H5 自定义分享
	  const shareLink = `${window.location.origin}/myPackageA/compare-result/compare-result?categoryId=${categoryId}&productIds=${productIds}`;
	
	  // 2. 分享标题（简洁明了，包含产品数量）
	  const shareTitle = `多款产品对比结果`;
	
	  // 3. 分享描述（突出对比价值）
	  const shareDesc = `包含核心参数对比，快速了解差异`;
	
	  // 4. 分享图标（建议用公司LOGO或产品相关图标，尺寸200x200px，HTTPS地址）
	  const shareIcon = `${window.location.origin}/static/mypoint_pic.png`;
	let data = {
		title: shareTitle,
		desc:shareDesc,
		link: shareLink, //分享链接
		imgUrl: shareIcon, //图片c
	}
	//安卓机型获取当前页面路径
	let url = window.location.href.split('#')[0];
	
	//ios机型获取当前页面路径
	let ua = navigator.userAgent.toLowerCase();
	let isWeixin = ua.indexOf('micromessenger') !== -1;
	if (isWeixin) {
		let isiOS = /(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent); //ios终端
	    if (isiOS && window.sessionStorage.getItem('firstEntryUrl')) {
	        url = window.sessionStorage.getItem('firstEntryUrl').split('#')[0];
	    }
	}
	hshare(data, url)
}
const getUrl = (fileUrl) => {
  if (!fileUrl) {
    uni.showToast({ title: '暂无文档', icon: 'none' });
    return;
  }

  // 区分环境：H5 端直接打开 URL，其他端用原下载逻辑
  if (uni.getSystemInfoSync().uniPlatform === 'web') {
    // H5 方案：用浏览器新窗口打开 PDF（依赖浏览器原生支持）
	pdfShow.value = true
    viewFileUrl.value = fileUrl
    // const opened = window.open(fileUrl, '_blank');
  } else {
    // 非 H5 端（小程序/APP）：保留原下载+打开逻辑
    uni.downloadFile({
      url: fileUrl,
      success: (res) => {
        if (res.statusCode === 200) {
          uni.openDocument({
            filePath: res.tempFilePath,
            showMenu: true,
            success: () => console.log('打开文档成功'),
            fail: (err) => {
              uni.showToast({ title: '打开失败，请重试', icon: 'none' });
              console.error('openDocument 失败：', err);
            }
          });
        } else {
          uni.showToast({ title: '下载失败', icon: 'none' });
        }
      },
      fail: (err) => {
        uni.showToast({ title: '下载失败，请检查网络', icon: 'none' });
        console.error('downloadFile 失败：', err);
      }
    });
  }
};

// 【核心1：获取第一个产品的分组列表（A/B/C组）】
// 所有产品的分组结构一致，取第一个产品的 basicInfos 作为分组源
const getFirstProductGroups = () => {
  if (productPKInfoList.value.length === 0) return [];
  return productPKInfoList.value[0].basicInfos || [];
};

// 【核心2：获取指定产品、指定分组、指定属性的内容】
const getProductFactorValue = (product, groupCode, factorType) => {
  // 1. 找到产品中当前分组（如A组-基本信息）
  const targetGroup = product.basicInfos.find(item => item.groupCode === groupCode);
  if (!targetGroup) return '';
  
  // 2. 找到分组中当前属性（如type=5-保障期限）
  const targetFactor = targetGroup.factors.find(item => item.type === factorType);
  return targetFactor ? targetFactor.content : '';
};


// 【核心3：判断属性是否所有产品都相同（“只看不同”逻辑）】
const shouldHide = (groupCode, factorType) => {
  // 未开启“只看不同”或只有1个产品，不隐藏
  if (!showOnlyDiff.value || productPKInfoList.value.length <= 1) return false;

  // 取第一个产品的属性值作为基准
  const firstProduct = productPKInfoList.value[0];
  const baseValue = getProductFactorValue(firstProduct, groupCode, factorType);
  
  // 归一化空值（避免“/”“空字符串”视为不同）
  const normalize = (val) => val === '' || val === '/' ? '无数据' : val;
  const baseNormalized = normalize(baseValue);

  // 检查所有产品的当前属性值是否与基准一致
  const allSame = productPKInfoList.value.every(product => {
    const currentValue = getProductFactorValue(product, groupCode, factorType);
    return normalize(currentValue) === baseNormalized;
  });

  // 所有产品相同则隐藏，否则显示
  return allSame;
};


// 前往PK选择页
const navigateToPKPage = () => {
	uni.navigateBack()
};

// 初始化数据
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?.productPKInfoList) {
		  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;
}
.popup {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: #fff;
    z-index: 999;
    display: flex;
    flex-direction: column;
}
</style>
