<template>
  <view class="module-container">
    <!-- 内容区域 -->
    <view class="content">
      <!-- 加载状态 -->
      <view v-if="loading" class="loading">
        <view class="spinner"></view>
        <text>加载中...</text>
      </view>
      <!-- 1. 公司介绍（直接显示单个PDF） -->
      <view v-if="!loading && currentType === 1 && companyPdf.urls" class="pdf-single">
		      <!-- 当前Tab的PDF列表 -->
		            <view 
		              v-for="(url, index) in currentPdf.urls" 
		              :key="index" 
		              class="pdf-item-container"
		            >
					  <PdfViewer 
						  :pdfInfo="{
							title: null,
							url: url
						  }"
						  :autoLoad="index === 0" 
						  :lazyLoad="true"
						  :maxRetryCount="2"
						  @loadComplete="handlePdfLoadComplete"
						  @loadError="handlePdfLoadError"
						  @pageChange="handlePageChange"
						/>
		            </view>
      </view>

      <!-- 2-4. 带Tab的模块 -->
      <view v-if="!loading && currentType >= 2 && currentType <= 4">
        <!-- Tab切换栏 -->
        <view class="tab-bar">
          <view 
            v-for="(tab, index) in filteredCurrentTabs" 
            :key="tab.id"
            class="tab-item"
            :class="{ active: activeTab === index }"
            @click="switchTab(index)"
          >
            <text class="tab-text">{{ tab.title }}</text>
            <view class="tab-indicator" v-if="activeTab === index"></view>
          </view>
        </view>

        <!-- Tab对应的PDF内容 -->
        <view class="pdf-tab-content" v-if="currentPdf.type === 'showURL'">
          <template v-if="filteredCurrentTabs.length > 0 && currentPdf.urls">
            <!-- 当前Tab的PDF列表 -->
            <view 
              v-for="(url, index) in currentPdf.urls" 
              :key="index" 
              class="pdf-item-container"
            >
			  <PdfViewer 
				  :pdfInfo="{
					title: null,
					url: url,
					landscapeFlag:currentPdf.landscapeFlag
				  }"
				  :autoLoad="index === 0" 
				  :lazyLoad="true"
				  :maxRetryCount="2"
				  @loadComplete="handlePdfLoadComplete"
				  @loadError="handlePdfLoadError"
				  @pageChange="handlePageChange"
				/>
            </view>
          </template>
          <template v-else>
            <view class="pdf-empty">暂无访问权限</view>
          </template>
        </view>
        
        <!-- 显示产品搜索组件 -->
        <view class="pdf-tab-content" v-if="currentPdf.type === 'showPage'">
          <productListVue/>
        </view>
      </view>

      <!-- 错误状态 -->
      <view v-if="!loading && (currentType < 1 || currentType > 4)" class="error">
        <text>无效的模块类型</text>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import api from "@/api/api";
import productListVue from '@/myPackageA/product-list/product-list.vue';	
// 导入PDF查看器组件
import PdfViewer from '@/components/pdf-viewer/pdf-viewer.vue';

// ========================== 类型定义 ==========================
interface PdfItem {
  id: string;
  title: string;
  urls: string[];
  type: string;
  landscapeFlag?:boolean;
}

interface PermissionRight {
  key: string;
}

interface PermissionItem {
  key: string;
  rights: PermissionRight[];
}

// ========================== 响应式数据 ==========================
const OSS_BASE_URL = 'https://csf-doc-center.oss-cn-shanghai-finance-1-pub.aliyuncs.com';
const currentType = ref<number>(1);
const loading = ref(true);
const activeTab = ref(0);
const currentPdf = ref<PdfItem>({ id: '', title: '', urls: [], type: '' ,landscapeFlag:false});
const permissionList = ref<PermissionItem[]>([]);

// 公司介绍PDF
const companyPdf = ref<PdfItem>({
  id: 'company',
  title: '公司介绍',
  // urls: Array.from({ length: 21 }, (_, i) => 
  //   `${OSS_BASE_URL}/public/company-intro_part${i + 1}.pdf`
  // ),
  urls: [`${OSS_BASE_URL}/public/company-intro.pdf`],
  type: 'showURL'
});

// 其他配置保持不变...
const rawTabConfig = ref<Record<number, PdfItem[]>>({
  2: [ 
    { 
      id: 'case1', 
      title: '规划案例', 
      urls: [
        `${OSS_BASE_URL}/cases/planning.pdf`,
      ], 
      type: 'showURL' ,
    },
    { 
      id: 'case2', 
      title: '团财案例', 
      urls: [
        `${OSS_BASE_URL}/cases/CorporateServiceDeliveryCase-GroupandPropertyInsurance.pdf`
      ], 
      type: 'showURL' ,
    }
  ],
  3: [ 
    { 
      id: 'product2', 
      title: '港险分析', 
      urls: [
        `${OSS_BASE_URL}/products/hk-analysis-20260115.pdf`,
      ], 
      type: 'showURL' ,
	  landscapeFlag:true
    },
    { 
      id: 'product1', 
      title: '港险明细', 
      urls: [
        `${OSS_BASE_URL}/products/hk-detail-20260115.pdf`,
      ], 
      type: 'showURL' ,
	  landscapeFlag:true
    },
    { 
      id: 'product3', 
      title: '产品对比', 
      urls: [], 
      type: 'showPage' 
    },
  ],
  4: [ 
    { 
      id: 'policy1', 
      title: '个险政策', 
      urls: [
        `${OSS_BASE_URL}/policies/individual-policy.pdf`
      ], 
      type: 'showURL' 
    },
    { 
      id: 'policy2', 
      title: '家办政策', 
      urls: [
        `${OSS_BASE_URL}/policies/group-policy.pdf`,
      ], 
      type: 'showURL' 
    },
    { 
      id: 'policy3', 
      title: '介绍费政策', 
      urls: [
        `${OSS_BASE_URL}/policies/commission-policy.pdf`
      ], 
      type: 'showURL' 
    }
  ]
});

const typeToPermissionKey = ref<Record<number, string>>({
  2: 'cases',
  3: 'products',
  4: 'policies'
});

// ========================== 事件处理 ==========================
const handlePdfLoadComplete = (url: string, pageCount: number) => {
  console.log(`PDF加载完成: ${url}, 共 ${pageCount} 页`);
};

const handlePdfLoadError = (url: string, error: Error) => {
  console.error(`PDF加载失败: ${url}`, error);
  uni.showToast({
    title: 'PDF加载失败',
    icon: 'none',
    duration: 2000
  });
};

const handlePageChange = (currentPage: number, totalPages: number) => {
  console.log(`页面变化: ${currentPage}/${totalPages}`);
};

// ========================== 辅助方法 ==========================
const getPdfTitle = (url: string): string => {
  if (!url) return '未命名文件';
  const fileName = url.split('/').pop() || '';
  const title = fileName
    .replace(/\.pdf$/i, '')
    .replace(/[-_]/g, ' ')
    .replace(/([A-Z])/g, ' $1')
    .trim();
  return title || 'PDF文档';
};

// ========================== 核心方法（简化版） ==========================
const queryUserInfoAndPermission = () => {
  const userId = uni.getStorageSync('cffp_userId');
  if (!userId) {
    uni.setStorageSync('loginType', 'visitor');
    initPdfAfterPermission();
    return;
  }

  api.queryInfo({ userId }).then(res => {
    if (res.success) {
      permissionList.value = res.data.accessPermission || [];
    } else {
      uni.setStorageSync('loginType', 'visitor');
      permissionList.value = [];
    }
    initPdfAfterPermission();
  }).catch(() => {
    uni.setStorageSync('loginType', 'visitor');
    permissionList.value = [];
    initPdfAfterPermission();
  });
};

const initPdfAfterPermission = () => {
  loading.value = true;
  const filteredTabs = filteredCurrentTabs.value;
  console.log(filteredTabs)
  if (currentType.value >= 2 && currentType.value <= 4) {
    if (filteredTabs.length > 0) {
      activeTab.value = 0;
      currentPdf.value = filteredTabs[0];
    } else {
      currentPdf.value = { id: '', title: '', urls: [], type: '',landscapeFlag:false };
    }
  }else{
	  currentPdf.value = { id: 'company', title: '公司介绍', urls: [`${OSS_BASE_URL}/public/company-intro.pdf`], type: 'showURL',landscapeFlag:false }; 
  }

  setTimeout(() => {
    loading.value = false;
  }, 200);
};

const filteredCurrentTabs = computed(() => {
  const originalTabs = rawTabConfig.value[currentType.value] || [];
  if (permissionList.value.length === 0) return [];
  
  const targetPermissionKey = typeToPermissionKey.value[currentType.value];
  if (!targetPermissionKey) return [];
  
  const targetPermission = permissionList.value.find(
    item => item.key === targetPermissionKey
  );
  if (!targetPermission || targetPermission.rights.length === 0) return [];
  
  const allowedTabIds = new Set(
    targetPermission.rights.map(right => right.key)
  );
  return originalTabs.filter(tab => allowedTabIds.has(tab.id));
});

const switchTab = (index: number) => {
  const tabs = filteredCurrentTabs.value;
  if (index < 0 || index >= tabs.length || tabs.length === 0) return;

  uni.showLoading({ title: '切换中...' });
  
  setTimeout(() => {
    activeTab.value = index;
    currentPdf.value = tabs[index];
    uni.setStorageSync('tabsIndex', index);
    
    setTimeout(() => {
      uni.hideLoading();
    }, 300);
  }, 100);
};

// ========================== 生命周期 ==========================
onLoad((query) => {
  currentType.value = Number(query.type) || 1;
  const index = uni.getStorageSync('tabsIndex');
  setTimeout(() => {
    if (index) {
      switchTab(index);
    }
  }, 300);
  
  queryUserInfoAndPermission();
});

// 监听当前PDF变化
watch(() => currentPdf.value, (newVal) => {
  // Tab切换时不需要额外处理，组件会自动处理
});
</script>

<style scoped lang="scss">
/* 样式可以大幅简化，因为PDF查看逻辑都在组件中 */
.module-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f5f5f5;
}

.content {
  flex: 1;
  display: flex;
  flex-direction: column;
  position: relative;
}

.loading {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #ffffff;

  .spinner {
    width: 30px;
    height: 30px;
    border: 3px solid #eeeeee;
    border-top-color: #20269B;
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin-bottom: 16px;
  }

  text {
    color: #999999;
    font-size: 14px;
  }
}

.error {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #ef4444;
  font-size: 16px;
  background-color: #ffffff;
}

.pdf-item-container {
  margin-bottom: 24rpx;
  background: #ffffff;
  border-radius: 8rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.tab-bar {
  display: flex;
  flex-direction: row;
  height: 48px;
  background-color: #ffffff;
  border-bottom: 1px solid #eeeeee;
  overflow-x: auto;
  white-space: nowrap;
  scrollbar-width: none;

  &::-webkit-scrollbar {
    display: none;
  }

  .tab-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 0 16px;
    height: 100%;
    position: relative;
    cursor: pointer;

    .tab-text {
      font-size: 14px;
      color: #666666;
      transition: color 0.3s;
    }

    .tab-indicator {
      position: absolute;
      bottom: 0;
      width: 24px;
      height: 2px;
      background-color: #20269B;
      border-radius: 1px;
      transition: all 0.3s;
    }

    &.active {
      .tab-text {
        color: #20269B;
        font-weight: 500;
      }
    }
  }
}

.pdf-tab-content {
  width: 100%;
  position: absolute;
  top: 48px;
  bottom: 0;
  background-color: #f5f5f5;
  overflow-y: auto;
  padding: 16rpx;
  box-sizing: border-box;
}

.pdf-empty {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #999999;
  font-size: 14px;
  background-color: #ffffff;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}
</style>