<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">团队发展动态评估报告(基础版)</view>
				<view class="fm2-texts adf">
					<view class="fm2-texts-pre"><span style="letter-spacing: 6px;">客户公司：</span>{{ reportData.teamInfo.enterpriseName||'' }}</view>
					<view class="fm2-texts-pre"><span style="letter-spacing: 6px;">团队名称：</span>{{ reportData.teamInfo.teamName||'' }}</view>
					<view class="fm2-texts-pre"><span style="letter-spacing: 2.5px;">评估发起人：</span>{{ reportData.teamInfo.initiator||'' }}</view>
					<view class="fm2-texts-pre"><span>报告生成时间：</span>{{ reportData.teamInfo.reportDate||'' }}</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">团队发展动态评估报告(基础版)</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">团队发展动态评估报告(基础版)</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 style="width:100%;height:200px;" class="pdfEchart">
						<l-echart ref="ztzdfxRef" :canvas2d="true" @finished="initZtzdfxChart"></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" canvas-id="score-canvas" id="score-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">团队发展动态评估报告(基础版)</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}">
							<view class="vbt-pre adfac" v-for="(ss,si) in item.scoreSpreads" :key="si">
								<view class="vbtp-left adfacjc" :class="{'black':(item.title=='人际关系'||item.title=='学习'||item.title=='内部流程、系统与结构')}" :style="{'background':item.titlecolor,'padding':'0 16px'}">{{ ss.theme||'' }}</view>
								<view class="vbtp-right" :style="{'border':'1px solid '+item.bcolor}">
									<view class="vbtpr-title">{{ ss.question||'' }}</view>
									<view class="vbtpr-jd">
										<view class="vj_num" :style="{'width':((ss.avgScore>25?25:ss.avgScore)/25*100)+'%','background':item.pfztfb}"></view>   
										<view class="vj-val adfacjc" :style="{'border':'1px solid '+item.bcolor,'left':'calc('+((ss.avgScore>25?25:ss.avgScore)/25*100)+'% - 12px)','box-shadow':'0px 2px 6px 0px '+item.bcolor}">{{ (ss.avgScore>25?25:ss.avgScore) }}</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',titlecolor:'#BA8EB4',wddf:'linear-gradient( 90deg, #F5EFF5 0%, #FAF2F9 100%)',
						pfztfb:'linear-gradient( 90deg, #761E6A 0%, #BA8EB4 100%)',
						desc:`「宗旨与动机」维度，我们旨在探究是否存在一个清晰的存在理由和明确的方向，能够激发团队成员的动力并吸引他们的想象力，以及个人与集体的身份认同是否围绕共同的目标，并达成一致。`},
					{title:'外部流程、系统与结构',bcolor:'#B3DEDE',titlecolor:'#80C8C8',wddf:'linear-gradient( 90deg, #E8F5F5 0%, #F0F8F8 100%)',
						pfztfb:'linear-gradient( 90deg, #009191 0%, #80C8C8 100%)',
						desc:`「外部流程、系统与结构」维度，我们旨在探究团队如何与各种利益相关者互动，他们与团队的利益相关方各自如何寻求了解对方，以及现有系统和流程的有效性，以帮助管理不同的期望和需求。`},
					{title:'人际关系',bcolor:'#FFDF73',titlecolor:'#FFEBA8',wddf:'linear-gradient( 90deg, rgba(255,215,80,0.34) 0%, rgba(251,225,130,0.09) 100%)',
						pfztfb:'linear-gradient( 90deg, #FFD750 0%, #FFEBA8 100%)',
						desc:`「人际关系」维度，我们旨在探究团队成员如何相互交流、信任程度、尊重和关心的程度，以及团队成员之间的关系如何促进（或破坏）协作。`},
					{title:'内部流程、系统与结构',bcolor:'#B3DEDE',titlecolor:'#CDE9EA',wddf:'linear-gradient( 90deg, #E8F5F5 0%, #F0F8F8 100%)',
						pfztfb:'linear-gradient( 90deg, #4EB2B2 0%, #CDE9EA 100%)',
						desc:`「内部流程、系统与结构」维度，我们旨在探究团队如何在平衡责任与自主权方面进行协作。我们关注团队的敏捷程度、沟通方式以及决策过程的有效性。`},
					{title:'学习',bcolor:'#E6EAED',titlecolor:'#D7E5FA',wddf:'linear-gradient( 270deg, #F2F5F9 0%, #E3ECF8 100%)',
						pfztfb:'linear-gradient( 90deg, #AFCDF5 0%, #D7E5FA 100%)',
						desc:`「学习」维度，我们旨在探究团队如何提高其绩效、技能和资源以应对当前和未来的任务。我们还希望了解团队如何管理能力和提高效率。`},
					{title:'领导力',bcolor:'#E6EAED',titlecolor:'#8093A3',wddf:'linear-gradient( 270deg, #F2F4F6 0%, #EDF0F2 100%)',
						pfztfb:'linear-gradient( 90deg, #002846 0%, #8093A3 100%)',
						desc:`「领导力」维度，我们旨在探究领导素质和行为如何对团队功能和其他因素产生调节影响，以及这是积极的还是消极的。`}
				]
				if(this.reportData&&this.reportData.dimensionAnalysis){
					this.reportData.dimensionAnalysis.forEach((d,i)=>{
						d.scoreSpreads.forEach(s=>{
							s.theme = s.theme.replaceAll('，','').replaceAll(',','');
						})
						this.reportData.dimensionAnalysis[i] = {...d,...tempDimensionAnalysis[i]}
					})
				}
			})
		},
		// async createPdf(){
		// 	uni.showLoading({
		// 		title:'正在生成PDF所需的图片...'
		// 	})
		// 	const imgUrl = await this.downloadZtzdfxImg();
		//  this.pdfImages.push(imgUrl);
		
		// 	for(const d of this.reportData.dimensionAnalysis){
		// 		const fileurl = await this.generateScoreImage(d);
		// 		this.pdfImages.push(fileurl)
		// 	}
			
		// 	this.$showToast(`生成成功，共计${this.pdfImages.length}张`);
		// 	uni.hideLoading();
		// 	console.log(this.pdfImages);
		// },
		// Promise.all方法，性能更高
		async createPdf(){
		    uni.showLoading({
		        title:'正在生成PDF所需的图片...'
		    })
		    try {
		        const ztzdfxImgPromise = this.downloadZtzdfxImg();
		        const dimensionImagePromises = this.reportData.dimensionAnalysis.map(d => {
		            return this.generateScoreImage(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' });
		    }
		},
		// 绘制主函数
		async generateScoreImage(dimensionData,scoreData) {
			return new Promise(resolve=>{
				console.log('开始生成图片...');
				// --- 1. 定义尺寸和样式 ---
				const canvasWidth = 588; // .v2-box 的宽度大约是 630 - 20*2(padding) - 1*2(border) = 588
				const itemHeight = 49; // 每个评估项的高度
				const totalHeight = itemHeight * scoreData.length;
				// 调整为整数，避免边框模糊
				const canvasHeight = totalHeight;
						
				// --- 2. 获取 Canvas 节点 ---
				// 使用 ID 选择器更精确
				const query = uni.createSelectorQuery().in(this);
				query.select('#score-canvas')
				    .fields({ node: true, size: true })
				    .exec(async (res) => {
				        // 【重要】增加健壮性检查
				        if (!res || !res[0] || !res[0].node) {
				            console.error('获取 Canvas 节点失败，请检查 canvas-id 和 type="2d" 是否正确设置。');
				            uni.showToast({ title: '组件初始化失败', icon: 'none' });
				            return;
				        }
						
				        const canvasNode = res[0].node;
				        const context = canvasNode.getContext('2d');
				        const dpr = uni.getSystemInfoSync().pixelRatio;
						
				        // --- 3. 设置画布尺寸和缩放以适应高分屏 ---
				        canvasNode.width = canvasWidth * dpr;
				        canvasNode.height = canvasHeight * dpr;
				        context.scale(dpr, dpr);
						
				        // --- 4. 开始绘制 ---
				        // 绘制大背景
				        context.fillStyle = '#FFFFFF';
				        context.fillRect(0, 0, canvasWidth, canvasHeight);
						
				        // --- 5. 循环绘制每一项 ---
				        for (let i = 0; i < scoreData.length; i++) {
				            const item = scoreData[i];
				            const yPos = i * itemHeight;
				            // 注意：这里不再需要 await，因为 canvas 2d 绘图是同步的
				            this.drawScoreItem(context, item, yPos, canvasWidth, itemHeight, dimensionData);
				        }
				        
				        // 【补充】绘制最外层的上下边框，避免被循环内的矩形覆盖
				        context.strokeStyle = dimensionData.bcolor;
				        context.lineWidth = 1;
				        context.strokeRect(0, 0, canvasWidth, canvasHeight);
						
						
				        // --- 6. 生成图片 ---
				        uni.hideLoading();
				        uni.canvasToTempFilePath({
				            canvas: canvasNode,
				            x: 0,
				            y: 0,
				            width: canvasWidth,
				            height: canvasHeight,
				            destWidth: canvasWidth * dpr,
				            destHeight: canvasHeight * dpr,
				            success: async (result) => {
				                console.log('图片生成成功!', result.tempFilePath);
				                const fileurl = await this.uploadFilePromise(result.tempFilePath);
				                console.log(fileurl, 'fileurl');
								resolve(fileurl)
				            },
				            fail: (err) => {
				                console.error('图片生成失败', err);
				                uni.showToast({ title: '图片生成失败', icon: 'none' });
				            }
				        }, this);
				});
			})
		},
		// 辅助函数：计算自动换行文字的总高度
		calculateWrappedTextHeight(ctx, text, lineHeight, maxWidth) {
		    let words = text.split('');
		    let line = '';
		    let height = lineHeight; // 至少有一行
		    for (let n = 0; n < words.length; n++) {
		        let testLine = line + words[n];
		        let metrics = ctx.measureText(testLine);
		        let testWidth = metrics.width;
		        if (testWidth > maxWidth && n > 0) {
		            line = words[n];
		            height += lineHeight;
		        } else {
		            line = testLine;
		        }
		    }
		    return height;
		},
		// 辅助函数：绘制单个评估项
		drawScoreItem(ctx, scoreItem, y, width, height, dimensionData) {
		    const leftBoxWidth = 72;
			const rightBoxX = leftBoxWidth;
			const rightBoxWidth = width - leftBoxWidth;
			const rightPadding = 10; // 右侧内容的通用内边距
		
			// 1. --- 绘制左侧部分 ---
			ctx.fillStyle = dimensionData.titlecolor;
			ctx.fillRect(0, y, leftBoxWidth, height);
			
			// 绘制白色下边框
			if (y + height < ctx.canvas.height / (uni.getSystemInfoSync().pixelRatio)) {
				ctx.strokeStyle = '#FFFFFF';
				ctx.lineWidth = 1;
				ctx.beginPath();
				ctx.moveTo(0, y + height - 1);
				ctx.lineTo(leftBoxWidth, y + height - 1);
				ctx.stroke();
			}
			
			// 绘制左侧标题文字 (要求 1)
			let theme = (scoreItem.theme||'').replaceAll('，','').replaceAll(',','');
			const isBlackLeftTitle = (dimensionData.title == '人际关系' || dimensionData.title == '学习' || dimensionData.title == '内部流程、系统与结构');
			ctx.fillStyle = isBlackLeftTitle ? '#002846' : '#FFFFFF';
			ctx.font = '10px sans-serif';
			ctx.textAlign = 'center';
			ctx.textBaseline = 'middle';
			this.drawWrappedText(ctx, theme, leftBoxWidth / 2, y + height / 2, 12, leftBoxWidth - 32); // 左右留16px边距
		
			// 2. --- 绘制右侧部分 ---
			// 绘制右侧外边框
			ctx.strokeStyle = dimensionData.bcolor;
			ctx.lineWidth = 1;
			ctx.strokeRect(rightBoxX, y, rightBoxWidth, height);
		
			// --- 计算右侧内容垂直居中需要的参数 (要求 2) ---
			const descLineHeight = 16;
			const descMaxWidth = rightBoxWidth - rightPadding * 2;
			ctx.font = '9px sans-serif'; // 设置好字体用于计算
			const descHeight = this.calculateWrappedTextHeight(ctx, scoreItem.question, descLineHeight, descMaxWidth);
			
			const spacing = 7; // 文字与进度条间距 (要求 4)
			const progressBarHeight = 6; // 进度条高度 (要求 3)
			
			// 计算右侧所有内容的总高度
			const totalContentHeight = descHeight + spacing + progressBarHeight;
			// 计算内容块的起始 Y 坐标，使其在右侧框内垂直居中
			const contentStartY = y + (height - totalContentHeight) / 2;
		
			// --- 开始绘制右侧内容 ---
			// 绘制右侧描述文字 (要求 2)
			ctx.fillStyle = '#193D59';
			ctx.font = '9px sans-serif';
			ctx.textAlign = 'left';
			ctx.textBaseline = 'top'; // 基线设为 top 方便计算
			this.drawWrappedText(ctx, scoreItem.question, rightBoxX + rightPadding, contentStartY, descLineHeight, descMaxWidth);
		
			// 绘制进度条 (要求 3)
			const progressBarY = contentStartY + descHeight + spacing;
			const progressBarWidth = rightBoxWidth - rightPadding * 2;
			const scoreWidth = ((scoreItem.avgScore>25?25:scoreItem.avgScore)/ 25) * progressBarWidth;
			const barRadius = 3;
		
			// 绘制灰色背景
			ctx.fillStyle = '#F0F2F8';
			ctx.beginPath();
			ctx.moveTo(rightBoxX + rightPadding + barRadius, progressBarY);
			ctx.arcTo(rightBoxX + rightPadding + progressBarWidth, progressBarY, rightBoxX + rightPadding + progressBarWidth, progressBarY + progressBarHeight, barRadius);
			ctx.arcTo(rightBoxX + rightPadding + progressBarWidth, progressBarY + progressBarHeight, rightBoxX + rightPadding, progressBarY + progressBarHeight, barRadius);
			ctx.arcTo(rightBoxX + rightPadding, progressBarY + progressBarHeight, rightBoxX + rightPadding, progressBarY, barRadius);
			ctx.arcTo(rightBoxX + rightPadding, progressBarY, rightBoxX + rightPadding + progressBarWidth, progressBarY, barRadius);
			ctx.closePath();
			ctx.fill();
		
			// 绘制实际得分的渐变色进度条
			const gradient = ctx.createLinearGradient(rightBoxX + rightPadding, 0, rightBoxX + rightPadding + progressBarWidth, 0);
			const gradientColors = this.parseGradient(dimensionData.pfztfb);
			gradientColors.forEach(c => gradient.addColorStop(c.stop, c.color));
			ctx.fillStyle = gradient;
			ctx.save();
			ctx.clip(); // 使用上面的圆角矩形路径进行裁剪
			ctx.fillRect(rightBoxX + rightPadding, progressBarY, scoreWidth, progressBarHeight);
			ctx.restore();
		
			// 绘制分数框 (要求 4)
			const scoreFontSize = 12;
			const scorePaddingY = 4; // 上下内边距
			const scorePaddingX = 7; // 左右内边距
			const scoreBoxRadius = 4;
			
			ctx.font = `bold ${scoreFontSize}px sans-serif`;
			const scoreTextMetrics = ctx.measureText(scoreItem.avgScore>25?25:scoreItem.avgScore);
			const scoreBoxWidth = scoreTextMetrics.width + scorePaddingX * 2;
			const scoreBoxHeight = scoreFontSize + scorePaddingY * 2;
		
			// 计算分数框的位置，使其右端对齐在进度条的末端
			const scoreBoxX = rightBoxX + rightPadding + scoreWidth - scoreBoxWidth;
			// 垂直居中于进度条
			const scoreBoxY = progressBarY + (progressBarHeight / 2) - (scoreBoxHeight / 2);
		
			// 绘制阴影
			ctx.save();
			ctx.shadowColor = dimensionData.bcolor;
			ctx.shadowBlur = 6;
			ctx.shadowOffsetX = 0;
			ctx.shadowOffsetY = 2;
			
			// 绘制分数框背景和边框
			ctx.fillStyle = '#FFFFFF';
			ctx.strokeStyle = dimensionData.bcolor;
			ctx.lineWidth = 1;
			ctx.beginPath();
			ctx.moveTo(scoreBoxX + scoreBoxRadius, scoreBoxY);
			ctx.arcTo(scoreBoxX + scoreBoxWidth, scoreBoxY, scoreBoxX + scoreBoxWidth, scoreBoxY + scoreBoxHeight, scoreBoxRadius);
			ctx.arcTo(scoreBoxX + scoreBoxWidth, scoreBoxY + scoreBoxHeight, scoreBoxX, scoreBoxY + scoreBoxHeight, scoreBoxRadius);
			ctx.arcTo(scoreBoxX, scoreBoxY + scoreBoxHeight, scoreBoxX, scoreBoxY, scoreBoxRadius);
			ctx.arcTo(scoreBoxX, scoreBoxY, scoreBoxX + scoreBoxWidth, scoreBoxY, scoreBoxRadius);
			ctx.closePath();
			ctx.fill();
			ctx.stroke();
			ctx.restore();
		
			// 绘制分数文字
			ctx.fillStyle = '#002846';
			ctx.font = `bold ${scoreFontSize}px sans-serif`;
			ctx.textAlign = 'center';
			ctx.textBaseline = 'middle';
			ctx.fillText((scoreItem.avgScore>25?25:scoreItem.avgScore), scoreBoxX + scoreBoxWidth / 2, scoreBoxY + scoreBoxHeight / 2);
		},
		// 辅助函数：绘制自动换行的文字
		// 辅助函数：绘制自动换行且垂直居中的文字
		drawWrappedText(ctx, text, x, y_center, lineHeight, maxWidth) {
		    // 1. 将文本分割成多行
		    let words = text.split('');
		    let lines = [];
		    let currentLine = '';
		
		    for (let n = 0; n < words.length; n++) {
		        let testLine = currentLine + words[n];
		        let metrics = ctx.measureText(testLine);
		        let testWidth = metrics.width;
		        if (testWidth > maxWidth && n > 0) {
		            lines.push(currentLine);
		            currentLine = words[n];
		        } else {
		            currentLine = testLine;
		        }
		    }
		    lines.push(currentLine); // 加入最后一行
		
		    // 2. 计算文本块的总高度
		    const totalTextHeight = lines.length * lineHeight;
		
		    // 3. 计算绘制第一行文本的起始 Y 坐标
		    // y_center 是外部传入的容器中心点
		    // 我们从容器中心点上移一半文本总高度，得到文本块的顶部位置
		    let startY = y_center - totalTextHeight / 2;
		
		    // 4. 逐行绘制
		    // ctx.textBaseline = 'middle' 是在外部设置的，所以我们绘制每一行时，
		    // Y坐标需要是该行所在矩形区域的垂直中心。
		    for (let i = 0; i < lines.length; i++) {
		        // 计算当前行文本的中心Y坐标
		        const lineY = startY + (i * lineHeight) + (lineHeight / 2);
		        ctx.fillText(lines[i], x, lineY);
		    }
		},
		// 辅助函数：解析 CSS linear-gradient 字符串
		parseGradient(gradientString) {
			const colorStops = [];
			// 简化解析，仅适用于 "linear-gradient(90deg, #RRGGBB 0%, #RRGGBB 100%)" 格式
			const matches = gradientString.match(/#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})\s+(\d+)%/g);
			if (matches) {
				matches.forEach(match => {
					const parts = match.split(' ');
					colorStops.push({ color: parts[0], stop: parseInt(parts[1]) / 100 });
				});
			}
			return colorStops;
		},
		
		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 xdata = ['宗旨与动机', '外部流程、系统与结构', '关系', '内部流程、系统与结构', '学习', '领导力'].reverse();
            let yvalue = [40, 25, 30, 35, 33, 47].reverse();
			let ycolor = [['#771E6A','#771E6A'],['#009191','#009191'],['#FFD750','#FFD750'],['#4EB2B2','#4EB2B2'],['#AFCDF5','#AFCDF5'],['#002846','#002846']].reverse();
            let yData = yvalue.map((v, i) => {
				return {
					value: v,
					itemStyle: {
						color: new echarts.graphic.LinearGradient(
							0, 0, 1, 0,
							[
								{ offset: 0, color: ycolor[i][0] },
								{ offset: 1, color: ycolor[i][1] }
							]
						),
                        borderRadius: [0, 4, 4, 0] 
					}
				};
			});
            const chart = await this.$refs.ztzdfxRef.init(echarts);
            let option = {
				grid: {
                  left: '2%',
                  right: '10%',
                  bottom:  '0%',
                  top: '10%',
				  containLabel: true
				},
				xAxis: {
				  type: 'value',
				  boundaryGap: [0, 0.01],
				  splitLine: {
					show: false
				  },
					// 隐藏X轴轴线和标签，使图表更干净
				  axisLine: {
					show: false
				  },
				  axisLabel: {
					show: false // X轴刻度值也不显示
				  }
				},
				yAxis: {
				  type: 'category',
				  data: xdata,
				  axisLine: {
					show: true, // 设置为 true 来显示Y轴的轴线
					lineStyle: {
					  color: '#ECEEF5',
					  width: 1
					}
				  },
				  // 隐藏Y轴上的小刻度线（如果你想保留可以设为true）
				  axisTick: {
					  show: false
				  },
				  axisLabel: {
					color: '#193D59',
					fontSize: 10*this.scale
				  }
				},
				series: [
				  {
					type: 'bar',
					barWidth: `${8*this.scale}px`,
					data: yData
				  }
				]
            };
            chart.setOption(option);
			this.isChartReady = true;
			this.$nextTick(() => {
				this.calculatePdfContainerHeight();
			});
        },
      }
    };
</script>

<style scoped lang="scss">
	.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;
	}
	
	.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;
		}
	}
	
	@import '../static/pdf.scss';
</style>