<template>
	<!-- 页面元信息，用于控制页面滚动（小程序和App） -->
	<page-meta :page-style="pageScrollDisabled ? 'overflow: hidden;' : ''"></page-meta>
	<view class="member-consume-container">
		<view class="form-card">
			<view class="form-content">
				<form @submit="handleFormSubmit">
					<!-- 会员选择 -->
					<view class="form-group">
						<text class="form-label">会员</text>
						<view class="custom-select" @tap="removeid?'':iskh?openSelectModal('hy'):''">
							<text class="select-text">{{ formData.hy || '请选择会员' }}</text>
							<text class="select-arrow">▼</text>
						</view>
					</view>

					<!-- 耗卡日期 - 只有新增耗卡时且为授权用户才显示 -->
					<view class="form-group" v-if="canEditDate && !removeid">
						<text class="form-label">耗卡日期</text>
						<view class="input-wrapper">
							<picker :disabled="istime" mode="date" :value="formData.hksj" @change="onDateChange">
								<view class="custom-select">
									<text class="select-text">{{ formData.hksj || '请选择耗卡日期' }}</text>
									<text class="select-arrow">▼</text>
								</view>
							</picker>
						</view>
					</view>
					
					<!-- 品项明细 -->
					<view class="form-group">
						<text class="form-label">品项明细</text>
						<view class="px-container">
							<view v-for="(px, index) in pxList" :key="index" class="px-row">
								<!-- 品项选择区域 -->
								<view v-if="px.px && px.pxmc" class="px-info">
									<view class="px-info-title">{{ px.pxmc }}</view>
									<view class="px-info-details">
										<view class="px-info-item">
											<text class="px-info-label">单价:</text>
											<text class="px-info-value">¥{{ px.pxjg || 0 }}</text>
										</view>
										<view class="px-info-item" v-if="px.TotalPurchased ">
											<text class="px-info-label">总购买:</text>
											<text class="px-info-value">{{ px.TotalPurchased || 0 }}</text>
										</view>
										<view class="px-info-item" v-if="px.ConsumedCount ">
											<text class="px-info-label">已消费:</text>
											<text class="px-info-value">{{ px.ConsumedCount || 0 }}</text>
										</view>
										<view class="px-info-item" v-if="px.RemainingCount">
											<text class="px-info-label">剩余:</text>
											<text class="px-info-value">{{ px.RemainingCount || 0 }}</text>
										</view>
										<view class="px-info-item">
											<text class="px-info-label">来源:</text>
											<text class="px-info-value">{{ px.sourceType || "" }}</text>
										</view>
										<view class="px-info-item" >
											<text class="px-info-label">科美手工费:</text>
											<text class="px-info-value">{{ px.techBeautyLaborCost || "0" }}</text>
										</view>
										<view class="px-info-item">
											<text class="px-info-label">健康师手工费:</text>
											<text class="px-info-value">{{ px.healthCoachLaborCost || "0" }}</text>
										</view>
										<view class="px-info-item">
											<text class="px-info-label">总业绩:</text>
											<text class="px-info-value">{{ px.pxjg * px.projectNumber || "0" }}</text>
										</view>
									</view>
								</view>
								<view v-else class="px-select" @tap="selectPx(index)">
									选择品项
								</view>

								<!-- 次数输入框 -->
								<input :disabled="px.RemainingCount?false:true" type="number" class="px-number" placeholder="次数" min="1" :max="px.RemainingCount"
									step="1" v-model="px.projectNumber" @input="updatePxNumber(index, $event)">

								<!-- 删除按钮 -->
								<button type="button" class="px-delete" @tap="deletePxRow(index)">删除</button>

								<!-- 第三行：健康师和科技部老师 -->
								<view class="px-row-third">
									<!-- 健康师选择 -->
									<view class="px-staff-section">
										<view class="px-jks-select" v-if="px.qt2 != '医美'" @tap="selectPxJks(index)">
											添加健康师
										</view>
										<view class="px-jks-list"
											v-if="px.lqXhJksyjList && px.lqXhJksyjList.length > 0">
											<view v-for="(jks, jksIndex) in px.lqXhJksyjList" :key="jksIndex"
												class="px-staff-item">
												<view class="px-staff-header">
													<text class="px-staff-name">{{ jks.jksxm }}</text>
													<button v-if="px.qt2 != '医美'" class="px-staff-remove"
														@click="removePxJks(index, jksIndex)">删除</button>
												</view>
												<view class="px-staff-fields">
													<view class="px-staff-row">
														<view class="px-staff-field">
															<text class="px-staff-field-label">业绩</text>
															<input disabled type="text" v-model="jks.jksyj" placeholder="请输入业绩"
																@change="updateJksField(index, jksIndex, 'jksyj', $event)">
														</view>
														<view v-if="px.qt2 != '医美'" class="px-staff-field">
															<text class="px-staff-field-label">手工费</text>
															<input disabled type="number" v-model="jks.laborCost"
																placeholder="手工费" min="0" step="0.01"
																@change="updateJksField(index, jksIndex, 'laborCost', $event)">
														</view>
													</view>
													<view v-if="px.qt2 != '医美'" class="px-staff-row">
														<view class="px-staff-field">
															<text class="px-staff-field-label">次数</text>
															<input disabled type="number" v-model="jks.kdpxNumber"
																placeholder="次数" min="0" step="1"
																@change="updateJksField(index, jksIndex, 'kdpxNumber', $event)">
														</view>
														<view class="px-staff-field">
															<!-- 占位，保持布局平衡 -->
														</view>
													</view>
												</view>
											</view>
										</view>
									</view>

									<!-- 科技部老师选择 -->
									<view class="px-staff-section">
										<view class="px-kjb-select" @tap="selectPxKjb(index)"
											:style="{display: px.qt2 === '科美' ? 'block' : 'none'}">
											添加科技部老师
										</view>
										<view class="px-kjb-list"
											v-if="px.lqXhKjbsyjList && px.lqXhKjbsyjList.length > 0">
											<view v-for="(kjb, kjbIndex) in px.lqXhKjbsyjList" :key="kjbIndex"
												class="px-staff-item">
												<view class="px-staff-header">
													<text class="px-staff-name">{{ kjb.kjblsxm }}</text>
													<button class="px-staff-remove"
														@click="removePxKjb(index, kjbIndex)">删除</button>
												</view>
												<view class="px-staff-fields">
													<view class="px-staff-row">
														<view class="px-staff-field">
															<text class="px-staff-field-label">业绩</text>
															<input disabled type="text" v-model="kjb.kjblsyj" placeholder="请输入业绩"
																@change="updateKjbField(index, kjbIndex, 'kjblsyj', $event)">
														</view>
														<view class="px-staff-field">
															<text class="px-staff-field-label">手工费</text>
															<input disabled type="number" v-model="kjb.laborCost"
																placeholder="手工费" min="0" step="0.01"
																@change="updateKjbField(index, kjbIndex, 'laborCost', $event)">
														</view>
													</view>
													<view class="px-staff-row">
														<view class="px-staff-field">
															<text class="px-staff-field-label">次数</text>
															<input disabled type="number" v-model="kjb.hdpxNumber"
																placeholder="次数" min="0" step="1"
																@change="updateKjbField(index, kjbIndex, 'hdpxNumber', $event)">
														</view>
														<view class="px-staff-field">
															<!-- 占位，保持布局平衡 -->
														</view>
													</view>
												</view>
											</view>
										</view>
									</view>

									<!-- 陪同选择（仅当 isAllowAccompanied 为 1 时显示） -->
									<view class="px-staff-section" v-if="px.isAllowAccompanied == 1">
										<view class="px-jks-select" @tap="selectAccompaniedJks(index)">
											添加陪同健康师
										</view>
										<view class="px-jks-list"
											v-if="px.accompaniedJksList && px.accompaniedJksList.length > 0">
											<view v-for="(accompaniedJks, accompaniedIndex) in px.accompaniedJksList" :key="accompaniedIndex"
												class="px-staff-item">
												<view class="px-staff-header">
													<text class="px-staff-name">{{ accompaniedJks.jksxm }}</text>
													<button class="px-staff-remove"
														@click="removeAccompaniedJks(index, accompaniedIndex)">删除</button>
												</view>
												<view class="px-staff-fields">
													<view class="px-staff-row">
														<!-- <view class="px-staff-field">
															<text class="px-staff-field-label">是否陪同</text>
															<input type="number" v-model="accompaniedJks.isAccompanied"
																placeholder="是否陪同" min="0" max="1" step="1"
																@change="updateAccompaniedJksField(index, accompaniedIndex, 'isAccompanied', $event)">
														</view> -->
														<view class="px-staff-field">
															<text class="px-staff-field-label">陪同次数</text>
															<input type="digit" v-model="accompaniedJks.accompaniedProjectNumber"
																placeholder="陪同次数" min="0" step="1"
																@change="updateAccompaniedJksField(index, accompaniedIndex, 'accompaniedProjectNumber', $event)">
														</view>
													</view>
												</view>
											</view>
										</view>
									</view>
								</view>
							</view>
						</view>
						<button type="button" class="btn-add-px" @tap="addPxRow">添加品项</button>
					</view>

					<!-- 消费金额 -->
					<view class="form-group">
						<text class="form-label">消费金额</text>
						<view class="input-wrapper">
							<input type="number" v-model="formData.xfje" placeholder="自动计算" min="0" step="0.01"
								disabled>
						</view>
					</view>

					<!-- 手工费用 -->
					<view class="form-group">
						<text class="form-label">手工费用</text>
						<view class="input-wrapper">
							<input type="number" v-model="formData.sgfy" placeholder="自动计算" min="0" step="0.01"
								disabled>
						</view>
					</view>

					<!-- 是否加班 - 只在晚上7点半后显示 -->
					<view class="form-group" v-if="showOvertimeOption && !removeid">
						<text class="form-label">是否加班</text>
						<text class="tips-text" style="display: block; margin: 8rpx 0; font-size: 24rpx; color: #666;">7点30后实际操作才选择加班</text>
						<view class="input-wrapper">
							<checkbox-group @change="onOvertimeChange">
								<view class="checkbox-wrapper" @tap.stop="toggleOvertime">
									<checkbox value="overtime" :checked="formData.isOvertime" />
									<text class="checkbox-label">加班</text>
								</view>
							</checkbox-group>
							<!-- 加班系数下拉选择 -->
							<view v-if="formData.isOvertime" class="overtime-select-wrapper">
								<picker mode="selector" :range="overtimeOptions" :value="overtimeIndex" @change="onOvertimeCoefficientChange">
									<view class="custom-select">
										<text class="select-text">{{ formData.overtimeCoefficient > 0 ? formData.overtimeCoefficient : '请选择加班系数' }}</text>
										<text class="select-arrow">▼</text>
									</view>
								</picker>
							</view>
						</view>
					</view>
					<view class="form-group" v-else-if="removeid">
						<text class="form-label">是否加班</text>
						<view class="input-wrapper">
							<view class="custom-select">
								<text class="select-text">{{ formData.overtimeCoefficient > 0 ? formData.overtimeCoefficient : '否' }}</text>
								<!-- <text class="select-arrow">▼</text> -->
							</view>
						</view>
					</view>
					<!-- 会员签字 -->
					<view class="form-group" v-if="!removeid">
						<text class="form-label">会员签字</text>
						<view class="input-wrapper">
							<view v-if="!memberSignature" class="signature-placeholder">
								<button @click="openSignatureModal" class="btn-signature-placeholder">
									<text class="signature-placeholder-text">点击进行签字</text>
								</button>
							</view>
							<view v-if="memberSignature" class="signature-preview">
								<text class="preview-label">签字预览：</text>
								<image @tap="previewSignature(memberSignature)" :src="memberSignature"
									class="signature-image" mode="aspectFit" />
								<view class="signature-actions">
									<button @click="openSignatureModal" class="btn-re-signature">重新签字</button>
									<button @click="clearMemberSignature" class="btn-clear-signature">清除签字</button>
								</view>
							</view>
						</view>
					</view>
					<view class="form-group" v-else-if="memberSignature&&removeid">
						<text class="form-label">会员签字</text>
						<view class="input-wrapper">
							<view class="signature-preview">
								<image @tap="previewSignature(baseUrl+memberSignature)" :src="baseUrl+memberSignature"
									class="signature-image" mode="aspectFit" />
							</view>
						</view>
					</view>


					<!-- 提交按钮 -->
					<view class="btn-group">
						<button type="submit" class="btn btn-primary"
							@tap="issubmitOrder?submitConsume():null">{{ issubmitOrder?'提交':'提交中...' }}</button>
					</view>
				</form>
			</view>
		</view>

		<!-- 选择弹窗 -->
		<SearchSelectModal :show="showModal" :title="modalTitle" :options="currentOptions" :loading="modalLoading"
			:has-more="hasMoreData" :search-param="searchParam" 
			:show-cross-store="currentSelectField === 'hy' || currentSelectField === 'jks'"
			:is-cross-store="currentSelectField === 'jks' ? !filterByStore : isCrossStore"
			@confirm="handleModalConfirm" @close="closeModal"
			@load-more="handleLoadMore" @refresh="handleRefresh" @search="handleSearch"
			@cross-store-change="onCrossStoreChange" />

		<!-- 消息提示 -->
		<u-toast ref="uToast"></u-toast>

		<!-- 全屏签字弹窗 -->
		<view v-if="showSignatureModal" class="signature-modal-overlay" @tap="closeSignatureModal">
			<view class="signature-modal" @tap.stop>
				<view class="signature-modal-header">
					<text class="signature-modal-title"></text>
					<button @click="closeSignatureModal" class="btn-close-modal">×</button>
				</view>
				<view class="signature-modal-content">
					<SignaturePad :width="800" :height="500" :line-width="4" stroke-color="#2e7d32"
						:px-info="signaturePxInfo" signature-type="consume"
						@confirm="handleSignatureConfirm" @clear="handleSignatureClear" ref="signaturePadModal" />
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import SearchSelectModal from '@/components/SearchSelectModal.vue'
	import SignaturePad from '@/components/SignaturePad.vue'
	import memberApi from '@/apis/modules/member.js'
	import lxApi from '@/apis/modules/lx.js'
	import projectApi from '@/apis/modules/project.js'
	import appointmentApi from '@/apis/modules/appointment.js'
	import consumeApi from '@/apis/modules/consume.js'
	import config from '@/common/config.js'

	export default {
		components: {
			SearchSelectModal,
			SignaturePad
		},
		data() {
			return {
				istime:true,
				iskh:true,
				appointmentId: null,
				issubmitOrder: true,
				baseUrl: config.getImgBaseUrl(),
				// 表单数据
				formData: {
					hy: '',
					hyzh: '',
					hymc: '',
					gklx: '',
					hksj: '', // 耗卡日期
					xfje: '',
					sgfy: '',
					isOvertime: false, // 是否加班
					overtimeCoefficient: 0 // 加班系数，默认0
				},

				// 会员签字
				memberSignature: '',
				showSignatureModal: false,
				scrollTop: 0,
				signaturePxInfo: null, // 签字时显示的品项信息

				// 选中的值
				selectedValues: {
					hy: null
				},

				// 品项列表
				pxList: [],

				// 弹窗相关
				showModal: false,
				modalTitle: '',
				currentSelectField: '',
				currentOptions: [],
				modalLoading: false,
				hasMoreData: true,
				currentPage: 1,
				pageSize: 20,
				searchKeyword: '',
				searchParam: '',

				// 用户信息
				userInfo: null,

				// 跨店相关
				isCrossStore: false,
				// 健康师门店筛选（默认筛选本门店）
				filterByStore: true,

				// 选项数据
				jksOptions: [],
				kjbOptions: [],

				// 当前选择的行索引
				currentRowIndex: -1,
				currentJksIndex: -1,
				currentKjbIndex: -1,
				mdxx: null,
				removeinfo: {},
				removeid: null,
				
				// 页面滚动禁止状态（用于小程序和App）
				pageScrollDisabled: false,
				
				// 加班系数选项
				overtimeOptions: [0.5, 1],
				
				// 陪同模式标识
				isAccompaniedMode: false
			}
		},
		onLoad(options) {
			this.initializePage(options);
		},
		onShow() {
			this.getistime()
		},
		onUnload() {
			// 页面卸载时恢复页面滚动
			this.enablePageScroll();
		},
		computed: {
			// 检查当前用户是否可以修改耗卡日期
			canEditDate() {
				// && this.userInfo.userId === '18628973287';
				return this.userInfo 
			},
		// 判断是否超过晚上8点，决定是否显示加班选项
		showOvertimeOption() {
			// return true;
			const now = new Date();
			const hours = now.getHours();
			// 判断是否超过20:00（八点）
			return hours >= 20;
		},
			// 获取当前加班系数在选项数组中的索引
			overtimeIndex() {
				const index = this.overtimeOptions.indexOf(this.formData.overtimeCoefficient);
				return index >= 0 ? index : 0;
			}
		},
		methods: {
			getistime(){
				this.istime = true
				const menuData = uni.getStorageSync('appMenuData') || []
				if (Array.isArray(menuData) && menuData.length > 0) {
					const rootNode = menuData.find(item => item.fullName == 'app时间选择开关按钮')
					// console.error(rootNode)
					if (rootNode) {
						console.error('时间选择开关按钮')
						this.istime = false
					}
				}
			},
			// 处理日期变化
			onDateChange(e) {
				this.formData.hksj = e.detail.value;
			},
			
			// 跨店开关变化
			onCrossStoreChange(value) {
				if (this.currentSelectField === 'jks') {
					// 健康师选择：filterByStore 与 value 相反（value=true 表示跨店，filterByStore=false 表示不筛选门店）
					this.filterByStore = !value;
					// 重新加载健康师数据
					if (this.showModal) {
						this.currentPage = 1;
						this.hasMoreData = true;
						this.loadOptionsData('jks', 1, this.searchKeyword);
					}
				} else {
					this.isCrossStore = value;
					// 如果弹窗已打开且正在选择会员，重新加载数据
					if (this.showModal && this.currentSelectField === 'hy') {
						this.currentPage = 1;
						this.hasMoreData = true;
						this.loadOptionsData('hy', 1, this.searchKeyword);
					}
				}
			},
			
			// 切换加班状态（点击容器时触发）
			toggleOvertime() {
				this.formData.isOvertime = !this.formData.isOvertime;
				this.handleOvertimeChange(this.formData.isOvertime);
			},
			
			// 处理是否加班变化
			onOvertimeChange(e) {
				console.log('onOvertimeChange', e);
				// checkbox-group 的 change 事件，e.detail.value 是一个数组，包含所有选中的值
				// const checked = e.detail.value && e.detail.value.length > 0 && e.detail.value.includes('overtime');
				// this.formData.isOvertime = checked;
				// this.handleOvertimeChange(checked);
			},
			
			// 处理加班状态变化的统一逻辑
			handleOvertimeChange(isOvertime) {
				if (!isOvertime) {
					// 如果取消勾选，重置加班系数为0
					this.formData.overtimeCoefficient = 0;
				} else {
					// 如果勾选，默认选择第一个选项（0.5）
					if (!this.formData.overtimeCoefficient || this.formData.overtimeCoefficient === 0) {
						this.formData.overtimeCoefficient = 0.5;
					}
				}
			},
			
			// 处理加班系数选择变化
			onOvertimeCoefficientChange(e) {
				const index = e.detail.value;
				this.formData.overtimeCoefficient = this.overtimeOptions[index];
			},
			
			// 签字相关方法
			async newUploadBase64Image() {
				let info = null;
				await lxApi.UploadBase64Image({
					"base64Data": this.memberSignature,
					"imageType": "png",
					"fileName": "memberSignature.png"
				}).then(res => {
					console.log('UploadBase64Image', res);
					if (res.code == 200) {
						info = res.data;
					}
				})
				return info
			},

			previewSignature(e) {
				console.log('previewSignature', e);
				uni.previewImage({
					urls: [e]
				});
			},

			// 签字确认
			handleSignatureConfirm(signatureData) {
				this.memberSignature = signatureData.dataUrl;
				// 延迟关闭，让用户看到提示信息
				// setTimeout(() => {
				// 	this.showSignatureModal = false;
				// 	// 恢复页面滚动
				// 	this.enablePageScroll();
				// 	uni.showToast({
				// 		title: '签字确认成功',
				// 		icon: 'success'
				// 	});
				// }, 2000);
			},

			handleSignatureClear() {
				this.memberSignature = '';
			},

			clearMemberSignature() {
				this.memberSignature = '';
				if (this.$refs.signaturePad) {
					this.$refs.signaturePad.clearSignature();
				}
				uni.showToast({
					title: '签字已清除',
					icon: 'success'
				});
			},

		// 全屏签字相关方法
		openSignatureModal() {
			// 隐藏键盘，防止点击签字时弹出键盘
			uni.hideKeyboard();
			// 计算品项信息
			this.calculateSignaturePxInfo();
			this.showSignatureModal = true;
			// 禁止页面滚动
			this.disablePageScroll();
		},
			
			// 计算签字时显示的品项信息
			calculateSignaturePxInfo() {
				if (!this.pxList || this.pxList.length === 0) {
					this.signaturePxInfo = {
						items: [],
						actualPrice: '0.00'
					};
					return;
				}
				
				// 收集所有品项信息，每条包含品项名、类型和数量
				const items = [];
				
				this.pxList.forEach(px => {
					if (px.pxmc) {
						items.push({
							name: px.pxmc,
							count: parseInt(px.projectNumber) || 0,
							type: px.sourceType || '购买'
						});
					}
				});
				
				// 消费金额作为实付金额
				const actualPrice = parseFloat(this.formData.xfje) || 0;
				
				this.signaturePxInfo = {
					items: items,
					actualPrice: actualPrice.toFixed(2)
				};
			},

			closeSignatureModal() {
				this.showSignatureModal = false;
				// 恢复页面滚动
				this.enablePageScroll();
			},

		// 禁止页面滚动
		disablePageScroll() {
			// #ifdef H5
			// 获取当前滚动位置
			this.scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;
			// 设置页面不可滚动
			document.body.style.overflow = 'hidden';
			document.body.style.position = 'fixed';
			document.body.style.width = '100%';
			document.body.style.top = `-${this.scrollTop}px`;
			// #endif
			// #ifdef APP-PLUS || MP
			// App 和小程序中，通过 page-meta 组件禁止页面滚动
			this.pageScrollDisabled = true;
			// #endif
		},

		// 恢复页面滚动
		enablePageScroll() {
			// #ifdef H5
			// 恢复页面滚动
			document.body.style.overflow = '';
			document.body.style.position = '';
			document.body.style.width = '';
			document.body.style.top = '';
			// 恢复滚动位置
			if (this.scrollTop !== undefined) {
				window.scrollTo(0, this.scrollTop);
			}
			// #endif
			// #ifdef APP-PLUS || MP
			// App 和小程序中，恢复页面滚动
			this.pageScrollDisabled = false;
			// #endif
		},

			clearSignatureModal() {
				if (this.$refs.signaturePadModal) {
					this.$refs.signaturePadModal.clearSignature();
				}
			},

			confirmSignatureModal() {
				if (this.$refs.signaturePadModal) {
					this.$refs.signaturePadModal.confirmSignature();
				}
			},
			async getpxqtlist(list){
				for(let i = 0; i < list.length; i++){
					list[i].projectNumber = list[i].originalProjectNumber ;
					let px = list[i].px;
					const detailResult = await lxApi.getPxDetail(px);
					list[i].qt2 = detailResult.data.qt2 || "";
					// list[i].sgf = detailResult.data.sgf || 0;
					list[i].healthCoachLaborCost = detailResult.data.healthCoachLaborCost || 0;
					list[i].techBeautyLaborCost = detailResult.data.techBeautyLaborCost || 0;
					list[i].isAllowAccompanied = detailResult.data.isAllowAccompanied || 0;
					list[i].beautyType = detailResult.data.beautyType || '';
					// 初始化陪同相关字段
					if (!list[i].accompaniedJksList) {
						list[i].accompaniedJksList = [];
					}
					let jkslist = []
					let kjblist = []
					let accompaniedJksList = []
					list[i].lqXhJksyjList.forEach(jks => {
						jks.kdpxNumber = jks.originalKdpxNumber;
						jks.laborCost = jks.originalLaborCost;
						if(jks.isAccompanied == 0){
							jkslist.push(jks);
						} else {
							accompaniedJksList.push(jks);
						}
					});
					list[i].lqXhKjbsyjList.forEach(kjb => {
						kjb.kdpxNumber = kjb.originalKdpxNumber;
						kjb.laborCost = kjb.originalLaborCost;
						kjblist.push(kjb);
					});
					list[i].lqXhJksyjList = jkslist;
					list[i].lqXhKjbsyjList = kjblist;
					list[i].accompaniedJksList = accompaniedJksList;
				}
				this.pxList = list;
				console.log(this.pxList);
				this.calculateTotalAmounts();
				this.$forceUpdate();
			},
			// 初始化页面
			async initializePage(options) {
				try {
					// 获取用户信息
					this.userInfo = uni.getStorageSync('userInfo');
					if (!this.userInfo || Object.keys(this.userInfo).length === 0) {
						uni.showToast({
							title: '请先登录',
							icon: 'none'
						});
						setTimeout(() => {
							uni.reLaunch({
								url: '/pages/login/login'
							});
						}, 1500);
						return;
					}
					if (options.id) {
						this.removeid = options.id;
						this.API.getConsumeDetail(options.id).then(res => {
							this.removeinfo = res.data;
							this.formData.hy = res.data.hymc;
							this.selectedValues.hy = res.data.hy;
							this.formData.xfje = res.data.xfje;
							this.formData.sgfy = res.data.sgfy;
							this.formData.overtimeCoefficient = res.data.overtimeCoefficient;
							this.getpxqtlist(res.data.lqXhPxmxList)
							let hyqz = res.data.signatureFile ? JSON.parse(res.data.signatureFile) : [];
							this.memberSignature = hyqz.length > 0 ? hyqz[0].url : '';

						});
					} else if(options.appointmentId){
						this.iskh = false
						this.appointmentId = options.appointmentId;
						const response = await this.API.getMemberDetail(options.gk);
						if(response.code === 200 && response.data){
						
							this.formData.hy = response.data.khmc;
							this.selectedValues.hy = response.data.id;
							// 补充会员相关信息
							this.formData.hyzh = response.data.id;
							this.formData.hymc = response.data.khmc;
							this.formData.gklx = response.data.khlx || '';
						}
						// 设置默认日期为当前日期
						this.formData.hksj = this.utils.gettime().substring(0, 10);
						// 添加默认的品项行
						this.addPxRow();
					} else {
						// 设置默认日期为当前日期
						this.formData.hksj = this.utils.gettime().substring(0, 10);
						// 添加默认的品项行
						this.addPxRow();
					}

					// 初始化健康师和科技部老师数据
					await this.loadInitialOptions();

					
				} catch (error) {
					console.error('页面初始化失败:', error);
					uni.showToast({
						title: '页面初始化失败',
						icon: 'none'
					});
				}
			},

			// 加载初始选项数据
			async loadInitialOptions() {
				try {
					// 并行加载健康师和科技部老师数据
					const [jksResult, kjbResult] = await Promise.all([
						this.getJksOptions(1, ''),
						this.getKjbOptions(1, '')
					]);

					console.log('健康师数据加载完成:', this.jksOptions.length);
					console.log('科技部老师数据加载完成:', this.kjbOptions.length);
				} catch (error) {
					console.error('加载初始选项数据失败:', error);
				}
				this.API.getLqMdxx(this.userInfo.mdid).then(res => {
					this.mdxx = res.data;
				});
			},

			// 打开选择弹窗
			async openSelectModal(fieldId) {
				this.currentSelectField = fieldId;
				this.showModal = true;
				this.modalTitle = '加载中...';
				this.modalLoading = true;
				this.currentPage = 1;
				this.hasMoreData = true;
				this.searchKeyword = '';
				this.currentOptions = [];

				try {
					// 设置搜索参数
					switch (fieldId) {
						case 'hy':
							this.searchParam = 'khmc';
							this.modalTitle = '选择会员';
							break;
						case 'px':
							this.searchParam = 'pxmc';
							this.modalTitle = '选择品项';
							break;
						case 'jks':
							this.searchParam = 'jksxm';
							this.modalTitle = '选择健康师';
							break;
						case 'kjb':
							this.searchParam = 'kjblsxm';
							this.modalTitle = '选择科技部人员';
							break;
					}

					await this.loadOptionsData(fieldId, 1);
				} catch (error) {
					console.error('获取选项数据失败:', error);
					this.modalTitle = '加载失败';
					this.currentOptions = [];
					uni.showToast({
						title: '数据加载失败，请检查网络连接',
						icon: 'none'
					});
				} finally {
					this.modalLoading = false;
				}
			},

			// 关闭弹窗
			closeModal() {
				this.showModal = false;
				this.currentSelectField = '';
				this.currentOptions = [];
				this.modalLoading = false;
				this.hasMoreData = true;
				this.currentPage = 1;
				this.searchKeyword = '';
				this.isAccompaniedMode = false;
			},

			// 加载选项数据
			async loadOptionsData(fieldId, page = 1, searchKeyword = '') {
				let options = [];

				switch (fieldId) {
					case 'hy':
						options = await this.getMemberOptions(page, searchKeyword);
						break;
					case 'px':
						this.hasMoreData = false;
						options = await this.getPxOptions(page, searchKeyword);
						break;
					case 'jks':
						options = await this.getJksOptions(page, searchKeyword);
						break;
					case 'kjb':
						options = await this.getKjbOptions(page, searchKeyword);
						break;
				}

				// 为每个选项添加全局唯一的 key
				options = options.map((option, index) => ({
					...option,
					uniqueKey: `${fieldId}_${page}_${index}_${Date.now()}`
				}));

				if (page === 1) {
					this.currentOptions = options;
				} else {
					this.currentOptions = [...this.currentOptions, ...options];
				}

				// 检查是否还有更多数据
				if (options.length < this.pageSize) {
					this.hasMoreData = false;
				}
			},

			// 处理弹窗确认
			handleModalConfirm(selectedOption) {
				if (this.currentSelectField && selectedOption) {
					if (this.currentSelectField === 'px') {
						// 处理品项选择
						this.handlePxSelection(selectedOption);
					} else if (this.currentSelectField === 'jks') {
						// 处理健康师选择
						if (this.isAccompaniedMode) {
							// 陪同健康师选择
							this.handleAccompaniedJksSelection(selectedOption);
						} else {
							// 普通健康师选择
							this.handleJksSelection(selectedOption);
						}
					} else if (this.currentSelectField === 'kjb') {
						// 处理科技部老师选择
						this.handleKjbSelection(selectedOption);
					} else if (this.currentSelectField === 'hy') {
						// 处理会员选择
						this.formData.hy = selectedOption.label;
						this.selectedValues.hy = selectedOption.value;
						// 补充会员相关信息
						this.formData.hyzh = selectedOption.value;
						this.formData.hymc = selectedOption.label;
						this.formData.gklx = selectedOption.khlx || '';
					}
				}
				this.closeModal();
			},

			// 处理品项选择
			async handlePxSelection(selectedOption) {
				if (this.currentRowIndex >= 0) {
					try {
						// 请求品项详细信息
						const detailResult = await lxApi.getPxDetail(selectedOption.px);
						let qt2 = "";
						let sgf = 0;
						let techBeautyLaborCost = 0
						let healthCoachLaborCost = 0
						let isAllowAccompanied = 0;

						if (detailResult.code === 200 && detailResult.data) {
							qt2 = detailResult.data.qt2 || "";
							sgf = detailResult.data.sgf || 0;
							healthCoachLaborCost = detailResult.data.healthCoachLaborCost || 0;
							techBeautyLaborCost = detailResult.data.techBeautyLaborCost || 0;
							isAllowAccompanied = detailResult.data.isAllowAccompanied || 0;
						}

						this.pxList[this.currentRowIndex] = {
							...this.pxList[this.currentRowIndex],
							px: selectedOption.px,
							pxmc: selectedOption.pxmc,
							pxjg: selectedOption.ItemPrice || 0,
							memberId: this.selectedValues.hy || "",
							sourceType: selectedOption.sourceType || "",
							totalPrice: (selectedOption.ItemPrice || 0) * (this.pxList[this.currentRowIndex]
								.projectNumber || 1),
							qt2: qt2, // 从接口获取的qt2字段
							sgf: sgf, // 从接口获取的手工费
							isAllowAccompanied: isAllowAccompanied, // 是否允许陪同
							ItemName: selectedOption.pxmc,
							ItemPrice: selectedOption.ItemPrice || 0,
							TotalPurchased: selectedOption.TotalPurchased || 0,
							ConsumedCount: selectedOption.ConsumedCount || 0,
							RemainingCount: selectedOption.RemainingCount || 0,
							BillingItemId: selectedOption.BillingItemId,
							// 陪同相关字段
							accompaniedJksList: [],// 陪同健康师列表
							techBeautyLaborCost:techBeautyLaborCost,
							healthCoachLaborCost:healthCoachLaborCost,
							beautyType:detailResult.data.beautyType || '',
						};

						// 品项修改时，清空健康师和科技部老师列表
						this.pxList[this.currentRowIndex].lqXhJksyjList = [];
						this.pxList[this.currentRowIndex].lqXhKjbsyjList = [];
						// 清空陪同健康师列表
						this.pxList[this.currentRowIndex].accompaniedJksList = [];

						this.calculateTotalAmounts();

						// 如果是医美品项，自动选择T区健康师并分配全部业绩
						if (qt2 === '医美') {
							this.$nextTick(() => {
								this.handleYimeiJksAutoSelection(this.currentRowIndex);
							});
						}

					} catch (error) {
						console.error('获取品项详情失败:', error);
						uni.showToast({
							title: '获取品项详情失败，请重试',
							icon: 'none'
						});
					}
				}
			},

			// 处理健康师选择
			async handleJksSelection(selectedOption) {
				if (this.currentRowIndex >= 0) {
					if (!this.pxList[this.currentRowIndex].lqXhJksyjList) {
						this.pxList[this.currentRowIndex].lqXhJksyjList = [];
					}

					const px = this.pxList[this.currentRowIndex];
					const jksItem = {
						jks: selectedOption.jks,
						jksxm: selectedOption.jksxm,
						jkszh: selectedOption.jkszh,
						jksyj: "",
						jsjId: "",
						kdpxid: px.BillingItemId || px.px,
						laborCost: 0, // 初始为0，后续通过均分计算
						kdpxNumber: 0, // 初始为0，后续通过均分计算
						isAccompanied: 0, // 是否陪同，默认0
						accompaniedProjectNumber: 0 // 陪同次数，默认0
					};

					this.pxList[this.currentRowIndex].lqXhJksyjList.push(jksItem);

					// 重新分配健康师的次数和手工费
					this.redistributeJksNumbersAndLaborCost(this.currentRowIndex);

					// 如果是医美品项，重新分配健康师业绩
					if (px.qt2 === '医美') {
						this.$nextTick(() => {
							// this.handleYimeiJksDistribution(this.currentRowIndex);
						});
					} else {
						// 非医美品项，如果有健康师和科技部老师，自动均分业绩
						this.$nextTick(() => {
							this.distributePerformance(this.currentRowIndex);
						});
					}

					// 异步获取金三角信息
					this.getJsjInfoByUserId(selectedOption.value, (jsjId, jsjName) => {
						jksItem.jsjId = jsjId;
					});
				}
			},

			// 处理科技部老师选择
			handleKjbSelection(selectedOption) {
				if (this.currentRowIndex >= 0) {
					if (!this.pxList[this.currentRowIndex].lqXhKjbsyjList) {
						this.pxList[this.currentRowIndex].lqXhKjbsyjList = [];
					}

					const px = this.pxList[this.currentRowIndex];
					const kjbItem = {
						kjbls: selectedOption.kjbls,
						kjblsxm: selectedOption.kjblsxm,
						kjblszh: selectedOption.kjblszh,
						kjblsyj: "",
						hkpxid: px.BillingItemId || px.px,
						laborCost: 0, // 初始为0，后续通过均分计算
						hdpxNumber: 0 // 初始为0，后续通过均分计算
					};

					this.pxList[this.currentRowIndex].lqXhKjbsyjList.push(kjbItem);

					// 重新分配科技部老师的次数和手工费
					this.redistributeKjbNumbersAndLaborCost(this.currentRowIndex);

					// 如果有健康师和科技部老师，自动均分业绩
					this.$nextTick(() => {
						this.distributePerformance(this.currentRowIndex);
					});
				}
			},

			// 处理加载更多
			async handleLoadMore(page) {
				if (this.currentSelectField && this.hasMoreData && !this.modalLoading) {
					this.modalLoading = true;
					try {
						await this.loadOptionsData(this.currentSelectField, page, this.searchKeyword);
					} catch (error) {
						console.error('加载更多数据失败:', error);
						uni.showToast({
							title: '加载失败',
							icon: 'none'
						});
					} finally {
						this.modalLoading = false;
					}
				}
			},

			// 处理刷新
			async handleRefresh() {
				if (this.currentSelectField) {
					this.currentPage = 1;
					this.hasMoreData = true;
					this.searchKeyword = '';
					await this.loadOptionsData(this.currentSelectField, 1);
				}
			},

			// 处理搜索
			async handleSearch(searchKeyword) {
				if (this.currentSelectField) {
					this.searchKeyword = searchKeyword;
					this.currentPage = 1;
					this.hasMoreData = true;
					this.modalLoading = true;

					try {
						await this.loadOptionsData(this.currentSelectField, 1, searchKeyword);
					} catch (error) {
						console.error('搜索失败:', error);
						uni.showToast({
							title: '搜索失败',
							icon: 'none'
						});
					} finally {
						this.modalLoading = false;
					}
				}
			},

			// 获取会员选项
			async getMemberOptions(page = 1, searchKeyword = '') {
				try {
					const params = {
						currentPage: page,
						pageSize: this.pageSize,
					};

					if (searchKeyword) {
						params.keyword = searchKeyword;
					}

					// 添加跨店参数
					if (!this.isCrossStore) {
						if(this.userInfo && this.userInfo.mdid) {
							params.gsmd = this.userInfo.mdid;
						} else{
							params.gsmd = '暂无';
						}
					}

					const result = await memberApi.getMemberList(params);
					if (result.code === 200 && result.data) {
						return result.data.list.map((item, index) => ({
							value: item.id,
							label: item.khmc,
							sjh: item.sjh,
							khlx: item.khlx,
							khlxName: item.khlxName,
							subtitle: '客户类型：' + (item.khlxName || '无') + '；手机号：' + (item.sjh || '无') +
								'；健康师：' + (item.mrsName || '无') + '；门店：' + (item.gsmdName || '无') + '；',
						}));
					}
					return [];
				} catch (error) {
					console.error('获取会员列表出错:', error);
					return [];
				}
			},

			// 添加品项行
			addPxRow() {
				this.pxList.push({
					px: "",
					pxmc: "",
					pxjg: 0,
					memberId: "",
					projectNumber: 1,
					sourceType: "购买",
					totalPrice: 0,
					lqXhJksyjList: [],
					lqXhKjbsyjList: [],
					qt2: "",
					isAllowAccompanied: 0,
					accompaniedJksList: []
				});
			},

			// 删除品项行
			deletePxRow(rowIndex) {
				if (this.pxList.length > 1) {
					this.pxList.splice(rowIndex, 1);
					this.calculateTotalAmounts();
				} else {
					uni.showToast({
						title: '至少需要保留一个品项',
						icon: 'none'
					});
				}
			},

			// 选择品项
			async selectPx(rowIndex) {
				this.currentRowIndex = rowIndex;
				this.openSelectModal('px');
			},

			// 获取品项选项（从会员剩余品项API获取）
			async getPxOptions(page = 1, searchKeyword = '') {
				if (!this.selectedValues.hy) {
					console.warn("请先选择会员");
					return [];
				}

				try {
					const params = {
						memberId: this.selectedValues.hy
					};

					if (searchKeyword) {
						params.xmmc = searchKeyword;
					}

					const result = await lxApi.getMemberRemainingItems(params);
					if (result.code === 200 && result.data && result.data.RemainingItems) {
						return result.data.RemainingItems.map(item => ({
							value: item.BillingItemId,
							label: item.ItemName,
							px: item.ItemId,
							pxmc: item.ItemName,
							pxjg: item.ItemPrice || 0,
							qt2: item.qt2 || "",
							RemainingCount: item.RemainingCount || 0,
							ItemPrice: item.ItemPrice || 0,
							sgf: 0,
							sourceType: item.SourceType || "购买",
							TotalPurchased: item.TotalPurchased || 0,
							ConsumedCount: item.ConsumedCount || 0,
							BillingItemId: item.BillingItemId,
							subtitle: '剩余: ' + (item.RemainingCount || 0) + '；类型：' + item.SourceType +
								';单价：' + item.ItemPrice +';备注：' + (item.Remark || '无')+ ';'
						}));
					}
					return [];
				} catch (error) {
					console.error('获取会员剩余品项出错:', error);
					return [];
				}
			},

			// 更新品项次数
			updatePxNumber(rowIndex, event) {
				const value = event.detail.value;
				console.log('value',value)
				if (this.pxList[rowIndex]) {
					let inputNumber = parseInt(value);

					// 验证不能超过剩余次数
					if (inputNumber <= 0 ) {
						inputNumber = 1;
						console.log('inputNumber',inputNumber)
						// 更新输入框显示的值
						this.$nextTick(() => {
							const inputElement = event.target;
							if (inputElement) {
								inputElement.value = inputNumber;
							}
						});
						this.$forceUpdate();
					}

					this.pxList[rowIndex].projectNumber = inputNumber;
					this.pxList[rowIndex].totalPrice = this.pxList[rowIndex].pxjg * this.pxList[rowIndex].projectNumber;
					

					// 重新分配健康师和科技部老师的次数和手工费
					this.redistributeJksNumbersAndLaborCost(rowIndex);
					this.redistributeKjbNumbersAndLaborCost(rowIndex);
					
					// 如果是医美品项，更新T区健康师业绩
					if (this.pxList[rowIndex].qt2 === '医美') {
						this.updateYimeiJksDistribution(rowIndex);
					} else {
						// 非医美品项，如果有健康师和科技部老师，自动均分业绩
						this.distributePerformance(rowIndex);
					}
				}
			},

			// 计算总消费金额和手工费用
			calculateTotalAmounts() {
				let totalXfje = 0;
				let totalSgfy = 0;

				this.pxList.forEach(px => {
					if (px.px && px.pxmc && px.pxjg && px.projectNumber) {
						const pxTotal = px.pxjg * px.projectNumber;
						totalXfje += pxTotal;
					}
					if (px.px && px.pxmc && px.projectNumber) {
						// totalSgfy += px.sgf * px.projectNumber;
						if (px.qt2 === '科美' && px.beautyType != 'cell' && px.beautyType != 'slim') {
							totalSgfy += px.techBeautyLaborCost * px.projectNumber;
						} else if(px.qt2 === '科美' && (px.beautyType == 'cell' || px.beautyType == 'slim')){
							if(px.lqXhKjbsyjList.length > 0){
								totalSgfy += px.techBeautyLaborCost * px.projectNumber;
							} else {
								totalSgfy += px.healthCoachLaborCost * px.projectNumber;
							}
						} else {
							totalSgfy += px.healthCoachLaborCost * px.projectNumber;
						}
					}
				});

				this.formData.xfje = totalXfje.toFixed(2);
				this.formData.sgfy = totalSgfy.toFixed(2);
			},

			// 选择品项健康师
			async selectPxJks(rowIndex) {
				this.currentRowIndex = rowIndex;
				this.currentJksIndex = this.pxList[rowIndex].lqXhJksyjList.length;
				this.isAccompaniedMode = false;
				this.openSelectModal('jks');
			},

			// 选择品项科技部老师
			async selectPxKjb(rowIndex) {
				this.currentRowIndex = rowIndex;
				this.currentKjbIndex = this.pxList[rowIndex].lqXhKjbsyjList.length;
				this.openSelectModal('kjb');
			},

			// 选择陪同健康师
			async selectAccompaniedJks(rowIndex) {
				this.currentRowIndex = rowIndex;
				this.isAccompaniedMode = true;
				this.openSelectModal('jks');
			},

			// 处理陪同健康师选择
			async handleAccompaniedJksSelection(selectedOption) {
				if (this.currentRowIndex >= 0) {
					if (!this.pxList[this.currentRowIndex].accompaniedJksList) {
						this.pxList[this.currentRowIndex].accompaniedJksList = [];
					}

					const px = this.pxList[this.currentRowIndex];
					const accompaniedJksItem = {
						jks: selectedOption.jks,
						jksxm: selectedOption.jksxm,
						jkszh: selectedOption.jkszh,
						jksyj: 0, // 业绩默认为0，不参与逻辑
						jsjId: "",
						kdpxid: px.BillingItemId || px.px,
						laborCost: 0, // 手工费默认为0，不参与逻辑
						kdpxNumber: 0, // 次数默认为0，不参与逻辑
						isAccompanied: 1, // 是否陪同，默认为1
						accompaniedProjectNumber: 1 // 陪同次数，需要手动填写
					};

					this.pxList[this.currentRowIndex].accompaniedJksList.push(accompaniedJksItem);
					this.isAccompaniedMode = false;
					this.$forceUpdate();

					// 异步获取金三角信息
					this.getJsjInfoByUserId(selectedOption.value, (jsjId, jsjName) => {
						accompaniedJksItem.jsjId = jsjId;
					});
				}
			},

			// 删除陪同健康师
			removeAccompaniedJks(rowIndex, accompaniedIndex) {
				if (this.pxList[rowIndex].accompaniedJksList) {
					this.pxList[rowIndex].accompaniedJksList.splice(accompaniedIndex, 1);
				}
				this.$forceUpdate();
			},

			// 更新陪同健康师字段
			updateAccompaniedJksField(rowIndex, accompaniedIndex, field, event) {
				const value = event.detail.value;
				if (this.pxList[rowIndex].accompaniedJksList && this.pxList[rowIndex].accompaniedJksList[accompaniedIndex]) {
					if (field === 'accompaniedProjectNumber' || field === 'isAccompanied') {
						this.pxList[rowIndex].accompaniedJksList[accompaniedIndex][field] = parseInt(value) || 0;
					} else {
						this.pxList[rowIndex].accompaniedJksList[accompaniedIndex][field] = value;
					}
				}
				this.$forceUpdate();
			},

			// 获取健康师选项
			async getJksOptions(page = 1, searchKeyword = '') {
				try {
					const params = {
						currentPage: page,
						pageSize: this.pageSize,
						gw: '健康师'
					};
					// 如果 filterByStore 为 true，则筛选本门店
					if (this.filterByStore && this.userInfo && this.userInfo.mdid) {
						params.mdid = this.userInfo.mdid;
					}

					if (searchKeyword) {
						params.realName = searchKeyword;
					}

					const result = await appointmentApi.getHealthWorkerList(params);
					if (result.code === 200 && result.data) {
						const options = result.data.list.map((item, index) => ({
							value: item.id,
							label: item.realName || `健康师${index + 1}`,
							fullName: item.realName || `健康师${index + 1}`,
							id: item.id,
							jks: item.id, // 添加jks字段
							jkszh: item.id,
							jksxm: item.realName || `健康师${index + 1}`,
							userName: item.userName || item.account || item.id,
							account: item.account || item.userName || item.id,
							subtitle: item.department || item.role || ''
						}));

						// 如果是第一页且没有搜索关键词，存储到jksOptions中
						if (page === 1 && !searchKeyword) {
							this.jksOptions = options;
						}

						return options;
					}
					return [];
				} catch (error) {
					console.error('获取健康师列表出错:', error);
					return [];
				}
			},

			// 获取科技部人员选项
			async getKjbOptions(page = 1, searchKeyword = '') {
				try {
					const params = {
						currentPage: page,
						pageSize: this.pageSize,
						gw: '科技老师' // 可以根据实际API调整筛选条件
					};

					if (searchKeyword) {
						params.kjblsxm = searchKeyword;
					}

					const result = await appointmentApi.getHealthWorkerList(params);
					if (result.code === 200 && result.data) {
						const options = result.data.list.map((item, index) => ({
							value: item.id,
							label: item.realName || `科技部人员${index + 1}`,
							fullName: item.realName || `科技部人员${index + 1}`,
							id: item.id,
							kjbls: item.id, // 添加kjbls字段
							kjblszh: item.id,
							kjblsxm: item.realName || `科技部人员${index + 1}`,
							userName: item.userName || item.account || item.id,
							account: item.account || item.userName || item.id,
							subtitle: item.department || item.role || ''
						}));

						// 如果是第一页且没有搜索关键词，存储到kjbOptions中
						if (page === 1 && !searchKeyword) {
							this.kjbOptions = options;
						}

						return options;
					}
					return [];
				} catch (error) {
					console.error('获取科技部人员列表出错:', error);
					return [];
				}
			},

			// 删除品项健康师
			removePxJks(rowIndex, jksIndex) {
				console.log('删除健康师:', rowIndex, jksIndex);
				if (this.pxList[rowIndex].lqXhJksyjList) {
					this.pxList[rowIndex].lqXhJksyjList.splice(jksIndex, 1);

					// 重新分配健康师的次数和手工费
					this.redistributeJksNumbersAndLaborCost(rowIndex);

					// 如果是医美品项，重新分配健康师业绩
					if (this.pxList[rowIndex].qt2 === '医美') {
						this.$nextTick(() => {
							this.handleYimeiJksDistribution(rowIndex);
						});
					} else {
						// 非医美品项，如果有健康师和科技部老师，自动均分业绩
						this.$nextTick(() => {
							this.distributePerformance(rowIndex);
						});
					}
				}
				this.$forceUpdate()
			},

			// 删除品项科技部老师
			removePxKjb(rowIndex, kjbIndex) {
				console.log('删除科技部老师:', rowIndex, kjbIndex);
				if (this.pxList[rowIndex].lqXhKjbsyjList) {
					this.pxList[rowIndex].lqXhKjbsyjList.splice(kjbIndex, 1);

					// 重新分配科技部老师的次数和手工费
					this.redistributeKjbNumbersAndLaborCost(rowIndex);

					// 如果有健康师和科技部老师，自动均分业绩
					this.$nextTick(() => {
						this.distributePerformance(rowIndex);
					});
				}
				this.$forceUpdate()
			},

			// 更新健康师字段
			updateJksField(rowIndex, jksIndex, field, event) {
				const value = event.detail.value;
				if (this.pxList[rowIndex].lqXhJksyjList && this.pxList[rowIndex].lqXhJksyjList[jksIndex]) {
					if (field === 'laborCost' || field === 'kdpxNumber') {
						this.pxList[rowIndex].lqXhJksyjList[jksIndex][field] = parseFloat(value) || 0;
					} else {
						this.pxList[rowIndex].lqXhJksyjList[jksIndex][field] = value;
					}
				}
				this.$forceUpdate()
			},

			// 更新科技部老师字段
			updateKjbField(rowIndex, kjbIndex, field, event) {
				const value = event.detail.value;
				if (this.pxList[rowIndex].lqXhKjbsyjList && this.pxList[rowIndex].lqXhKjbsyjList[kjbIndex]) {
					if (field === 'laborCost' || field === 'hdpxNumber') {
						this.pxList[rowIndex].lqXhKjbsyjList[kjbIndex][field] = parseFloat(value) || 0;
					} else {
						this.pxList[rowIndex].lqXhKjbsyjList[kjbIndex][field] = value;
					}
				}
				this.$forceUpdate()
			},

			// 处理表单提交
			handleFormSubmit(event) {
				event.preventDefault();
				this.submitConsume();
			},

			// 提交耗卡
			async submitConsume() {
				// 验证表单
				if (!this.selectedValues.hy) {
					uni.showToast({
						title: '请选择会员',
						icon: 'none'
					});
					return;
				}

				if(!this.validateForm()){
					return;
				}
				if (this.removeid) {
					// 检查是否有科美品项
					// const hasKemei = this.pxList.some(px => px.qt2 === '科美');
					// 过滤品项列表，只保留提交需要的字段
					const filteredPxList = this.pxList.map(px => ({
						billingItemId: px.BillingItemId || px.billingItemId,
						px: px.px,
						memberId: px.memberId,
						pxmc: px.pxmc,
						pxjg: px.pxjg,
						projectNumber: px.projectNumber,
						sourceType: px.sourceType,
						totalPrice: px.pxjg * px.projectNumber,
						lqXhJksyjList:  [...px.lqXhJksyjList,...px.accompaniedJksList] || [],
						lqXhKjbsyjList: px.lqXhKjbsyjList || [],
						// accompaniedJksList: px.accompaniedJksList || []
					}));
					const formData = {
						...this.removeinfo,
						xfje: this.formData.xfje,
						sgfy: this.formData.sgfy,
						lqXhPxmxList:filteredPxList.filter(px => px.px && px.pxmc),
						// overtimeCoefficient: this.formData.overtimeCoefficient || 0
					};
					console.log({...formData});
					// return;
					this.issubmitOrder = false;
					const result = await this.API.updateConsumeForNoDelete(formData)
					
					uni.hideLoading();
					if (result.code === 200) {
						uni.showToast({
							title: '修改成功！',
							icon: 'success'
						});
						this.clearForm();
						this.issubmitOrder = true;
						setTimeout(() => {
							// 返回上一页
							uni.navigateBack();
						}, 1000);
					} else {
						uni.showToast({
							title: result.msg || '提交失败，请重试',
							icon: 'none'
						});
						this.issubmitOrder = true;
					}
					
				} else {
					try {
						// 检查是否有科美品项
						const hasKemei = this.pxList.some(px => px.qt2 === '科美');

						// 过滤品项列表，只保留提交需要的字段
						const filteredPxList = this.pxList.map(px => ({
							billingItemId: px.BillingItemId,
							px: px.px,
							memberId: px.memberId,
							pxmc: px.pxmc,
							pxjg: px.pxjg,
							projectNumber: px.projectNumber,
							sourceType: px.sourceType,
							totalPrice: px.pxjg * px.projectNumber,
							lqXhJksyjList:  [...px.lqXhJksyjList,...px.accompaniedJksList] || [],
							lqXhKjbsyjList: px.lqXhKjbsyjList || [],
							// accompaniedJksList: px.accompaniedJksList || []
						}));

						// 处理会员签字
						let hyqz = []
						if (this.memberSignature) {
							let memberinfo = await this.newUploadBase64Image()
							console.error(memberinfo)
							if (memberinfo) {
								hyqz.push({
									name: memberinfo.name,
									fileId: memberinfo.name,
									url: memberinfo.url
								});
							}
						}

						// 收集表单数据
						// 处理耗卡日期：如果用户设置了日期则使用设置的日期，否则使用当前时间
						let hksjValue = this.utils.gettime();
						if (this.formData.hksj) {
							// 如果设置了日期，则添加时分秒
							hksjValue = this.formData.hksj + ' ' + new Date().toTimeString().substring(0, 8);
						}
						
						const formData = {
							md: this.userInfo.mdid || "",
							"mdbh": this.userInfo.mdid,
							"mdmc": this.mdxx.dm,
							hy: this.selectedValues.hy,
							"hyzh": this.formData.hyzh,
							"hymc": this.formData.hymc,
							"gklx": this.formData.gklx,
							xfje: this.formData.xfje,
							sgfy: this.formData.sgfy,
							hksj: hksjValue,
							sfykjb: hasKemei ? "是" : "否", // 是否有科技部
							lqXhPxmxList: filteredPxList.filter(px => px.px && px.pxmc),
							signatureFile: JSON.stringify(hyqz),
							overtimeCoefficient: this.formData.overtimeCoefficient || 0
						};

						console.log("耗卡数据:", formData);
						// return
						if(this.appointmentId){
							formData.appointmentId = this.appointmentId;
						}
						uni.showLoading({
							title: '正在提交...'
						});
						this.issubmitOrder = false;
						// 调用实际的API
						const result = await consumeApi.submitConsume(formData);

						uni.hideLoading();

						if (result.code === 200) {
							uni.showToast({
								title: '耗卡成功！',
								icon: 'success'
							});
							this.clearForm();
							this.issubmitOrder = true;
						} else {
							uni.showToast({
								title: result.msg || '提交失败，请重试',
								icon: 'none'
							});
							this.issubmitOrder = true;
						}

					} catch (error) {
						uni.hideLoading();
						console.error('提交失败:', error);
						uni.showToast({
							title: '网络错误，请稍后重试',
							icon: 'none'
						});
					}
				}



			},
			validateForm() {
				if (this.pxList.length === 0) {
					uni.showToast({
						title: '请至少添加一个品项',
						icon: 'none'
					});
					return;
				}

				// 验证每个品项的信息
				for (let i = 0; i < this.pxList.length; i++) {
					const px = this.pxList[i];

					// 验证品项基本信息
					if (!px.px || !px.pxmc) {
						uni.showToast({
							title: `第${i + 1}个品项信息不完整，请重新选择`,
							icon: 'none'
						});
						return;
					}
				}

				// 验证相同品项的次数总和不能超过剩余次数
				// 按品项分组（优先使用 BillingItemId，如果没有则使用 px）
				console.log('========== 开始验证相同品项次数总和 ==========');
				console.log('品项列表:', this.pxList.map((px, idx) => ({
					行号: idx + 1,
					品项名称: px.pxmc,
					BillingItemId: px.BillingItemId,
					px: px.px,
					次数: px.projectNumber,
					剩余次数: px.RemainingCount
				})));

				const pxGroups = new Map();
				for (let i = 0; i < this.pxList.length; i++) {
					const px = this.pxList[i];
					// 生成唯一标识：优先使用 BillingItemId，否则使用 px
					const key = px.BillingItemId;
					
					console.log(`处理第${i + 1}行: 品项=${px.pxmc}, BillingItemId=${key}, 次数=${px.projectNumber}, 剩余次数=${px.RemainingCount}`);
					
					if (!pxGroups.has(key)) {
						pxGroups.set(key, {
							items: [],
							pxName: px.pxmc || '',
							remainingCount: null
						});
						console.log(`  创建新分组: key=${key}, 品项名称=${px.pxmc}`);
					}
					
					const group = pxGroups.get(key);
					group.items.push({
						index: i,
						px: px,
						projectNumber: px.projectNumber || 0
					});
					console.log(`  添加到分组: 当前分组有${group.items.length}个品项`);
					
					// 记录第一个有 RemainingCount 的值作为该品项的剩余次数
					if (group.remainingCount === null && px.RemainingCount !== undefined && px.RemainingCount !== null) {
						group.remainingCount = px.RemainingCount;
						console.log(`  设置剩余次数: ${px.RemainingCount}`);
					}
				}

				console.log('分组结果:', Array.from(pxGroups.entries()).map(([key, group]) => ({
					key: key,
					品项名称: group.pxName,
					剩余次数: group.remainingCount,
					包含行数: group.items.length,
					行号列表: group.items.map(item => item.index + 1),
					次数列表: group.items.map(item => item.projectNumber)
				})));

				// 验证每个分组的次数总和
				for (const [key, group] of pxGroups.entries()) {
					console.log(`\n验证分组: key=${key}, 品项=${group.pxName}`);
					
					// 只验证有 RemainingCount 的品项（修改时已存在的品项可能没有此字段）
					if (group.remainingCount === null) {
						console.log(`  跳过验证: 该品项没有剩余次数字段（可能是修改时已存在的品项）`);
						continue;
					}

					// 计算该品项在所有行的次数总和
					const totalNumber = group.items.reduce((sum, item) => sum + Number(item.projectNumber), 0);
					const rowNumbers = group.items.map(item => item.index + 1).join('、');
					
					console.log(`  次数总和: ${totalNumber} (行号: ${rowNumbers})`);
					console.log(`  剩余次数: ${group.remainingCount}`);
					console.log(`  验证结果: ${totalNumber > group.remainingCount ? '❌ 失败' : '✅ 通过'}`);
					
					if (totalNumber > group.remainingCount) {
						console.error(`验证失败: 品项"${group.pxName}"在第${rowNumbers}行的次数总和(${totalNumber})超过剩余次数(${group.remainingCount})`);
						uni.showToast({
							title: `品项"${group.pxName}"在第${rowNumbers}行的次数总和(${totalNumber})不能超过剩余次数(${group.remainingCount})`,
							icon: 'none'
						});
						return;
					}
				}
				
				console.log('========== 相同品项次数总和验证通过 ==========\n');

				// 继续验证其他信息
				for (let i = 0; i < this.pxList.length; i++) {
					const px = this.pxList[i];

					// 验证健康师（特殊处理：px为cell或slim时，健康师和科技部老师至少选择一个）
					const isSpecialPx = px.beautyType == 'cell' || px.beautyType == 'slim';
					// 过滤掉陪同健康师（isAccompanied为1的健康师不参与验证）
					const normalJksList = px.lqXhJksyjList ? px.lqXhJksyjList.filter(jks => !jks.isAccompanied || jks.isAccompanied === 0) : [];
					const hasJks = normalJksList.length > 0;
					const hasKjb = px.lqXhKjbsyjList && px.lqXhKjbsyjList.length > 0;

					if (isSpecialPx) {
						// px为cell或slim时，健康师和科技部老师至少选择一个
						if (!hasJks && !hasKjb) {
							uni.showToast({
								// (px=${px.px})
								title: `第${i + 1}个品项必须至少选择一个健康师或科技部老师`,
								icon: 'none'
							});
							return;
						}
					} else {
						// 其他品项必须选择健康师
						if (!hasJks) {
							uni.showToast({
								title: `第${i + 1}个品项必须至少选择一个健康师`,
								icon: 'none'
							});
							return;
						}
					}

					// 计算健康师业绩总和（只有当选择了健康师时才进行验证）
					let jksTotalYj = 0;
					let jksTotalLaborCost = 0;
					let jksTotalNumber = 0;

					// 检查是否为医美品项
					const isYimei = px.qt2 === '医美';
					let tquJks = null; // T区健康师
					let otherJksList = []; // 其他健康师

					// 只有当选择了健康师时才进行健康师相关验证（排除陪同健康师）
					if (hasJks) {
						// 分离T区健康师和其他健康师（排除陪同健康师）
						for (let j = 0; j < normalJksList.length; j++) {
							const jks = normalJksList[j];

							// 验证健康师是否选择
							if (!jks.jks || !jks.jksxm) {
								uni.showToast({
									title: `第${i + 1}个品项的第${j + 1}个健康师必须选择`,
									icon: 'none'
								});
								return;
							}

							// 验证健康师业绩必须填写（医美品项的非T区健康师除外）
							const isTquJks = isYimei && jks.jksxm && jks.jksxm.includes('T区');
							const isNonTquJks = isYimei && !isTquJks;

							if (!isNonTquJks && (!jks.jksyj || jks.jksyj.trim() === "")) {
								uni.showToast({
									title: `第${i + 1}个品项的第${j + 1}个健康师业绩必须填写`,
									icon: 'none'
								});
								return;
							}

							// 验证业绩为数字（医美品项的非T区健康师可以为空或0）
							const yj = parseFloat(jks.jksyj || 0);
							if (isNaN(yj) || yj < 0) {
								uni.showToast({
									title: `第${i + 1}个品项的第${j + 1}个健康师业绩必须为有效数字`,
									icon: 'none'
								});
								return;
							}

							// 医美品项特殊处理：检查是否包含"T区"
							if (isYimei && jks.jksxm && jks.jksxm.includes('T区')) {
								tquJks = jks;
							} else {
								otherJksList.push(jks);
							}

							jksTotalYj += yj;
							jksTotalLaborCost += parseFloat(jks.laborCost) || 0;
							jksTotalNumber += parseInt(jks.kdpxNumber) || 0;
						}

						// 医美品项特殊验证
						if (isYimei) {
							const pxTotalAmount = px.pxjg * px.projectNumber;
							// const pxTotalLaborCost = (px.sgf || 0) * px.projectNumber;

							if (tquJks) {
								// 有T区健康师的情况
								// 验证T区健康师业绩等于品项总金额
								const tquYj = parseFloat(tquJks.jksyj);
								if (Math.abs(tquYj - pxTotalAmount) > 0.01) {
									uni.showToast({
										title: `第${i + 1}个品项是医美品项，T区健康师业绩(${tquYj.toFixed(2)})必须等于品项金额(${pxTotalAmount.toFixed(2)})`,
										icon: 'none'
									});
									return;
								}

								// 验证T区健康师次数和手工费等于品项总次数和总手工费
								// if (parseInt(tquJks.kdpxNumber) !== px.projectNumber) {
								// 	uni.showToast({
								// 		title: `第${i + 1}个品项是医美品项，T区健康师次数必须等于品项次数(${px.projectNumber})`,
								// 		icon: 'none'
								// 	});
								// 	return;
								// }
								// if (Math.abs(parseFloat(tquJks.laborCost) - pxTotalLaborCost) > 0.01) {
								// 	uni.showToast({
								// 		title: `第${i + 1}个品项是医美品项，T区健康师手工费必须等于品项手工费(${pxTotalLaborCost.toFixed(2)})`,
								// 		icon: 'none'
								// 	});
								// 	return;
								// }

								// 验证其他健康师业绩为0
								for (let k = 0; k < otherJksList.length; k++) {
									const otherJks = otherJksList[k];
									const otherYj = parseFloat(otherJks.jksyj);
									if (Math.abs(otherYj) > 0.01) {
										uni.showToast({
											title: `第${i + 1}个品项是医美品项，非T区健康师业绩必须为0`,
											icon: 'none'
										});
										return;
									}
								}

								// 验证其他健康师次数和手工费都为0
								for (let k = 0; k < otherJksList.length; k++) {
									const otherJks = otherJksList[k];
									if (parseInt(otherJks.kdpxNumber) !== 0) {
										uni.showToast({
											title: `第${i + 1}个品项是医美品项，非T区健康师次数必须为0`,
											icon: 'none'
										});
										return;
									}
									if (Math.abs(parseFloat(otherJks.laborCost)) > 0.01) {
										uni.showToast({
											title: `第${i + 1}个品项是医美品项，非T区健康师手工费必须为0`,
											icon: 'none'
										});
										return;
									}
								}
							} else {
								// 没有T区健康师的情况，按普通品项验证
								// if (Math.abs(jksTotalYj - pxTotalAmount) > 0.01) {
								// 	uni.showToast({
								// 		title: `第${i + 1}个品项的健康师业绩总和(${jksTotalYj.toFixed(2)})必须等于品项金额(${pxTotalAmount.toFixed(2)})`,
								// 		icon: 'none'
								// 	});
								// 	return;
								// }
							}
						} else {
							// 非医美品项，按原逻辑验证
							const pxTotalAmount = px.pxjg * px.projectNumber;
							// 如果同时有健康师和科技部老师，健康师组和科技老师组都获得全部业绩；否则健康师获得全部业绩
							const expectedJksAmount = pxTotalAmount; // 无论是否有科技部老师，健康师组都获得全部业绩
							// if (Math.abs(jksTotalYj - expectedJksAmount) > 0.01) {
							// 	uni.showToast({
							// 		title: `第${i + 1}个品项的健康师业绩总和(${jksTotalYj.toFixed(2)})必须等于品项金额(${pxTotalAmount.toFixed(2)})`,
							// 		icon: 'none'
							// 	});
							// 	return;
							// }
						}
					} // 结束健康师验证逻辑

					// 如果是科美品项，验证科技部老师（特殊处理：px为cell或slim允许没有科技部老师）
					if (px.qt2 === '科美') {
						if (!isSpecialPx && (!px.lqXhKjbsyjList || px.lqXhKjbsyjList.length === 0)) {
							uni.showToast({
								title: `第${i + 1}个品项是科美品项，必须至少选择一个科技部老师`,
								icon: 'none'
							});
							return;
						}

						// 只有当选择了科技部老师时才进行科技部老师相关验证
						if (hasKjb) {
							let kjbTotalYj = 0;
							let kjbTotalLaborCost = 0;
							let kjbTotalNumber = 0;
							const pxTotalAmount = px.pxjg * px.projectNumber;

							for (let k = 0; k < px.lqXhKjbsyjList.length; k++) {
								const kjb = px.lqXhKjbsyjList[k];

								// 验证科技部老师是否选择
								if (!kjb.kjbls || !kjb.kjblsxm) {
									uni.showToast({
										title: `第${i + 1}个品项的第${k + 1}个科技部老师必须选择`,
										icon: 'none'
									});
									return;
								}

								// 验证科技部老师业绩必须填写
								if (!kjb.kjblsyj || kjb.kjblsyj.trim() === "") {
									uni.showToast({
										title: `第${i + 1}个品项的第${k + 1}个科技部老师业绩必须填写`,
										icon: 'none'
									});
									return;
								}

								// 验证业绩为数字
								const yj = parseFloat(kjb.kjblsyj);
								if (isNaN(yj) || yj < 0) {
									uni.showToast({
										title: `第${i + 1}个品项的第${k + 1}个科技部老师业绩必须为有效数字`,
										icon: 'none'
									});
									return;
								}

								kjbTotalYj += yj;
								kjbTotalLaborCost += parseFloat(kjb.laborCost) || 0;
								kjbTotalNumber += parseInt(kjb.hdpxNumber) || 0;
							}

							// 如果同时有健康师和科技部老师，科技老师组获得全部业绩；否则科技部老师获得全部业绩
							const expectedKjbAmount = pxTotalAmount; // 无论是否有健康师，科技老师组都获得全部业绩
							// if (Math.abs(kjbTotalYj - expectedKjbAmount) > 0.01) {
							// 	uni.showToast({
							// 		title: `第${i + 1}个品项的科技部老师业绩总和(${kjbTotalYj.toFixed(2)})必须等于品项金额(${pxTotalAmount.toFixed(2)})`,
							// 		icon: 'none'
							// 	});
							// 	return;
							// }
						} // 结束科技部老师验证逻辑
					} else if (hasKjb && hasJks) {
						// 非科美品项，但如果同时有健康师和科技部老师，也需要验证均分
						let kjbTotalYj = 0;
						const pxTotalAmount = px.pxjg * px.projectNumber;

						for (let k = 0; k < px.lqXhKjbsyjList.length; k++) {
							const kjb = px.lqXhKjbsyjList[k];

							// 验证科技部老师是否选择
							if (!kjb.kjbls || !kjb.kjblsxm) {
								uni.showToast({
									title: `第${i + 1}个品项的第${k + 1}个科技部老师必须选择`,
									icon: 'none'
								});
								return;
							}

							// 验证科技部老师业绩必须填写
							if (!kjb.kjblsyj || kjb.kjblsyj.trim() === "") {
								uni.showToast({
									title: `第${i + 1}个品项的第${k + 1}个科技部老师业绩必须填写`,
									icon: 'none'
								});
								return;
							}

							// 验证业绩为数字
							const yj = parseFloat(kjb.kjblsyj);
							if (isNaN(yj) || yj < 0) {
								uni.showToast({
									title: `第${i + 1}个品项的第${k + 1}个科技部老师业绩必须为有效数字`,
									icon: 'none'
								});
								return;
							}

							kjbTotalYj += yj;
						}

						// 验证科技部老师业绩总和等于品项金额（全部各自组内均分）
						const expectedKjbAmount = pxTotalAmount;
						// if (Math.abs(kjbTotalYj - expectedKjbAmount) > 0.01) {
						// 	uni.showToast({
						// 		title: `第${i + 1}个品项的科技部老师业绩总和(${kjbTotalYj.toFixed(2)})必须等于品项金额(${pxTotalAmount.toFixed(2)})`,
						// 		icon: 'none'
						// 	});
						// 	return;
						// }
					}
				}
				return true;
			},
			// 重新分配健康师的次数和手工费
			redistributeJksNumbersAndLaborCost(pxIndex) {
				const px = this.pxList[pxIndex];
				console.log('px:', px);
				if (!px.lqXhJksyjList || px.lqXhJksyjList.length === 0) {
					return;
				}

				// 过滤掉陪同健康师（isAccompanied为1的健康师不参与计算）
				const normalJksList = px.lqXhJksyjList.filter(jks => !jks.isAccompanied || jks.isAccompanied === 0);
				
				if (normalJksList.length === 0) {
					return;
				}

				// 如果是科美品项，健康师的次数和手工费都是0
				if (px.qt2 === '科美' && px.beautyType != 'cell' && px.beautyType != 'slim') {
					normalJksList.forEach(jks => {
						jks.kdpxNumber = 0;
						jks.laborCost = 0;
					});
					return;
				}
				if ((px.beautyType == 'cell' || px.beautyType == 'slim') && px.lqXhKjbsyjList.length > 0) {
					normalJksList.forEach(jks => {
						jks.kdpxNumber = 0;
						jks.laborCost = 0;
					});
					return;
				}

				// 计算品项总次数和总手工费
				const totalNumber = px.projectNumber || 0;
				const totalLaborCost = (px.healthCoachLaborCost || 0) * totalNumber;

				// 健康师数量（排除陪同健康师）
				const jksCount = normalJksList.length;

				if (jksCount > 0) {
					// 次数和手工费都小数均分，保留两位小数
					const avgNumber = totalNumber / jksCount;
					const avgLaborCost = totalLaborCost / jksCount;

					normalJksList.forEach((jks, index) => {
						// 次数：小数均分，保留两位小数
						jks.kdpxNumber = parseFloat(avgNumber.toFixed(2));
						// 手工费：小数均分，保留两位小数
						jks.laborCost = avgLaborCost.toFixed(2);
					});
				}
				this.$forceUpdate()
			},

			// 重新分配科技部老师的次数和手工费
			redistributeKjbNumbersAndLaborCost(pxIndex) {
				this.calculateTotalAmounts();
				const px = this.pxList[pxIndex];
				// 计算品项总次数和总手工费
				const totalNumber = px.projectNumber || 0;
				const totalLaborCost = (px.techBeautyLaborCost || 0) * totalNumber;
				const totalLaborCostjks = (px.healthCoachLaborCost || 0) * totalNumber;

				// 科技部老师数量
				const kjbCount = px.lqXhKjbsyjList.length;
				const jksCount = px.lqXhJksyjList.length;
				if (!px.lqXhKjbsyjList || px.lqXhKjbsyjList.length === 0) {
					const avgNumberjks = totalNumber / jksCount;
					const avgLaborCostjks = totalLaborCostjks / jksCount;
					px.lqXhJksyjList.forEach((jks, index) => {
						jks.kdpxNumber = parseFloat(avgNumberjks.toFixed(2));
						jks.laborCost = avgLaborCostjks.toFixed(2);
					});	
					return;
				}

				if (kjbCount > 0) {
					// 次数和手工费都小数均分，保留两位小数
					const avgNumber = totalNumber / kjbCount;
					const avgLaborCost = totalLaborCost / kjbCount;

					px.lqXhKjbsyjList.forEach((kjb, index) => {
						// 次数：小数均分，保留两位小数
						kjb.hdpxNumber = parseFloat(avgNumber.toFixed(2));
						// 手工费：小数均分，保留两位小数
						kjb.laborCost = avgLaborCost.toFixed(2);
					});
					px.lqXhJksyjList.forEach(jks => {
						jks.kdpxNumber = 0;
						jks.laborCost = 0;
					});
				}
				this.$forceUpdate()
			},

			// 医美品项自动选择T区健康师
			handleYimeiJksAutoSelection(pxIndex) {
				const px = this.pxList[pxIndex];

				if (px.qt2 !== '医美') {
					return;
				}

				// 检查健康师选项是否已加载
				if (!this.jksOptions || this.jksOptions.length === 0) {
					console.warn('健康师选项尚未加载，无法自动选择T区健康师');
					return;
				}

				// 查找T区健康师
				const tquJks = this.jksOptions.find(jks => jks.fullName && jks.fullName.includes('T区'));
				console.log('tquJks:', tquJks);
				if (tquJks) {
					// 自动添加T区健康师
					const pxTotalAmount = px.pxjg * px.projectNumber;
					// const pxTotalLaborCost = (px.sgf || 0) * px.projectNumber;

					const jksItem = {
						"jks": tquJks.id,
						"jksxm": tquJks.fullName,
						"jkszh": tquJks.id,
						"jksyj": pxTotalAmount.toFixed(2), // 全部业绩
						"jsjId": "",
						// "laborCost": pxTotalLaborCost.toFixed(2), // 全部手工费
						// "kdpxNumber": px.projectNumber, // 全部次数
						"laborCost": 0, // 全部手工费
						"kdpxNumber":0, // 全部次数
						"kdpxid": px.BillingItemId || px.px,
						"isAccompanied": 0, // 是否陪同，默认0
						"accompaniedProjectNumber": 0 // 陪同次数，默认0
					};

					// 使用Vue.set确保响应式更新
					this.$set(this.pxList[pxIndex], 'lqXhJksyjList', [jksItem]);

					// 强制更新视图
					this.$forceUpdate();

					// 获取金三角信息
					this.getJsjInfoByUserId(tquJks.id, (jsjId, jsjName) => {
						jksItem.jsjId = jsjId;
					});
				} else {
					console.warn('未找到T区健康师，请确保健康师列表中包含名称带有"T区"的健康师');
				}
			},

			// 医美品项健康师业绩自动分配
			handleYimeiJksDistribution(pxIndex) {
				const px = this.pxList[pxIndex];
				if (px.qt2 !== '医美' || !px.lqXhJksyjList || px.lqXhJksyjList.length === 0) {
					return;
				}

				const pxTotalAmount = px.pxjg * px.projectNumber;
				const pxTotalLaborCost = (px.sgf || 0) * px.projectNumber;

				// 过滤掉陪同健康师（isAccompanied为1的健康师不参与计算）
				const normalJksList = px.lqXhJksyjList.filter(jks => !jks.isAccompanied || jks.isAccompanied === 0);
				
				if (normalJksList.length === 0) {
					return;
				}

				// 分离T区健康师和其他健康师（排除陪同健康师）
				let tquJks = null;
				let otherJksList = [];

				for (let i = 0; i < normalJksList.length; i++) {
					const jks = normalJksList[i];
					if (jks.jksxm && jks.jksxm.includes('T区')) {
						tquJks = jks;
					} else {
						otherJksList.push(jks);
					}
				}

				if (tquJks) {
					// 有T区健康师的情况
					// T区健康师获得全部业绩、次数和手工费
					tquJks.jksyj = pxTotalAmount.toFixed(2);
					tquJks.kdpxNumber = px.projectNumber;
					tquJks.laborCost = pxTotalLaborCost.toFixed(2);

					// 其他健康师业绩、次数和手工费都为0
					if (otherJksList.length > 0) {
						for (let i = 0; i < otherJksList.length; i++) {
							const otherJks = otherJksList[i];
							otherJks.jksyj = 0;
							otherJks.kdpxNumber = 0;
							otherJks.laborCost = 0;
						}
					}
				} else {
					// 没有T区健康师的情况，按普通品项重新分配
					this.redistributeJksNumbersAndLaborCost(pxIndex);
				}
			},

			// 根据用户ID获取金三角信息
			getJsjInfoByUserId(userId, callback) {
				let formattedDate = this.formData.hksj
				console.log('formattedDate:', formattedDate);
				memberApi.getJsjInfoByUserMonth(userId, formattedDate).then((res) => {
					if (res.code === 200 && res.data) {
						const jsjId = res.data.jsjId;
						const jsjName = res.data.jsjName;
						if (callback) {
							callback(jsjId, jsjName);
						}
					} else {
						if (callback) {
							callback('');
						}
					}
				}).catch((err) => {
					console.error('获取金三角信息出错:', err);
					if (callback) {
						callback('');
					}
				});
			},

			// 更新医美品项T区健康师业绩分配
			updateYimeiJksDistribution(pxIndex) {
				const px = this.pxList[pxIndex];
				if (px.qt2 !== '医美' || !px.lqXhJksyjList || px.lqXhJksyjList.length === 0) {
					return;
				}

				const pxTotalAmount = px.pxjg * px.projectNumber;
				// const pxTotalLaborCost = (px.sgf || 0) * px.projectNumber;

				// 过滤掉陪同健康师（isAccompanied为1的健康师不参与计算）
				const normalJksList = px.lqXhJksyjList.filter(jks => !jks.isAccompanied || jks.isAccompanied === 0);
				
				// 查找T区健康师（排除陪同健康师）
				const tquJks = normalJksList.find(jks => jks.jksxm && jks.jksxm.includes('T区'));

				if (tquJks) {
					// 更新T区健康师的业绩、次数和手工费
					tquJks.jksyj = pxTotalAmount.toFixed(2);
					// tquJks.kdpxNumber = px.projectNumber;
					// tquJks.laborCost = pxTotalLaborCost.toFixed(2);
					tquJks.kdpxNumber = 0;
					tquJks.laborCost = 0;
				} else {
					// 如果没有T区健康师，重新分配所有健康师的次数和手工费
					this.redistributeJksNumbersAndLaborCost(pxIndex);
				}
			},

			// 业绩均分：当同时有健康师和科技部老师时，自动均分业绩
			distributePerformance(pxIndex) {
				const px = this.pxList[pxIndex];
				if (!px || !px.px || !px.pxmc) {
					return;
				}

				// 医美品项不处理均分
				if (px.qt2 === '医美') {
					return;
				}

				// 过滤掉陪同健康师（isAccompanied为1的健康师不参与计算）
				const normalJksList = px.lqXhJksyjList ? px.lqXhJksyjList.filter(jks => !jks.isAccompanied || jks.isAccompanied === 0) : [];
				const hasJks = normalJksList.length > 0;
				const hasKjb = px.lqXhKjbsyjList && px.lqXhKjbsyjList.length > 0;
				const pxTotalAmount = px.pxjg * px.projectNumber;

				// 如果同时有健康师和科技部老师，全部各自组内均分
				// 健康师组：总业绩全部在健康师之间均分
				// 科技老师组：总业绩全部在科技老师之间均分
				if (hasJks && hasKjb) {
					// 健康师组：总业绩全部，在健康师之间均分（排除陪同健康师）
					const jksCount = normalJksList.length;
					const avgJksAmount = pxTotalAmount / jksCount;
					normalJksList.forEach((jks, index) => {
						// 转为字符串格式，避免验证时的类型问题
						jks.jksyj = avgJksAmount.toFixed(2);
					});

					// 科技老师组：总业绩全部，在科技老师之间均分
					const kjbCount = px.lqXhKjbsyjList.length;
					const avgKjbAmount = pxTotalAmount / kjbCount;
					px.lqXhKjbsyjList.forEach((kjb, index) => {
						// 转为字符串格式，避免验证时的类型问题
						kjb.kjblsyj = avgKjbAmount.toFixed(2);
					});
				} else if (hasJks && !hasKjb) {
					// 只有健康师，健康师组获得全部业绩，在健康师之间均分（排除陪同健康师）
					const jksCount = normalJksList.length;
					const avgJksAmount = pxTotalAmount / jksCount;
					normalJksList.forEach((jks, index) => {
						jks.jksyj = avgJksAmount.toFixed(2);
					});
				} else if (!hasJks && hasKjb) {
					// 只有科技部老师，科技老师组获得全部业绩，在科技老师之间均分
					const kjbCount = px.lqXhKjbsyjList.length;
					const avgKjbAmount = pxTotalAmount / kjbCount;
					px.lqXhKjbsyjList.forEach((kjb, index) => {
						kjb.kjblsyj = avgKjbAmount.toFixed(2);
					});
				}

				this.$forceUpdate();
			},
			// 清空表单
			clearForm() {
				this.formData = {
					hy: '',
					hyzh: '',
					hymc: '',
					gklx: '',
					hksj: this.utils.gettime().substring(0, 10),
					xfje: '',
					sgfy: '',
					isOvertime: false,
					overtimeCoefficient: 0
				};

				this.selectedValues = {
					hy: null
				};

				this.pxList = [];
				this.memberSignature = '';
				if (this.$refs.signaturePad) {
					this.$refs.signaturePad.clearSignature();
				}
				this.addPxRow();
			}
		}
	}
</script>

<style lang="scss" scoped>
	.member-consume-container {
		min-height: 100vh;
		background: linear-gradient(135deg, #e8f5e9 0%, #b2dfdb 100%);
		padding: 20rpx;
	}

	.header {
		background: linear-gradient(120deg, #43e97b 0%, #38f9d7 100%);
		border-radius: 36rpx;
		padding: 48rpx;
		text-align: center;
		margin-bottom: 48rpx;
		box-shadow: 0 8rpx 48rpx 0 rgba(76, 175, 80, 0.10);
	}

	.header-title {
		color: #fff;
		font-size: 36rpx;
		font-weight: bold;
		letter-spacing: 4rpx;
	}

	.form-card {
		background: #fff;
		border-radius: 36rpx;
		box-shadow: 0 8rpx 48rpx 0 rgba(76, 175, 80, 0.10);
		border: 3rpx solid #c8e6c9;
		overflow: hidden;
	}

	.form-content {
		padding: 48rpx;
	}

	.form-group {
		margin-bottom: 40rpx;
	}

	.form-group:last-child {
		margin-bottom: 0;
	}

	.form-label {
		display: block;
		margin-bottom: 16rpx;
		font-weight: bold;
		color: #388e3c;
		letter-spacing: 2rpx;
		font-size: 28rpx;
	}

	.custom-select {
		position: relative;
		background: #f9fff9;
		border: 3rpx solid #c8e6c9;
		border-radius: 20rpx;
		padding: 28rpx 24rpx;
		display: flex;
		align-items: center;
		justify-content: space-between;
		cursor: pointer;
		z-index: 10;
		min-height: 80rpx;
		height: 80rpx;
		box-sizing: border-box;
	}

	.select-text {
		font-size: 28rpx;
		color: #2e7d32;
		flex: 1;
	}

	.select-arrow {
		position: absolute;
		right: 24rpx;
		top: 50%;
		transform: translateY(-50%);
		color: #6a9c6a;
		font-size: 24rpx;
		pointer-events: none;
	}

	.input-wrapper {
		position: relative;
	}

	input {
		width: 100%;
		padding: 0 24rpx;
		border: 3rpx solid #c8e6c9;
		border-radius: 20rpx;
		font-size: 28rpx;
		background: #f9fff9;
		color: #2e7d32;
		box-sizing: border-box;
		min-height: 80rpx;
		height: 80rpx;
		// box-sizing: border-box;
	}

	input:focus {
		outline: none;
		border-color: #43a047;
		box-shadow: 0 0 0 6rpx rgba(76, 175, 80, 0.1);
		background: #fff;
	}

	input:disabled {
		background: #f5f5f5;
		color: #666;
		cursor: not-allowed;
	}

	/* 加班相关样式 */
	.checkbox-wrapper {
		display: flex;
		align-items: center;
		margin-bottom: 16rpx;
	}

	.checkbox-label {
		margin-left: 12rpx;
		font-size: 28rpx;
		color: #2e7d32;
	}

	.overtime-select-wrapper {
		margin-top: 16rpx;
	}

	/* 品项相关样式 */
	.px-container {
		margin-bottom: 32rpx;
	}

	.px-row {
		display: flex;
		gap: 24rpx;
		margin-bottom: 24rpx;
		align-items: center;
		flex-wrap: wrap;
		padding: 32rpx;
		border: 2rpx solid #e0e0e0;
		border-radius: 20rpx;
		background: #fafafa;
	}

	.px-select {
		flex: 2;
		padding: 24rpx;
		border: 3rpx solid #c8e6c9;
		border-radius: 20rpx;
		font-size: 28rpx;
		background: #f9fff9;
		color: #2e7d32;
		cursor: pointer;
		position: relative;
		min-width: 400rpx;
		text-align: center;
	}

	.px-select:focus {
		outline: none;
		border-color: #43a047;
		box-shadow: 0 0 0 6rpx rgba(76, 175, 80, 0.1);
		background: #fff;
	}

	.px-info {
		flex: 2;
		padding: 24rpx;
		border: 3rpx solid #e0e0e0;
		border-radius: 20rpx;
		font-size: 24rpx;
		background: #f8f9fa;
		color: #495057;
		min-width: 400rpx;
	}

	.px-info-title {
		font-weight: bold;
		color: #2e7d32;
		margin-bottom: 12rpx;
		font-size: 28rpx;
	}

	.px-info-details {
		display: grid;
		grid-template-columns: 1fr 1fr;
		gap: 8rpx;
		font-size: 24rpx;
	}

	.px-info-item {
		display: flex;
		align-items: center;
	}

	.px-info-label {
		color: #6c757d;
		font-weight: 500;
		margin-right: 20rpx;
	}

	.px-info-value {
		color: #495057;
		font-weight: 600;
	}

	.px-number {
		flex: 1;
		// padding: 24rpx;
		border: 3rpx solid #c8e6c9;
		border-radius: 20rpx;
		font-size: 28rpx;
		background: #f9fff9;
		color: #2e7d32;
		min-width: 160rpx;
	}

	.px-delete {
		padding: 24rpx 32rpx;
		// border: 3rpx solid #ddd;
		border-radius: 20rpx;
		background: #f5f5f5;
		color: #666;
		cursor: pointer;
		font-size: 24rpx;
		transition: all 0.2s ease;
	}

	.px-delete:hover {
		background: #e8e8e8;
		border-color: #ccc;
	}

	.btn-add-px {
		width: 100%;
		padding: 0 40rpx;
		border: 3rpx solid #43a047;
		border-radius: 20rpx;
		background: #e8f5e9;
		color: #2e7d32;
		font-size: 28rpx;
		font-weight: bold;
	}

	/* 品项第三行样式（健康师和科技部老师选择） */
	.px-row-third {
		display: block;
		margin-top: 16rpx;
		width: 100%;
	}

	.px-staff-section {
		width: 100%;
		margin-bottom: 24rpx;
	}

	.px-staff-section:last-child {
		margin-bottom: 0;
	}

	.px-jks-select,
	.px-kjb-select {
		padding: 16rpx 24rpx;
		border: 3rpx solid #c8e6c9;
		border-radius: 16rpx;
		background: #f9fff9;
		color: #2e7d32;
		cursor: pointer;
		font-size: 24rpx;
		text-align: center;
		transition: all 0.2s ease;
	}

	.px-jks-select:hover,
	.px-kjb-select:hover {
		background: #e8f5e9;
		border-color: #43a047;
	}

	.px-jks-list,
	.px-kjb-list {
		margin-top: 16rpx;
		border: 2rpx solid #e0e0e0;
		border-radius: 12rpx;
		background: #fff;
	}

	.px-staff-item {
		padding: 16rpx;
		border-bottom: 2rpx solid #f0f0f0;
		font-size: 24rpx;
	}

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

	.px-staff-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 12rpx;
	}

	.px-staff-name {
		flex: 1;
		color: #2e7d32;
		font-weight: bold;
	}

	.px-staff-remove {
		background: #f44336;
		color: #fff;
		border: none;
		border-radius: 8rpx;
		padding: 4rpx 12rpx;
		font-size: 20rpx;
		cursor: pointer;
	}

	.px-staff-remove:hover {
		background: #d32f2f;
	}

	.px-staff-fields {
		display: flex;
		flex-direction: column;
		gap: 16rpx;
	}

	.px-staff-row {
		display: flex;
		gap: 16rpx;
		align-items: center;
	}

	.px-staff-field {
		flex: 1;
		min-width: 200rpx;
	}

	.px-staff-field input {
		width: 100%;
		// padding: 12rpx 16rpx;
		border: 2rpx solid #ddd;
		border-radius: 8rpx;
		font-size: 24rpx;
		background: #f9f9f9;
	}

	.px-staff-field input:focus {
		outline: none;
		border-color: #43a047;
		background: #fff;
	}

	.px-staff-field-label {
		display: block;
		font-size: 20rpx;
		color: #666;
		margin-bottom: 8rpx;
		font-weight: 500;
	}

	.btn-group {
		display: flex;
		gap: 24rpx;
		margin-top: 48rpx;
	}

	.btn {
		flex: 1;
		padding: 10rpx 40rpx;
		border: none;
		border-radius: 20rpx;
		font-size: 28rpx;
		font-weight: bold;
		cursor: pointer;
		transition: all 0.2s ease;
		letter-spacing: 2rpx;
	}

	.btn-primary {
		background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
		color: #fff;
		box-shadow: 0 4rpx 16rpx rgba(67, 233, 123, 0.3);
	}

	.btn-primary:hover {
		box-shadow: 0 8rpx 32rpx rgba(67, 233, 123, 0.4);
		transform: translateY(-2rpx);
	}

	/* 签字相关样式 */
	.signature-preview {
		margin-top: 24rpx;
		padding: 24rpx;
		background: #f9fff9;
		border: 2rpx solid #c8e6c9;
		border-radius: 16rpx;
	}

	.preview-label {
		display: block;
		font-size: 26rpx;
		color: #2e7d32;
		font-weight: bold;
		margin-bottom: 16rpx;
	}

	.signature-image {
		width: 100%;
		max-width: 300rpx;
		height: 120rpx;
		border: 2rpx solid #e0e0e0;
		border-radius: 12rpx;
		background: #fff;
		margin-bottom: 16rpx;
	}

	.btn-clear-signature {
		padding: 12rpx 24rpx;
		background: #f5f5f5;
		color: #666;
		border: 2rpx solid #ddd;
		border-radius: 12rpx;
		font-size: 24rpx;
		font-weight: 500;
		cursor: pointer;
		transition: all 0.2s ease;
	}

	.btn-clear-signature:hover {
		background: #e0e0e0;
	}

	/* 全屏签字弹窗样式 */
	.signature-modal-overlay {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background: rgba(0, 0, 0, 0.7);
		z-index: 9999;
		display: flex;
		align-items: center;
		justify-content: center;
		box-sizing: border-box;
	}

	.signature-modal {
		width: 100%;
		background: #fff;
		overflow: hidden;
		height: 100%;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
	}

	.signature-modal-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 30rpx 40rpx;
		background: #f8f9fa;
		border-bottom: 2rpx solid #e9ecef;
	}

	.signature-modal-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #2e7d32;
	}

	.btn-close-modal {
		width: 60rpx;
		height: 60rpx;
		background: #f5f5f5;
		border: none;
		border-radius: 50%;
		font-size: 36rpx;
		color: #666;
		display: flex;
		align-items: center;
		justify-content: center;
		cursor: pointer;
		transition: all 0.2s ease;
		margin: 0;
	}

	.btn-close-modal:hover {
		background: #e0e0e0;
		color: #333;
	}

	.signature-modal-content {
		background: #fff;
		flex: 1;
		width: 100%;
	}

	/* 全屏模式下SignaturePad组件样式调整 */
	.signature-modal-content .signature-container {
		height: 100%;
		border: none;
		border-radius: 0;
		box-shadow: none;
	}

	.signature-modal-content .signature-header {
		padding: 20rpx 30rpx;
		background: #f8f9fa;
		border-bottom: 2rpx solid #e9ecef;
	}

	.signature-modal-content .signature-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #2e7d32;
	}

	.signature-modal-content .btn-clear,
	.signature-modal-content .btn-confirm {
		padding: 16rpx 32rpx;
		font-size: 28rpx;
		font-weight: 500;
		border-radius: 12rpx;
	}

	.signature-modal-content .btn-clear {
		background: #f5f5f5;
		color: #666;
		border: 2rpx solid #ddd;
	}

	.signature-modal-content .btn-clear:hover {
		background: #e0e0e0;
		color: #333;
	}

	.signature-modal-content .btn-confirm {
		background: #2e7d32;
		color: #fff;
		border: none;
	}

	.signature-modal-content .btn-confirm:hover {
		background: #1b5e20;
		transform: translateY(-2rpx);
	}

	.signature-modal-content .signature-pad {
		flex: 1;
		display: flex;
		justify-content: center;
		align-items: center;
		padding: 20rpx;
	}

	.signature-modal-content .signature-tips {
		padding: 20rpx;
		text-align: center;
		background: #f8f9fa;
		border-top: 2rpx solid #e9ecef;
	}

	.signature-modal-content .tips-text {
		font-size: 24rpx;
		color: #666;
	}

	/* 签字占位符样式 */
	.signature-placeholder {
		display: flex;
		justify-content: center;
		align-items: center;
		min-height: 200rpx;
		border: 2rpx dashed #c8e6c9;
		border-radius: 16rpx;
		background: #f9fff9;
	}

	.btn-signature-placeholder {
		background: #2e7d32;
		color: #fff;
		border: none;
		border-radius: 16rpx;
		font-size: 28rpx;
		font-weight: 500;
		cursor: pointer;
		transition: all 0.2s ease;
		box-shadow: 0 4rpx 16rpx rgba(46, 125, 50, 0.3);
	}

	.btn-signature-placeholder:hover {
		background: #1b5e20;
		transform: translateY(-2rpx);
		box-shadow: 0 8rpx 32rpx rgba(46, 125, 50, 0.4);
	}

	.signature-placeholder-text {
		color: #fff;
	}

	/* 签字操作按钮样式 */
	.signature-actions {
		display: flex;
		gap: 16rpx;
		margin-top: 16rpx;
	}

	.btn-re-signature {
		flex: 1;
		padding: 12rpx 24rpx;
		background: #2e7d32;
		color: #fff;
		border: none;
		border-radius: 12rpx;
		font-size: 24rpx;
		font-weight: 500;
		cursor: pointer;
		transition: all 0.2s ease;
	}

	.btn-re-signature:hover {
		background: #1b5e20;
	}

	@media (max-width: 750rpx) {
		// .form-content {
		// 	padding: 40rpx;
		// }

		// .px-row {
		// 	flex-direction: column;
		// }

		// .px-select,
		// .px-info,
		// .px-number {
		// 	min-width: 100%;
		// }

		// .signature-preview {
		// 	padding: 20rpx;
		// }

		// .preview-label {
		// 	font-size: 24rpx;
		// }

		// .signature-image {
		// 	max-width: 250rpx;
		// 	height: 100rpx;
		// }

		// .btn-clear-signature {
		// 	padding: 10rpx 20rpx;
		// 	font-size: 22rpx;
		// }
	}
</style>