<template>
    <view class="page-wrappe">
		<cus-header title=' ' bgColor="transparent"></cus-header>
		<view id="pdfContainer" class="pdf-container" :style="{'transform':'scale('+scale+')', 'height': containerScaledHeight + 'px'}" v-if="reportData">
			<!-- 封面 -->
			<view class="cd_box fm2 adffc" style="margin-top: 20px;height: 868px;">
				<img class="fm2-logo" src="https://gitee.com/hw_0302/chuang-heng-wechat-images/raw/master/versionTwo/fm_logo.png">
				<img class="fm2-logo2" src="https://gitee.com/hw_0302/chuang-heng-wechat-images/raw/master/versionTwo/fm_logo2.png">
				<img class="fm2-perill" src="https://gitee.com/hw_0302/chuang-heng-wechat-images/raw/master/versionTwo/fm_perill.png">
				<view class="fm2-line"></view>
				<view class="fm2-p">PERILL团队发展动态评估报告(专业版)</view>
				<view class="fm2-texts adf" style="margin-top: 5px;">
					<view class="fm2-texts-pre adf" style="margin-top: 10px;">
						<view class="fm2-texts-pre-span">客户名称：</view>
						<view class="fm2-texts-pre-val">{{ reportData.teamInfo.enterpriseName||'' }}</view>
					</view>
					<view class="fm2-texts-pre adf" style="margin-top: 10px;">
						<view class="fm2-texts-pre-span">团队名称：</view>
						<view class="fm2-texts-pre-val">{{ reportData.teamInfo.teamName||'' }}</view>
					</view>
					<view class="fm2-texts-pre adf" style="margin-top: 10px;">
						<view class="fm2-texts-pre-span">评估发起人：</view>
						<view class="fm2-texts-pre-val">{{ reportData.teamInfo.initiator||'' }}</view>
					</view>
					<view class="fm2-texts-pre adf" style="margin-top: 10px;">
						<view class="fm2-texts-pre-span">报告生成时间：</view>
						<view class="fm2-texts-pre-val">{{ reportData.teamInfo.reportDate||'' }}</view>
					</view>
					<view class="fm2-texts-pre adf" style="margin-top: 10px;">
						<view class="fm2-texts-pre-span">团队类型：</view>
						<view class="fm2-texts-pre-val">{{ reportData.teamInfo.functionName||'' }}</view>
					</view>
					<view class="fm2-texts-pre adf" style="margin-top: 10px;">
						<view class="fm2-texts-pre-span">团队层级：</view>
						<view class="fm2-texts-pre-val">{{ reportData.teamInfo.hierarchy||'' }}</view>
					</view>
				</view>
			</view>
			<!-- 介绍 -->
			<view class="cd_box">
				<view class="v2-top adfacjb" :style="{'background-image':'url(https://gitee.com/hw_0302/chuang-heng-wechat-images/raw/master/versionTwo/intro_title_bg.png)'}">
					<view class="vt-left" style="color: #FFFFFF;">介绍<span>PERILL团队发展动态评估简介</span></view>
					<view class="vt-right">PERILL团队发展动态评估报告(专业版)</view>
				</view>
				<view class="v2-box">
					<img class="vb-img1" :src="'https://gitee.com/hw_0302/chuang-heng-wechat-images/raw/master/versionTwo/'+'intro'+'_box_img1.png'">
					<img class="vb-img2" :src="'https://gitee.com/hw_0302/chuang-heng-wechat-images/raw/master/versionTwo/'+'intro'+'_box_img2.png'">
					<view class="v2-p">PERILL团队发展动态评估源于团队教练辅导领域的先驱、管理思维与团队绩效领域的权威、全球顶尖团队教练David Clutterbuck教授及其团队通过深入研究，提炼出影响团队绩效的140多个基于实证的因素，整合而成的团队评估和提升工具-PERILL团队发展动态评估。</view>
					<view class="v2-p" style="margin-top: 8px;">创衡国际基于10多年来在全球与200多家具有前瞻性的国际公司以及国内具有行业代表性公司的合作经验，结合CCMI的PERILL团队发展动态评估工具，在中国推出的团队发展动态评估系统，旨在帮助团队更全面、更有效地从六个维度评估团队的发展现状，为支持团队成为高价值团队提供全景式的客观评估。</view>
					<view class="v2-p" style="margin-top: 8px;">PERILL团队发展动态评估的主体内容由<span>{{reportData.teamInfo.questionCount||0}}</span>个关于团队的描述组成。</view>
				</view>
				<view class="v2-six">
					<view class="vsix-title">PERILL六大纬度</view>
					<view class="vsix-p">PERILL团队发展动态评估提供了一个复杂的团队系统概览，它并非针对孤立的问题，也不是简单的优缺点，而是着眼于团队系统的复杂性。它 通过6个影响因素(如下所述)提出问题，以揭示团队系统各要素之间的联系，以及这些联系如何影响团队的高效运作能力。</view>
					<view class="vsix-boxs">
						<view class="vsb adfac" v-for="(item,index) in sixWd" :key="index">
							<img class="vsb-img" :src="item.image"/>
							<view class="vsb-right">
								<view class="vsbr-top adfac">
									<view class="vsbrt-type" :style="{'background':item.color}">{{ item.type }}</view>
									<view class="vsbrt-title" :style="{'color':item.color}">{{ item.title }}</view>
								</view>
								<view class="vsbr-desc">{{ item.desc }}</view>
							</view>
						</view>
					</view>
				</view>
			</view>
			<!-- 总体评估分析 -->
			<view class="cd_box adffc">
				<view class="v2-top adfacjb" :style="{'background-image':'url(https://gitee.com/hw_0302/chuang-heng-wechat-images/raw/master/versionTwo/'+'intro'+'_top_title_bg2.png)'}">
					<view class="vt-left">总体评估分析</view>
					<view class="vt-right">PERILL团队发展动态评估报告(专业版)</view>
				</view>
				<view class="v2-box" @click="downloadZtzdfxImg">
					<img class="vb-img1" :src="'https://gitee.com/hw_0302/chuang-heng-wechat-images/raw/master/versionTwo/'+'intro'+'_box_img1.png'">
					<img class="vb-img2" :src="'https://gitee.com/hw_0302/chuang-heng-wechat-images/raw/master/versionTwo/'+'intro'+'_box_img2.png'">
					<view class="v2-p2">报告的核心是PERILL团队发展动态评估分析下的整体团队表现。这包括团队在PERILL团队发展动态评估每个关键要素上的综合得分，通过结合得分和置信指数，我们能够展示出高功能领域和低功能域。</view>
					<view class="v2-p2" style="margin-top: 16px;">下面图中的位置标记显示了团队按主题划分的总分。</view>
					<view class="vb-category">
						<view class="vbc-pre adfac">
							<view class="vbcp-yuan y1"></view>
							<view class="vbcp-text">团队Leader</view>
						</view>
						<view class="vbc-pre adfac">
							<view class="vbcp-yuan y2"></view>
							<view class="vbcp-text">团队Member</view>
						</view>
						<view class="vbc-pre adfac">
							<view class="vbcp-yuan y3"></view>
							<view class="vbcp-text">利益相关方Stakeholder</view>
						</view>
						<view class="vbc-pre adfac">
							<view class="vbcp-yuan y4"></view>
							<view class="vbcp-text">赞助人Sponsor</view>
						</view>
					</view>
					<view style="width:360px;height:360px;margin: 0 auto;" class="pdfEchart">
						<l-echart ref="ztzdfxRef" :canvas2d="true" @finished="initZtzdfxChart" style="width: 100%;height: 100%;"></l-echart>
					</view>
				</view>
				<view class="v2-data">
					<view class="vd-title" :style="{'background-image':'url(https://gitee.com/hw_0302/chuang-heng-wechat-images/raw/master/versionTwo/'+'intro'+'_title_bg1.png)'}">评估结果</view>
					<view class="v2-p" v-html="(reportData.totalDiagnosticOutput||'').replaceAll('\n\n','<br>')"></view>
				</view>
				<view class="v2-data" style="flex: 1;margin-top: 20px;">
					<view class="vd-title vt2" :style="{'background-image':'url(https://gitee.com/hw_0302/chuang-heng-wechat-images/raw/master/versionTwo/'+'intro'+'_title_bg2.png)'}">团队提升&教练建议</view>
					<view class="v2-p" v-html="(reportData.totalDiagnosisSuggest||'').replaceAll('\n\n','<br>')"></view>
				</view>
			</view>
			<!-- 多维度 -->
			<canvas type="2d" id="table-canvas" canvas-id="table-canvas" class="offscreen-canvas"></canvas>
			<template v-if="reportData&&reportData.dimensionAnalysis&&reportData.dimensionAnalysis.length">
				<view class="cd_box adffc" style="border: none;" :style="{'background-image':'url('+'https://gitee.com/hw_0302/chuang-heng-wechat-images/raw/master/versionTwo/'+typeDict[item.title]+'_bg.png)'}" v-for="(item,index) in reportData.dimensionAnalysis" :key="index">
					<view class="v2-top adfacjb" :style="{'background-image':'url('+'https://gitee.com/hw_0302/chuang-heng-wechat-images/raw/master/versionTwo/'+typeDict[item.title]+'_title_bg.png)'}">
						<view class="vt-left" :class="{'black':(item.title=='人际关系'||item.title=='学习')}">{{ item.title }}</view>
						<view class="vt-right">PERILL团队发展动态评估报告(专业版)</view>
					</view>
					<view class="v2-box" :style="{'border':'1px solid '+item.bcolor}">
						<img class="vb-img1" :src="'https://gitee.com/hw_0302/chuang-heng-wechat-images/raw/master/versionTwo/'+typeDict[item.title]+'_box_img1.png'">
						<img class="vb-img2" :src="'https://gitee.com/hw_0302/chuang-heng-wechat-images/raw/master/versionTwo/'+typeDict[item.title]+'_box_img2.png'">
						<view class="v2-p2">{{ item.desc }}</view>
						<!-- <view class="v2-p2" style="margin-top: 16px;">评分总体分布</view> -->
						<view class="vb-table" :style="{'border':'1px solid '+item.bcolor,'margin-top':'22px'}">
							<view class="vbt-th adfac" :class="{'black':(item.title=='人际关系'||item.title=='学习')}" :style="{'background':item.thcolor}">
								<view class="vbtt-w1">主题</view>
								<view class="vbtt-w2">最低分</view>
								<view class="vbtt-w2">平均分</view>
								<view class="vbtt-w2">最高分</view>
								<view class="vbtt-w3">问卷陈述</view>
							</view>
							<view class="vbt-pre adfac" v-for="(ss,si) in item.scoreSpreads" :key="si">
								<view class="vbtp-left vbtt-w1 adfacjc" :class="{'black':(item.title=='人际关系'||item.title=='学习'||item.title=='内部流程及系统与架构')}" :style="{'background':item.titlecolor,'padding':'0 16px'}">{{ ss.theme||'' }}</view>
								<view class="vbtp-num vbtt-w2" :style="{'border-bottom':'1px solid '+item.bcolor}">{{ ss.minScore||0 }}</view>
								<view class="vbtp-num vbtt-w2 green" :style="{'border-bottom':'1px solid '+item.bcolor}">{{ ss.avgScore||0 }}</view>
								<view class="vbtp-num vbtt-w2" :style="{'border-bottom':'1px solid '+item.bcolor}">{{ ss.maxScore||0 }}</view>
								<view class="vbtp-desc" :style="{'border-bottom':'1px solid '+item.bcolor}">
									<view class="vbtpd-title">{{ ss.question||'' }}</view>
									<view class="xr_tb adfac">
										<view class="xt_pre p1"></view>
										<view class="xt_pre p2"></view>
										<view class="xt_pre p3"></view>
										<view class="xt_score adfac" :style="{'left':ss.left,'width':(((ss.maxScore>25?25:ss.maxScore)-(ss.minScore>25?25:ss.minScore))*4)+'%'}">
											<view class="xts_num adfacjc red">{{ ss.minScore>25?25:ss.minScore }}</view>
											<view class="xts_box"></view>
											<view class="xts_num adfacjc green">{{ ss.maxScore>25?25:ss.maxScore }}</view>
										</view>
									</view>
								</view>
							</view>
						</view>
					</view>
					<view class="v2-data" :style="{'border':'1px solid '+item.bcolor}">
						<view class="vd-title vt3" :class="{'black':(item.title=='人际关系'||item.title=='学习')}" :style="{'background-image':'url(https://gitee.com/hw_0302/chuang-heng-wechat-images/raw/master/versionTwo/'+typeDict[item.title]+'_title_bg1.png)'}">评估结果</view>
						<view class="v2-p3">纬度得分</view>
						<view class="vd-wd adfac" :style="{'background':item.wddf}">
							<view class="vdwd-pre">维度加权总分：<span>{{ item.weightedTotal||0 }}</span></view>
							<view class="vdwd-pre vp">维度同意度总分（未加权）：<span>{{ item.consentTotal||0 }}</span></view>
							<view class="vdwd-pre">维度权重：<span>{{ item.weight||0 }}</span></view>
						</view>
						<view class="v2-p" style="margin-top: 8px;" v-html="(item.diagnosisOutput||'').replaceAll('\n\n','<br>')"></view>
					</view>
					<view class="v2-data" :style="{'border':'1px solid '+item.bcolor}" style="flex: 1;margin-top: 15px;">
						<view class="vd-title vt3" :class="{'black':(item.title=='人际关系'||item.title=='学习')}" :style="{'background-image':'url(https://gitee.com/hw_0302/chuang-heng-wechat-images/raw/master/versionTwo/'+typeDict[item.title]+'_title_bg1.png)'}">评估建议</view>
						<view class="v2-p" v-html="(item.diagnosisSuggest||'').replaceAll('\n\n','<br>')"></view>
					</view>
				</view>
			</template>
		</view>
		<view class="pdf_btn" @click="createPdf">生成PDF</view>
   </view>
</template>

<script name="">
	import { BaseApi } from '@/http/baseApi.js';
	import * as echarts from '@/pagesHome/components/lime-echart/static/echarts.min.js'
	import lEchart from '@/pagesHome/components/lime-echart/components/l-echart/l-echart.vue'
    
    export default {
        name: 'ZtzdfxChart',
		components:{ lEchart },
        data() {
        return {
			reportId:'',
			reportData: null,
			isChartReady: false,
			scale:1,
			originalContainerHeight: 0,
			containerScaledHeight: 'auto', 
            typeDict: {
				'宗旨与动机': 'zzdj',
				'外部流程及系统与架构': 'wbjg',
				'人际关系': 'rjgx',
				'内部流程及系统与架构': 'nbjg',
				'学习': 'xx',
				'领导力': 'ldl'
            },
            sixWd: [
				{
				  image: 'https://gitee.com/hw_0302/chuang-heng-wechat-images/raw/master/versionTwo/intro_img_p.png',
				  type: 'P',
				  title: '宗旨与动机',
				  desc: '指团队共享的目的和存在的意义, 包含对共同的愿景，目标和优先级的清晰度。',
				  color: '#761E6A'
				},
				{
				  image: 'https://gitee.com/hw_0302/chuang-heng-wechat-images/raw/master/versionTwo/intro_img_e.png',
				  type: 'E',
				  title: '外部流程、系统与结构',
				  desc: '指团队与其外部利益相关者 - 客户，供应商，股东，组织内的其他团队等的互动关联。',
				  color: '#009191'
				},
				{
				  image: 'https://gitee.com/hw_0302/chuang-heng-wechat-images/raw/master/versionTwo/intro_img_r.png',
				  type: 'R',
				  title: '人际关系',
				  desc: '指团队成员如何共同工作–他们是否相互尊重对方的能力，足够心理安全以能够坦诚相对，真正关心彼此的幸福感。',
				  color: '#FFD750'
				},
				{
				  image: 'https://gitee.com/hw_0302/chuang-heng-wechat-images/raw/master/versionTwo/intro_img_i.png',
				  type: 'I',
				  title: '内部流程、系统与结构',
				  desc: '指团队如何管理工作流程，互相支持和高质量的沟通和决策（包括工作任务和团队感情）。',
				  color: '#4EB2B2'
				},
				{
				  image: 'https://gitee.com/hw_0302/chuang-heng-wechat-images/raw/master/versionTwo/intro_img_l.png',
				  type: 'L',
				  title: '学习',
				  desc: '指团队应对多变的环境和保持持续的进步和成长的能力。团队如何提高绩效（如何完成今天的任务）、能力（如何提高技能和资源以处理明天的任务）和容量（长期的愿景， 如何用更少的资源做更多的事情）',
				  color: '#AFCDF5'
				},
				{
				  image: 'https://gitee.com/hw_0302/chuang-heng-wechat-images/raw/master/versionTwo/intro_img_l2.png',
				  type: 'L',
				  title: '领导力',
				  desc: '指团队认为需要怎样的领导行为能够让他们，作为个人或者团队做到最好。团队可以和他们的领导者讨论他们的责任，以帮助领导者成为他们需要的领导者。',
				  color: '#002846'
				}
            ],
			pdfImages:[],
		};
    },
	onLoad(options) {
		this.reportId = options.reportId;
		this.getReportData();
	},
    mounted() {
		this.calculateScaleAndPosition();
		uni.onWindowResize(() => {
			this.calculateScaleAndPosition();
		});
    },
    methods: {
		getReportData(){
			this.$api.get(`/core/report/previewReport/${this.reportId}`).then(({data:res})=>{
				if(res.code!==0) return this.$showToast(res.msg)
				this.reportData = res.data;
				
				const tempDimensionAnalysis = [
					{title:'宗旨与动机',bcolor:'#E4D2E1',thcolor:'#761E6A',titlecolor:'#BA8EB4',wddf:'linear-gradient( 90deg, #F5EFF5 0%, #FAF2F9 100%)',
						desc:`「宗旨与动机」维度，我们旨在探究是否存在一个清晰的存在理由和明确的方向，能够激发团队成员的动力并吸引他们的想象力，以及个人与集体的身份认同是否围绕共同的目标，并达成一致。`},
					{title:'外部流程及系统与架构',bcolor:'#B3DEDE',thcolor:'#009191',titlecolor:'#80C8C8',wddf:'linear-gradient( 90deg, #E8F5F5 0%, #F0F8F8 100%)',
						desc:`「外部流程、系统与结构」维度，我们旨在探究团队如何与各种利益相关者互动，他们与团队的利益相关方各自如何寻求了解对方，以及现有系统和流程的有效性，以帮助管理不同的期望和需求。`},
					{title:'人际关系',bcolor:'#FFDF73',thcolor:'#FFD750',titlecolor:'#FFEBA8',wddf:'linear-gradient( 90deg, rgba(255,215,80,0.34) 0%, rgba(251,225,130,0.09) 100%)',
						desc:`「人际关系」维度，我们旨在探究团队成员如何相互交流、信任程度、尊重和关心的程度，以及团队成员之间的关系如何促进（或破坏）协作。`},
					{title:'内部流程及系统与架构',bcolor:'#B3DEDE',thcolor:'#4EB2B2',titlecolor:'#CDE9EA',wddf:'linear-gradient( 90deg, #E8F5F5 0%, #F0F8F8 100%)',
						desc:`「内部流程、系统与结构」维度，我们旨在探究团队如何在平衡责任与自主权方面进行协作。我们关注团队的敏捷程度、沟通方式以及决策过程的有效性。`},
					{title:'学习',bcolor:'#C7DCF8',thcolor:'#AFCDF5',titlecolor:'#D7E5FA',wddf:'linear-gradient( 270deg, #F2F5F9 0%, #E3ECF8 100%)',
						desc:`「学习」维度，我们旨在探究团队如何提高其绩效、技能和资源以应对当前和未来的任务。我们还希望了解团队如何管理能力和提高效率。`},
					{title:'领导力',bcolor:'#E6EAED',thcolor:'#002846',titlecolor:'#8093A3',wddf:'linear-gradient( 270deg, #F2F4F6 0%, #EDF0F2 100%)',
						desc:`「领导力」维度，我们旨在探究领导素质和行为如何对团队功能和其他因素产生调节影响，以及这是积极的还是消极的。`}
				]
				this.reportData.dimensionAnalysis.forEach((d,i)=>{
					d.scoreSpreads.forEach(s=>{
						if((s.minScore+'').length>2) s.minScore = (s.minScore||0).toFixed(2)
						if((s.maxScore+'').length>2) s.maxScore = (s.maxScore||0).toFixed(2)
						if((s.avgScore+'').length>2) s.avgScore = (s.avgScore||0).toFixed(2)
						s.theme = s.theme.replaceAll('，','').replaceAll(',','');
						s.range = [s.minScore>25?25:s.minScore,s.maxScore>25?25:s.maxScore];
						if(s.minScore==0) s.left = '0%';
						else if(s.minScore>=25) s.left = 'calc(100% - 48px)';
						else s.left = s.minScore*4+'%';
					})
					this.reportData.dimensionAnalysis[i] = {...d,...tempDimensionAnalysis[i]}
				})
			})
		},
		async createPdf(){
		    uni.showLoading({
		        title:'正在生成PDF所需的图片...'
		    })
		    try {
		        const ztzdfxImgPromise = this.downloadZtzdfxImg();
		        const dimensionImagePromises = this.reportData.dimensionAnalysis.map(d => {
		            return this.generateTableImage(d,d.scoreSpreads);
		        });
		
		        const allImageUrls = await Promise.all([
		            ztzdfxImgPromise, 
		            ...dimensionImagePromises
		        ]);
		        this.pdfImages = allImageUrls;
				
				this.$api.post('/core/report/reportToPdf',{
					images:this.pdfImages,
					reportId:this.reportId
				}).then(({data:res})=>{
					if(res.code!==0) return this.$showToast(res.msg)
					uni.hideLoading();
					this.$showToast('生成成功');
					setTimeout(()=>{
						uni.redirectTo({
							url:'/pagesHome/report'
						})
					},1500)
				})
		    } catch (error) {
		        uni.hideLoading();
		        console.error('生成图片过程中发生错误:', error);
		        uni.showToast({ title: '生成图片失败，请重试', icon: 'none' });
		    }
		},
		/**
		 * @description 使用 Canvas 绘制表格并生成图片
		 * @param {Object} dimensionData 维度数据
		 * @param {Array} tableData 表格数据
		 * @returns {Promise<string>} 返回生成的图片临时文件路径
		 */
		generateTableImage(dimensionData, tableData) {
			return new Promise((resolve, reject) => {
				const query = uni.createSelectorQuery().in(this);
				query.select('#table-canvas')
					.fields({ node: true, size: true })
					.exec(async (res) => {
						if (!res || !res[0] || !res[0].node) {
							return reject('获取Canvas节点失败');
						}
						
						const canvasNode = res[0].node;
						const ctx = canvasNode.getContext('2d');
						const dpr = uni.getSystemInfoSync().pixelRatio;
		
						// --- 1. 定义布局和尺寸常量
						const TABLE_WIDTH = 548;
						const HEADER_HEIGHT = 38;
						const ROW_HEIGHT = 49;
						const FONT_FAMILY = 'sans-serif';
						const COL_WIDTHS = { theme: 72, min: 49, avg: 49, max: 49, statement: 329 };
						const COL_POSITIONS = {
							theme: 0,
							min: COL_WIDTHS.theme,
							avg: COL_WIDTHS.theme + COL_WIDTHS.min,
							max: COL_WIDTHS.theme + COL_WIDTHS.min + COL_WIDTHS.avg,
							statement: COL_WIDTHS.theme + COL_WIDTHS.min * 3
						};
		
						const CANVAS_HEIGHT = HEADER_HEIGHT + tableData.length * ROW_HEIGHT;
						const CANVAS_WIDTH = TABLE_WIDTH;
						
						canvasNode.width = CANVAS_WIDTH * dpr;
						canvasNode.height = CANVAS_HEIGHT * dpr;
						ctx.scale(dpr, dpr);
						
						ctx.fillStyle = '#FFFFFF';
						ctx.fillRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
						ctx.strokeStyle = dimensionData.bcolor;
						ctx.lineWidth = 1;
						ctx.strokeRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
		
						// --- 4. 绘制表头 ---
						const isBlackHeader = (dimensionData.title == '人际关系'||dimensionData.title == '学习');
						ctx.fillStyle = dimensionData.thcolor;
						ctx.fillRect(1, 1, CANVAS_WIDTH - 2, HEADER_HEIGHT - 1);
						ctx.fillStyle = isBlackHeader ? '#002846' : '#FFFFFF';
						ctx.font = `bold 10px ${FONT_FAMILY}`;
						ctx.textAlign = 'center';
						ctx.textBaseline = 'middle';
						
						ctx.fillText('主题', COL_POSITIONS.theme + COL_WIDTHS.theme / 2, HEADER_HEIGHT / 2);
						ctx.fillText('最低分', COL_POSITIONS.min + COL_WIDTHS.min / 2, HEADER_HEIGHT / 2);
						ctx.fillText('平均分', COL_POSITIONS.avg + COL_WIDTHS.avg / 2, HEADER_HEIGHT / 2);
						ctx.fillText('最高分', COL_POSITIONS.max + COL_WIDTHS.max / 2, HEADER_HEIGHT / 2);
						ctx.fillText('问卷陈述', COL_POSITIONS.statement + COL_WIDTHS.statement / 2, HEADER_HEIGHT / 2);
		
						// --- 5. 循环绘制每一行---
						tableData.forEach((row, index) => {
							const y = HEADER_HEIGHT + index * ROW_HEIGHT;
							
							const isBlackLeftTitle = (dimensionData.title == '人际关系' || dimensionData.title == '学习' || dimensionData.title == '内部流程及系统与架构');
							ctx.fillStyle = dimensionData.titlecolor;
							ctx.fillRect(1, y, COL_WIDTHS.theme - 1, ROW_HEIGHT);
							
							// 绘制主题文字
							ctx.textAlign = 'center';
							ctx.textBaseline = 'middle';
							ctx.fillStyle = isBlackLeftTitle ? '#002846' : '#FFFFFF';
							ctx.font = `10px ${FONT_FAMILY}`;
							this.drawWrappedText(ctx, row.theme, COL_POSITIONS.theme + COL_WIDTHS.theme / 2, y + ROW_HEIGHT / 2, 12, COL_WIDTHS.theme - 32);

							// 绘制主题单元格的白色下边框
							ctx.strokeStyle = '#FFFFFF';
							ctx.lineWidth = 1;
							ctx.beginPath();
							ctx.moveTo(1, y + ROW_HEIGHT - 1);
							ctx.lineTo(COL_WIDTHS.theme - 1, y + ROW_HEIGHT - 1);
							ctx.stroke();
		
							// 绘制其他单元格的下边框
							ctx.strokeStyle = dimensionData.bcolor;
							['min', 'avg', 'max', 'statement'].forEach(key => {
								ctx.beginPath();
								ctx.moveTo(COL_POSITIONS[key], y + ROW_HEIGHT);
								ctx.lineTo(COL_POSITIONS[key] + COL_WIDTHS[key], y + ROW_HEIGHT);
								ctx.stroke();
							});
							
							const minScore = ((row.minScore||0)+'').length>2?Number(row.minScore||0).toFixed(2):row.minScore;
							const avgScore = ((row.avgScore||0)+'').length>2?Number(row.avgScore||0).toFixed(2):row.avgScore;
							const maxScore = ((row.maxScore||0)+'').length>2?Number(row.maxScore||0).toFixed(2):row.maxScore;
							ctx.font = `bold 14px ${FONT_FAMILY}`;
							ctx.fillStyle = '#667E90';
							ctx.fillText(minScore, COL_POSITIONS.min + COL_WIDTHS.min / 2, y + ROW_HEIGHT / 2);
							ctx.fillStyle = '#27AE60';
							ctx.fillText(avgScore, COL_POSITIONS.avg + COL_WIDTHS.avg / 2, y + ROW_HEIGHT / 2);
							ctx.fillStyle = '#667E90';
							ctx.fillText(maxScore, COL_POSITIONS.max + COL_WIDTHS.max / 2, y + ROW_HEIGHT / 2);
							
							// 5.3 绘制问卷陈述列
							const statementX = COL_POSITIONS.statement;
							const statementPadding = 10;
							ctx.textAlign = 'left';
							ctx.textBaseline = 'top';
							ctx.fillStyle = '#193D59';
							ctx.font = `9px ${FONT_FAMILY}`;
							this.drawWrappedText(ctx, row.question, statementX + statementPadding, y + 8, 10, COL_WIDTHS.statement - statementPadding * 2);
							
							// 绘制范围指示器
							const rangeBarY = y + 33;
							const rangeBarWidth = COL_WIDTHS.statement - statementPadding * 2;
							const rangeBarHeight = 4;
							const rangeBarX = statementX + statementPadding;
		
							// 绘制三段色背景
							const segWidth = rangeBarWidth / 3;
							ctx.fillStyle = '#BA8EB4';
							ctx.fillRect(rangeBarX, rangeBarY, segWidth, rangeBarHeight);
							ctx.fillStyle = '#66BDBD';
							ctx.fillRect(rangeBarX + segWidth, rangeBarY, segWidth, rangeBarHeight);
							ctx.fillStyle = '#AFCDF5';
							ctx.fillRect(rangeBarX + segWidth * 2, rangeBarY, segWidth, rangeBarHeight);
		
							// --- 开始绘制滑块 ---
							const scaleFactor = rangeBarWidth / 25; 
							const minVal = row.range[0];
							const maxVal = row.range[1];
							const rangeLeft = minVal * scaleFactor;
							const rangeWidth = (maxVal - minVal) * scaleFactor;
							
							// 绘制中间的连接条
							const connectorY = rangeBarY - (8 - rangeBarHeight) / 2;
							const connectorHeight = 8;
							ctx.fillStyle = '#199C9C';
							ctx.fillRect(rangeBarX + rangeLeft, connectorY, rangeWidth, connectorHeight);
		
							// 绘制左右数字框
							const numBoxPadding = { h: 7, v: 4 };
							const numBoxFont = `bold 12px ${FONT_FAMILY}`;
							
							// 封装一个绘制数字框的函数
							const drawNumberBox = (text, side) => {
								ctx.font = numBoxFont;
								const metrics = ctx.measureText(text);
								const boxWidth = metrics.width + numBoxPadding.h * 2;
								const boxHeight = 12 + numBoxPadding.v * 2;
								
								const value = parseFloat(text);
								const centerPointX = rangeBarX + value * scaleFactor;
								let x;
								
								// 核心逻辑：判断两值是否相等
								if (minVal === maxVal) {
									// 如果相等，左右滑块并排显示，整体居中
									if (side === 'left') {
										x = centerPointX - boxWidth;
									} else { // 'right'
										x = centerPointX;
									}

									// --- 边界检查（针对组合滑块）---
									let combinedLeftX = centerPointX - boxWidth;
									if (combinedLeftX < rangeBarX) {
										const shift = rangeBarX - combinedLeftX;
										x += shift; // 将两个滑块一起向右移动
									}
									let combinedRightX = centerPointX + boxWidth;
									if (combinedRightX > rangeBarX + rangeBarWidth) {
										const shift = combinedRightX - (rangeBarX + rangeBarWidth);
										x -= shift; // 将两个滑块一起向左移动
									}

								} else {
									// 如果不相等，各自居中显示
									x = centerPointX - boxWidth / 2;

									// --- 边界检查（针对单个滑块）---
									if (x < rangeBarX) {
										x = rangeBarX;
									}
									if (x + boxWidth > rangeBarX + rangeBarWidth) {
										x = rangeBarX + rangeBarWidth - boxWidth;
									}
								}
								
								const boxY = connectorY + (connectorHeight - boxHeight) / 2;
								
								// 绘制阴影
								ctx.shadowColor = 'rgba(118, 30, 106, 0.08)';
								ctx.shadowBlur = 10;
								ctx.shadowOffsetY = 4;
								
								// 绘制圆角矩形背景
								ctx.fillStyle = '#FFFFFF';
								ctx.beginPath();
								ctx.moveTo(x + 4, boxY);
								ctx.arcTo(x + boxWidth, boxY, x + boxWidth, boxY + boxHeight, 4);
								ctx.arcTo(x + boxWidth, boxY + boxHeight, x, boxY + boxHeight, 4);
								ctx.arcTo(x, boxY + boxHeight, x, boxY, 4);
								ctx.arcTo(x, boxY, x + boxWidth, boxY, 4);
								ctx.closePath();
								ctx.fill();
								
								// 重置阴影
								ctx.shadowColor = 'transparent';
								ctx.shadowBlur = 0;
								ctx.shadowOffsetY = 0;
								
								// 绘制边框
								ctx.strokeStyle = 'rgba(131, 52, 120, 0.19)';
								ctx.lineWidth = 1;
								ctx.stroke();
								
								// 绘制文字
								ctx.fillStyle = side === 'left' ? '#904A87' : '#199C9C';
								ctx.textAlign = 'center';
								ctx.textBaseline = 'middle';
								ctx.fillText(text, x + boxWidth / 2, boxY + boxHeight / 2);
							};
							
							drawNumberBox(minVal.toString(), 'left');
							drawNumberBox(maxVal.toString(), 'right');
						});
						
						// --- 6. 生成图片文件 ---
						uni.canvasToTempFilePath({
							canvas: canvasNode,
							success: async (result) => {
								const fileurl = await this.uploadFilePromise(result.tempFilePath);
								resolve(fileurl);
							},
							fail: (err) => {
								console.error('图片生成失败', err);
								uni.showToast({ title: '图片生成失败', icon: 'none' });
								reject(err);
							}
						}, this);
					});
			});
		},
		/**
		 * @description 辅助函数：在Canvas中绘制可自动换行的文本
		 * @param {CanvasRenderingContext2D} ctx
		 * @param {string} text 要绘制的文本
		 * @param {number} x 起始x坐标
		 * @param {number} y 起始y坐标（对于居中对齐，这是中心y；对于top对齐，这是第一行的y）
		 * @param {number} lineHeight 行高
		 * @param {number} maxWidth 最大宽度
		 */
		drawWrappedText(ctx, text, x, y, lineHeight, maxWidth) {
			let words = text.split('');
			let line = '';
			let lines = [];

			for (let n = 0; n < words.length; n++) {
				let testLine = line + words[n];
				let metrics = ctx.measureText(testLine);
				if (metrics.width > maxWidth && n > 0) {
					lines.push(line);
					line = words[n];
				} else {
					line = testLine;
				}
			}
			lines.push(line);

			let startY;
			if (ctx.textBaseline === 'middle') {
				startY = y - (lineHeight * (lines.length - 1)) / 2;
			} else { // top
				startY = y;
			}
			
			for (let i = 0; i < lines.length; i++) {
				ctx.fillText(lines[i], x, startY + (i * lineHeight));
			}
		},
		calculateScaleAndPosition() {
		    uni.getSystemInfo({
				success: (res) => {
				    const screenWidth = res.windowWidth; // 手机屏幕的宽度
				    const pcContentWidth = 630; // PC端内容的原始宽度
				    this.scale = screenWidth / pcContentWidth;
				    this.$nextTick(() => {
						if (this.$refs.ztzdfxRef) {
							this.initZtzdfxChart();
						}
					});
				}
		    });
		},
		calculatePdfContainerHeight() {
			uni.createSelectorQuery().in(this).select('#pdfContainer').boundingClientRect(rect => {
				if (rect) {
					this.originalContainerHeight = rect.height;
					this.containerScaledHeight = this.originalContainerHeight * this.scale;
					// console.log('原始高度:', this.originalContainerHeight, '缩放比例:', this.scale, '缩放后高度:', this.containerScaledHeight);
				}
			}).exec();
		},
		downloadZtzdfxImg(){
			return new Promise(resolve=>{
				if (!this.isChartReady) return console.log('图表尚未准备好');
				
				const chartRef = this.$refs.ztzdfxRef;
				if (!chartRef) return console.log('无法找到图表组件');
				
				chartRef.canvasToTempFilePath({
					success: async (res) => {
						const imgUrl = await this.uploadFilePromise(res.tempFilePath);
						console.log(imgUrl,'imgUrl');
						resolve(imgUrl)
					},
					fail: (err) => {
						console.log('生成图片失败:', err);
					}
				});
			})
		},
		uploadFilePromise(url) {
		  return new Promise((resolve, reject) => {
		    let a = uni.uploadFile({
		      url: BaseApi+'/uploadFile',
		      filePath: url,
		      name: 'file',
		      success: (res) => {
		        setTimeout(() => {
					let data = JSON.parse(res.data)
					if(data&&data.code===0){
						resolve(data.data);
					}else this.$showToast(data?.msg)
		        }, 1000);
		      },
			  fail: err =>{
				resolve('');
			  }
		    });
		  });
		},
		async initZtzdfxChart() {
			let dataSum = this.reportData.overall.length*this.reportData.overall[0].themeTotalSpreads.length;
			const leaderData = [],memberData = [],stakeholderData=[],sponsorData=[];
			const overall = this.reportData.overall||[];
			overall.forEach(o=>{
				let themeTotalSpreads = o.themeTotalSpreads||[];
				if(['内部流程、系统与结构','学习','领导力'].includes(o.dimension)) themeTotalSpreads = o.themeTotalSpreads.reverse()||[];
				themeTotalSpreads.forEach(t=>{
					leaderData.push(t.scoreLeader||0);
					memberData.push(t.scoreMember||0);
					stakeholderData.push(t.scoreStakeholder||0);
					sponsorData.push(t.scoreSponsor||0);
				})
			})
			const sumArr = leaderData.concat(memberData).concat(stakeholderData).concat(sponsorData);
			const maxValue = sumArr.reduce((a,b)=>Math.max(a,b));
			const minValue = sumArr.reduce((a,b)=>Math.min(a,b));

            const chart = await this.$refs.ztzdfxRef.init(echarts);
            let option = {
				graphic: [
					{
						type: 'image',	
						id: 'radar-bg',
						z: -1,
						bounding: 'raw',
						left: 'center',
						top: 'center',
						style: {
							image:'https://gitee.com/hw_0302/chuang-heng-wechat-images/raw/master/six_chart_bg.png',
							width: 360*this.scale-20,
							height: 360*this.scale-20,
							opacity: 1
						}
					},
					{
						type: 'circle',
						z: 100, // 设置一个较高的 z 值，确保它在最顶层
						left: 'center', // 水平居中
						top: 'center',  // 垂直居中
						shape: {
							r: 12*this.scale // 圆形的半径，您可以根据需要调整大小
						},
						style: {
							fill: '#FFFFFF', // 填充色为白色
							shadowBlur: 20*this.scale,  // 阴影的模糊范围
							shadowColor: 'rgba(0, 0, 0, 0.15)', // 阴影颜色
							shadowOffsetY: 4*this.scale // 向下的阴影偏移，产生悬浮效果
						}
					}
				],
				radar: {
					// shape: 'circle',
					indicator: new Array(dataSum).fill({ max:maxValue, min:minValue }),
					axisName: {
						show: false
					},
					splitArea:{
					show:false
					},
					splitLine: {
					show: false
					},
					axisLine: {
					show: false
					},
					startAngle: 95
				},
				series: [
					{
						type: 'radar',
						data: [
							{
								value: sponsorData,
								itemStyle: {
									color: '#012846'
								},
								lineStyle: {
									color: '#012846',
									width:1.5
								},
								areaStyle: {
									color: 'rgba(255, 255, 255, 0.4)'
								},
								symbolSize: 3
							},
							{
								value: stakeholderData,
								itemStyle: {
									color: '#FFD650'
								},
								lineStyle: {
									color: '#FFD650',
									width:1.5
								},
								areaStyle: {
									color: 'rgba(255, 255, 255, 0.4)'
								},
								symbolSize: 3
							},
							{
								value: memberData,
								itemStyle: {
									color: '#AFCDF5'
								},
								lineStyle: {
									color: '#AFCDF5',
									width:1.5
								},
								areaStyle: {
									color: 'rgba(255, 255, 255, 0.4)'
								},
								symbolSize: 3
							},
							{
								value: leaderData,
								itemStyle: {
									color: '#9F6196'
								},
								lineStyle: {
									color: '#9F6196',
									width:1.5
								},
								areaStyle: {
									color: 'rgba(255, 255, 255, 0.4)'
								},
								symbolSize: 3
							}
						]
					}
				]
			};
			chart.setOption(option);
			this.isChartReady = true;
			this.$nextTick(() => {
				this.calculatePdfContainerHeight();
			});
        },
      }
    };
</script>

<style scoped lang="scss">
	.page-wrappe{
		width: 100%;
		background: #FFFFFF;
		overflow-x: hidden;
		overflow-y: auto;
		.pdf-container{
			width: 630px;
			padding: 0 20rpx;
			box-sizing: border-box;
			transform-origin: top left;
		}
	}
	.offscreen-canvas {
		position: fixed;
		top: -9999px;
		left: -9999px;
	}

	.pdf_btn{
		padding: 15rpx 20rpx;
		border-radius: 20rpx;
		font-size: 28rpx;
		color: #FFFFFF;
		background: #189B9B;
		position: fixed;
		right: 30rpx;
		bottom: 100rpx;
		z-index: 1000;
	}
	
	@import '../static/pdf.scss';
</style>