﻿<template>
	<el-dialog :title="!dataForm.id ? '新建' :  isDetail ? '详情':'编辑'" :close-on-click-modal="false" :visible.sync="visible" class="NCC-dialog NCC-dialog_center" lock-scroll width="90%">
		<el-row :gutter="15" class="" >
				<el-form ref="elForm" :model="dataForm" size="small" label-width="100px" label-position="right" :disabled="!!isDetail" :rules="rules">
					<el-col :span="8" v-if="false" >
						<el-form-item label="退卡编号" prop="id">
							<el-input v-model="dataForm.id" placeholder="请输入" clearable :style='{"width":"100%"}' >
							</el-input>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="门店" prop="md" required>
							<el-select v-model="dataForm.md" placeholder="请选择" clearable :style='{"width":"100%"}' filterable @change="handleMdChange">
								<el-option v-for="(item, index) in mdOptions" :key="index" :label="item.fullName" :value="item.id" ></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="8" v-if="false">
						<el-form-item label="门店编号" prop="mdbh">
							<el-input v-model="dataForm.mdbh" placeholder="自动填充" clearable readonly :style='{"width":"100%"}' >
							</el-input>
						</el-form-item>
					</el-col>
					<el-col :span="8" v-if="false">
						<el-form-item label="门店名称" prop="mdmc">
							<el-input v-model="dataForm.mdmc" placeholder="自动填充" clearable readonly :style='{"width":"100%"}' >
							</el-input>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="会员" prop="hy" required>
							<el-select v-model="dataForm.hy" placeholder="请选择" clearable :style='{"width":"100%"}' filterable @change="handleHyChange">
								<el-option v-for="(item, index) in hyOptions" :key="index" :label="item.fullName" :value="item.id" ></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="8" v-if="false">
						<el-form-item label="会员姓名" prop="hymc">
							<el-input v-model="dataForm.hymc" placeholder="自动填充" clearable readonly :style='{"width":"100%"}' >
							</el-input>
						</el-form-item>
					</el-col>
					<el-col :span="8" v-if="false">
						<el-form-item label="会员账号" prop="hyzh">
							<el-input v-model="dataForm.hyzh" placeholder="自动填充" clearable readonly :style='{"width":"100%"}' >
							</el-input>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="退款金额" prop="tkje">
							<el-input v-model="dataForm.tkje" placeholder="自动计算" clearable readonly :style='{"width":"100%"}'>
								<template slot="append">元</template>
							</el-input>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="手工费用" prop="sgfy">
							<el-input v-model="dataForm.sgfy" placeholder="自动计算" clearable readonly :style='{"width":"100%"}'>
								<template slot="append">元</template>
							</el-input>
						</el-form-item>
					</el-col>
					<el-col :span="16"></el-col>
					<el-col :span="24" v-if="false" >
						<el-form-item label="退卡品项" prop="tkpx">
							<el-input v-model="dataForm.tkpx" placeholder="请输入" clearable :style='{"width":"100%"}' >
							</el-input>
						</el-form-item>
					</el-col>
					<el-col :span="24">
					<el-form-item label-width="0">
						<div class="table-header">
							<span class="table-title">品项明细</span>
							<el-button v-if="!dataForm.id" type="warning" size="mini" icon="el-icon-plus" @click="addHandleLqXhPxmxEntityList()">新增品项</el-button>
						</div>
						
						<!-- 品项列表 -->
						<div class="px-list-container">
							<div v-for="(px, pxIndex) in dataForm.lqHytkMxList" :key="pxIndex" class="px-item">
								<!-- 品项基本信息 -->
								<div class="px-basic-info">
									<div class="px-item-header">
										<span class="px-item-title">品项明细</span>
										<el-button v-if="!dataForm.id"size="mini" type="danger" icon="el-icon-delete" @click="handleDelLqXhPxmxEntityList(pxIndex)">删除</el-button>
									</div>
									
									<!-- 品项选择 -->
									<div class="px-select-row">
										<el-select v-model="px.px" placeholder="请选择品项" clearable filterable @change="handlePxChange(pxIndex, px)" style="width: 200px;">
											<el-option v-for="(item, index) in pxOptions" :key="index" :label="item.fullName" :value="item.id" :disabled="item.disabled"></el-option>
										</el-select>
									</div>
									
									<!-- 品项详细信息 -->
									<div class="px-detail-info" v-if="px.px">
										<div class="px-detail-row">
											<div class="px-detail-item">
												<span class="px-detail-label">品项名称：</span>
												<span class="px-detail-value">{{ px.pxmc || '未选择' }}</span>
											</div>
											<div class="px-detail-item">
												<span class="px-detail-label">单价：</span>
												<span class="px-detail-value">¥{{ px.pxjg || 0 }}</span>
											</div>
											<div class="px-detail-item">
												<span class="px-detail-label">已消费：</span>
												<span class="px-detail-value">{{ px.yxf || 0 }}</span>
											</div>
											<div class="px-detail-item">
												<span class="px-detail-label">总购买：</span>
												<span class="px-detail-value">{{ px.zgm || 1 }}</span>
											</div>
											<div class="px-detail-item">
												<span class="px-detail-label">剩余：</span>
												<span class="px-detail-value">{{ (px.zgm || 1) - (px.yxf || 0) }}</span>
											</div>
											<div class="px-detail-item">
												<span class="px-detail-label">类型：</span>
												<span class="px-detail-value">{{ px.ly || '购买' }}</span>
											</div>
									
										</div>
										
										<!-- 消费数量输入 -->
										<div class="px-consumption-row">
											<el-input-number v-model="px.projectNumber" :min="1" :max="getRemainingCount(px)" placeholder="消费数量" size="mini" style="width: 120px;" @change="onProjectNumberChange"></el-input-number>
										</div>
									</div>
								</div>

								<!-- 健康师业绩区域 -->
								<div class="px-staff-section">
									<div class="px-staff-header">
										<span class="px-staff-title">健康师业绩</span>
										<el-button v-if="!dataForm.id" size="mini" type="success" icon="el-icon-plus" @click="addPxJks(pxIndex)">添加健康师</el-button>
									</div>
									<div class="px-staff-list">
										<div v-for="(jks, jksIndex) in px.lqHytkJksyjList" :key="jksIndex" class="px-staff-row">
											<div class="px-staff-item">
												<div class="px-staff-fields">
													<div class="px-staff-field">
														<label>健康师</label>
														<el-select v-model="jks.jks" placeholder="选择健康师" clearable filterable size="mini" style="width: 200px;" @change="handleJksChange(pxIndex, jksIndex, jks)">
															<el-option v-for="(item, index) in jksOptions" :key="index" :label="item.fullName" :value="item.id"></el-option>
														</el-select>
													</div>
													<div class="px-staff-field">
														<label>业绩</label>
														<el-input v-model="jks.jksyj" placeholder="请输入业绩" size="mini" style="width: 120px;" @input="formatPxStaffNumber(pxIndex, jksIndex, 'jksyj', 'lqHytkJksyjList')">
															<template slot="append">元</template>
														</el-input>
													</div>
													<div class="px-staff-field">
														<label>手工费</label>
														<el-input v-model="jks.laborCost" placeholder="手工费" size="mini" style="width: 120px;" @input="formatPxStaffNumber(pxIndex, jksIndex, 'laborCost', 'lqHytkJksyjList')">
															<template slot="append">元</template>
														</el-input>
													</div>
													<div class="px-staff-field">
														<label>次数</label>
														<el-input-number v-model="jks.kdpxNumber" :min="1" :max="999" placeholder="次数" size="mini" style="width: 120px;"></el-input-number>
													</div>
													<div class="px-staff-field" v-if="!dataForm.id">
														<el-button size="mini" type="danger" icon="el-icon-delete" @click="removePxJks(pxIndex, jksIndex)">删除</el-button>
													</div>
												</div>
											</div>
										</div>
									</div>
								</div>

								<!-- 科技部老师业绩区域 - 仅当品项类型为科美时显示 -->
								<div class="px-staff-section" v-if="px.qt2 === '科美'" :key="'kjb-' + pxIndex + '-' + px.qt2">
									<div class="px-staff-header">
										<span class="px-staff-title">科技部老师业绩</span>
										<el-button v-if="!dataForm.id" size="mini" type="success" icon="el-icon-plus" @click="addPxKjb(pxIndex)">添加科技部老师</el-button>
									</div>
									<div class="px-staff-list">
										<div v-for="(kjb, kjbIndex) in px.lqHytkKjbsyjList" :key="kjbIndex" class="px-staff-row">
											<div class="px-staff-item">
												<div class="px-staff-fields">
													<div class="px-staff-field">
														<label>科技部老师</label>
														<el-select v-model="kjb.kjbls" placeholder="选择科技部老师" clearable filterable size="mini" style="width: 200px;" @change="handleKjbChange(pxIndex, kjbIndex, kjb)">
															<el-option v-for="(item, index) in kjbOptions" :key="index" :label="item.fullName" :value="item.id"></el-option>
														</el-select>
													</div>
													<div class="px-staff-field">
														<label>业绩</label>
														<el-input v-model="kjb.kjblsyj" placeholder="请输入业绩" size="mini" style="width: 120px;" @input="formatPxStaffNumber(pxIndex, kjbIndex, 'kjblsyj', 'lqHytkKjbsyjList')">
															<template slot="append">元</template>
														</el-input>
													</div>
													<div class="px-staff-field">
														<label>手工费</label>
														<el-input v-model="kjb.laborCost" placeholder="手工费" size="mini" style="width: 120px;" @input="formatPxStaffNumber(pxIndex, kjbIndex, 'laborCost', 'lqHytkKjbsyjList')">
															<template slot="append">元</template>
														</el-input>
													</div>
													<div class="px-staff-field">
														<label>次数</label>
														<el-input-number v-model="kjb.hdpxNumber" :min="1" :max="999" placeholder="次数" size="mini" style="width: 120px;"></el-input-number>
													</div>
													<div class="px-staff-field" v-if="!dataForm.id">
														<el-button size="mini" type="danger" icon="el-icon-delete" @click="removePxKjb(pxIndex, kjbIndex)">删除</el-button>
													</div>
												</div>
											</div>
										</div>
									</div>
								</div>
								
								<!-- 非科美品项提示 -->
								<div class="px-staff-section" v-if="px.qt2 && px.qt2 !== '科美'">
									<div class="px-staff-header">
										<span class="px-staff-title">科技部老师业绩</span>
									</div>
									<div class="px-staff-tip">
										<i class="el-icon-info"></i>
										<span>当前品项类型为"{{ px.qt2 }}"，无需配置科技部老师业绩</span>
									</div>
								</div>
							</div>
						</div>
					</el-form-item>
				</el-col>
				<el-col :span="24">
						<el-form-item label="备注" prop="bz">
							<el-input v-model="dataForm.bz" placeholder="请输入" show-word-limit :style='{"width":"100%"}' type='textarea' :autosize='{"minRows":4,"maxRows":4}' >
							</el-input>
						</el-form-item>
					</el-col>
					<el-col :span="24">
						<el-form-item label="上传文件" prop="fileUrl">
							<NCC-UploadImg v-model="dataForm.fileUrl" :fileSize="30" sizeUnit="MB" :limit="9" >
							</NCC-UploadImg>
						</el-form-item>
					</el-col>
				</el-form>
		</el-row>
		<span slot="footer" class="dialog-footer">
			<el-button @click="visible = false">取 消</el-button>
			<el-button type="primary" @click="dataFormSubmit()" v-if="!isDetail">确 定</el-button>
		</span>
	</el-dialog>
</template>
<script>
	import request from '@/utils/request'
	import { getDictionaryDataSelector } from '@/api/systemData/dictionary'
	import { previewDataInterface } from '@/api/systemData/dataInterface'
	import { getInfo } from '@/api/user'
	export default {
		components: {},
		props: [],
		data() {
			return {
				loading: false,
				visible: false,
				isDetail: false,
				dataForm: {
					id:'',
					id:undefined,
					md:undefined,
					mdbh:undefined,
					mdmc:undefined,
					hy:undefined,
					hymc:undefined,
					hyzh:undefined,
					tkje:undefined,
					sgfy:undefined,
					bz:undefined,
					tkpx:undefined,
					tksj:undefined,
					tkr:undefined,
					fileUrl:undefined,
					lqHytkJksyjList:[],
					lqHytkKjbsyjList:[],
					lqHytkMxList:[],
				},
				rules: {
					md: [
						{ required: true, message: '请选择门店', trigger: 'change' }
					],
					hy: [
						{ required: true, message: '请选择会员', trigger: 'change' }
					]
				},
				mdOptions : [],
				hyOptions : [],
				pxOptions : [],
				jksOptions:[],
				kjbOptions:[],
			}
		},
		computed: {},
        watch: {},
        created() {
			// 门店数据在loadStoreDataAndSetDefault中加载，避免重复
			this.gethyOptions();
			this.getpxOptions();
		},
		mounted() {
        },
		methods: {
			// 门店选择变化处理
			handleMdChange(val) {
				const selectedMd = this.mdOptions.find(item => item.id === val);
				if (selectedMd) {
					this.dataForm.mdbh = selectedMd.mdbh || selectedMd.id;
					this.dataForm.mdmc = selectedMd.fullName;
					console.log('选择门店:', selectedMd);
				} else {
					this.dataForm.mdbh = '';
					this.dataForm.mdmc = '';
				}
			},
			// 会员选择变化处理
			handleHyChange(val) {
				const selectedHy = this.hyOptions.find(item => item.id === val);
				if (selectedHy) {
					this.dataForm.hyzh = selectedHy.hyzh || selectedHy.id;
					this.dataForm.hymc = selectedHy.fullName;
					console.log('选择会员:', selectedHy);
					
					// 选择会员后，获取该会员的剩余品项
					this.getpxOptions();
				} else {
					this.dataForm.hyzh = '';
					this.dataForm.hymc = '';
					this.pxOptions = []; // 清空品项选项
				}
			},
			// 品项选择变化处理
			handlePxChange(index, row) {
				if (row.px) {
					const selectedPx = this.pxOptions.find(item => item.id === row.px);
					if (selectedPx) {
						request({
							url: `/api/Extend/LqXmzl/${selectedPx.id}`,
							method: 'GET',
						}).then((res) => {
							let qt2 = res.data.qt2 || "";
							let sgf = res.data.sgf || 0;
							row.pxmc = selectedPx.fullName;
							row.pxjg = selectedPx.ItemPrice || 0;
							row.qt2 = qt2 || "";
							row.yxf = selectedPx.ConsumedCount || 0; // 已消费
							row.zgm = selectedPx.TotalPurchased || 1; // 总购买
							row.ly = selectedPx.sourceType || "购买"; // 来源
							row.projectNumber = 1; // 默认消费数量为1
							row.sgf = sgf;
							
							// 如果品项类型不是"科美"，清空科技部老师列表
							if (row.qt2 !== '科美') {
								row.lqHytkKjbsyjList = [];
							}
							
							console.log('选择品项:', selectedPx.fullName, 'qt2:', selectedPx.qt2, '剩余数量:', selectedPx.RemainingCount);
							
							// 重新计算总金额和总手工费
							this.calculateTotalAmount();
							this.calculateTotalLaborCost();
						})
					}
				} else {
					// 清空品项时，重置所有相关字段
					row.pxmc = '';
					row.pxjg = 0;
					row.qt2 = '';
					row.yxf = 0;
					row.zgm = 1;
					row.ly = '购买';
					row.projectNumber = 1;
					row.lqHytkKjbsyjList = []; // 清空科技部老师列表
					
					// 重新计算总金额和总手工费
					this.calculateTotalAmount();
					this.calculateTotalLaborCost();
				}
			},
			getmdOptions(){
				previewDataInterface('730960205902251269').then(res => {
					this.mdOptions = res.data
				});
			},
			gethyOptions(){
				previewDataInterface('730998109110273285').then(res => {
					this.hyOptions = res.data
				});
			},
			// 获取品项选项（从会员剩余品项API获取）
			async getpxOptions() {
				if (!this.dataForm.hy) {
					console.warn("请先选择会员");
					this.pxOptions = [];
					return;
				}

				try {
					const response = await request({
						url: `/api/Extend/lqkhxx/GetMemberRemainingItems?memberId=${this.dataForm.hy}`,
						method: 'GET',
					});

					if (response.code == 200 && response.data && response.data.RemainingItems) {
						this.pxOptions = response.data.RemainingItems.map(item => ({
							fullName: item.ItemName,
							id: item.ItemId,
							value: item.ItemId,
							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
						}));
						console.log('获取会员剩余品项成功:', this.pxOptions);
					} else {
						console.warn("获取会员剩余品项失败，使用默认数据");
						this.pxOptions = [];
					}
				} catch (error) {
					console.error("获取会员剩余品项出错:", error);
					this.pxOptions = [];
				}
			},
			// 获取健康师选项
			getjksOptions() {
				request({
					url: `/api/Extend/user?page=1&pageSize=1000&mdid=${this.dataForm.md}&gw=健康师`,
					method: 'GET',
				}).then((res) => {
					if (res.code == 200 && res.data.list.length > 0) {
						this.jksOptions = res.data.list.map(item => ({
							fullName: item.realName || item.name || item.userName,
							id: item.id,
							value: item.id,
							label: item.realName || item.name || item.userName,
							jks: item.id,
							jksxm: item.realName || item.name || item.userName,
							jkszh: item.mobilePhone || item.account || item.userName
						}));
					} else {
						this.jksOptions = [];
					}
				})
			},
			// 获取科技部老师选项
			async getkjbOptions() {
				await this.getKjbOptionsByOrganizeId();
			},
			// 根据门店ID获取科技部组织ID，再获取科技部老师列表
			async getKjbOptionsByOrganizeId() {
				const userResponse = await request({
					url: `/api/Extend/user?page=1&pageSize=1000&gw=科技老师`,
					method: 'GET',
				});
				
				if (userResponse.code == 200 && userResponse.data && userResponse.data.list.length > 0) {
					this.kjbOptions = userResponse.data.list.map(item => ({
						fullName: item.realName || item.name || item.userName,
						id: item.id,
						value: item.id,
						label: item.realName || item.name || item.userName,
						kjbls: item.id,
						kjblsxm: item.realName || item.name || item.userName,
						kjblszh: item.mobilePhone || item.account || item.userName
					}));
					console.log('科技部老师列表:', this.kjbOptions);
				} else {
					console.warn('获取科技部老师列表失败');
					this.kjbOptions = [];
				}
			},
			// 品项健康师选择
			handleJksChange(pxIndex, jksIndex, row) {
				console.log('品项健康师选择:', row);
				if (row.jks) {
					// 根据选择的健康师ID获取用户信息
					const selectedJks = this.jksOptions.find(item => item.id === row.jks);
					if (selectedJks) {
						// 填充姓名和账号
						row.jksxm = selectedJks.fullName;
						row.jkszh = selectedJks.userName || selectedJks.account || selectedJks.id;
						
						// 获取金三角信息
						this.getJsjInfoByUserId(row.jks, (jsjId, jsjName) => {
							row.jsjName = jsjName;
							row.jsjId = jsjId;
						});
					}
				} else {
					// 清空相关字段
					row.jksxm = '';
					row.jkszh = '';
					row.jsjId = '';
				}
			},
			// 品项科技部老师选择
			handleKjbChange(pxIndex, kjbIndex, row) {
				console.log('品项科技部老师选择:', row);
				if (row.kjbls) {
					// 根据选择的科技部老师ID获取用户信息
					const selectedKjb = this.kjbOptions.find(item => item.id === row.kjbls);
					if (selectedKjb) {
						// 填充姓名和账号
						row.kjblsxm = selectedKjb.fullName;
						row.kjblszh = selectedKjb.userName || selectedKjb.account || selectedKjb.id;
					}
				} else {
					// 清空相关字段
					row.kjblsxm = '';
					row.kjblszh = '';
				}
			},
			// 根据用户ID获取金三角信息
			getJsjInfoByUserId(userId, callback) {
				request({
					url: `/api/Extend/lqycsdjsj/Actions/GetThisMonthJsjInfo?userId=${userId}`,
					method: 'GET',
				}).then((res) => {
					if (res.code === 200 && res.data) {
						// 假设返回的数据结构中有jsj_id字段
						const jsjId = res.data.jsjId;
						const jsjName = res.data.jsjName;

						if (callback) {
							callback(jsjId, jsjName);
						}
						console.log('获取金三角信息成功:', res.data);
					} else {
						console.warn('获取金三角信息失败:', res.msg);
						if (callback) {
							callback('');
						}
					}
				}).catch((err) => {
					console.error('获取金三角信息出错:', err);
					if (callback) {
						callback('');
					}
				});
			},
			// 品项内人员业绩数字格式化
			formatPxStaffNumber(pxIndex, staffIndex, field, listName) {
				const targetList = this.dataForm.lqHytkMxList[pxIndex][listName];
				if (targetList && targetList[staffIndex] && targetList[staffIndex][field] !== undefined) {
					let value = targetList[staffIndex][field].toString().replace(/,/g, '');
					
					if (!/^\d*\.?\d*$/.test(value)) {
						value = value.replace(/[^\d.]/g, '');
					}
					
					targetList[staffIndex][field] = value;
				}
			},
			// 获取品项剩余数量
			getRemainingCount(px) {
				if (px.px) {
					const selectedPx = this.pxOptions.find(item => item.id === px.px);
					if (selectedPx) {
						return selectedPx.RemainingCount || 0;
					}
				}
				return (px.zgm || 1) - (px.yxf || 0);
			},
			// 消费数量变化处理
			onProjectNumberChange() {
				// 重新计算总金额和总手工费
				this.calculateTotalAmount();
				this.calculateTotalLaborCost();
			},
			// 计算总退款金额
			calculateTotalAmount() {
				let totalAmount = 0;
				this.dataForm.lqHytkMxList.forEach(px => {
					if (px.px && px.pxjg && px.projectNumber) {
						totalAmount += parseFloat(px.pxjg) * parseInt(px.projectNumber);
					}
				});
				this.dataForm.tkje = totalAmount.toFixed(2);
			},
			// 计算总手工费
			calculateTotalLaborCost() {
				let totalLaborCost = 0;
				this.dataForm.lqHytkMxList.forEach(px => {
					if (px.sgf && px.projectNumber) {
						totalLaborCost += parseFloat(px.sgf) * parseInt(px.projectNumber);
					}
				});
				this.dataForm.sgfy = totalLaborCost.toFixed(2);
			},
			goBack() {
                this.$emit('refresh')
            },
			init(id, isDetail) {
				this.dataForm.id = id || 0;
                this.visible = true;
                this.isDetail = isDetail || false;
				this.$nextTick(() => {
					this.$refs['elForm'].resetFields();
					if (this.dataForm.id) {
						request({
							url: '/api/Extend/LqHytkHytk/' + this.dataForm.id,
							method: 'get'
						}).then(res =>{
							this.dataForm = res.data;
							this.dataForm.fileUrl = this.dataForm.fileUrl?JSON.parse(this.dataForm.fileUrl):[];
						})
					} else {
						// 新建时自动设置当前用户门店
						this.loadStoreDataAndSetDefault();
						// 加载健康师和科技部老师选项
						this.getjksOptions();
						this.getkjbOptions();
						// 初始化时计算总金额和总手工费
						this.calculateTotalAmount();
						this.calculateTotalLaborCost();
					}
				})
			},
			dataFormSubmit() {
			
				this.$refs['elForm'].validate((valid) => {
                    if (valid) {
						// 验证品项数据
						if (!this.validatePxList()) {
							return;
						}

						// 处理提交格式
						this.processFormData();
						console.log(this.dataForm)
						// return

						this.dataForm.fileUrl = JSON.stringify(this.dataForm.fileUrl);
                        if (!this.dataForm.id) {
                            request({
                                url: `/api/Extend/LqHytkHytk`,
                                method: 'post',
                                data: this.dataForm,
                            }).then((res) => {
                                this.$message({
                                    message: res.msg,
                                    type: 'success',
                                    duration: 1000,
                                    onClose: () => {
                                        this.visible = false,
                                            this.$emit('refresh', true)
                                    }
                                })
                            })
                        } else {
                            request({
                                url: '/api/Extend/LqHytkHytk/' + this.dataForm.id,
                                method: 'PUT',
                                data: this.dataForm
                            }).then((res) => {
                                this.$message({
                                    message: res.msg,
                                    type: 'success',
                                    duration: 1000,
                                    onClose: () => {
                                        this.visible = false
                                        this.$emit('refresh', true)
                                    }
                                })
                            })
                        }
                    }
                })
			},
			// 品项相关方法
			addHandleLqXhPxmxEntityList() {
				let item = {
					id: undefined,
					glkdbh: undefined,
					px: undefined,
					pxmc: undefined,
					pxjg: undefined,
					xfzs: undefined,
					yxf: 0, // 已消费
					zgm: 1, // 总购买
					ly: '购买', // 来源
					projectNumber: 1, // 消费数量
					qt2: undefined, // 品项类型
					lqHytkJksyjList: [], // 健康师业绩列表
					lqHytkKjbsyjList: [], // 科技部老师业绩列表
				}
				this.dataForm.lqHytkMxList.push(item);
				// 重新计算总金额和总手工费
				this.calculateTotalAmount();
				this.calculateTotalLaborCost();
			},
			handleDelLqXhPxmxEntityList(index) {
				this.dataForm.lqHytkMxList.splice(index, 1);
				// 重新计算总金额和总手工费
				this.calculateTotalAmount();
				this.calculateTotalLaborCost();
			},
			validatePxList(){
				const pxList = this.dataForm.lqHytkMxList;
				
				// 1. 验证是否有品项
				if (!pxList || pxList.length === 0) {
					this.$message.error('请至少添加一个品项');
					return false;
				}
				
				// 2. 验证每个品项的信息
				for (let i = 0; i < pxList.length; i++) {
					const px = pxList[i];
					
					// 验证品项基本信息
					if (!px.px || !px.pxmc) {
						this.$message.error(`第${i + 1}个品项信息不完整，请重新选择`);
						return false;
					}
					if (!px.pxjg || parseFloat(px.pxjg) <= 0) {
						this.$message.error(`第${i + 1}个品项的价格必须大于0`);
						return false;
					}
					
					// 验证退卡次数不能超过剩余次数
					if (px.RemainingCount && px.projectNumber > px.RemainingCount) {
						this.$message.error(`第${i + 1}个品项的退卡次数(${px.projectNumber})不能超过剩余次数(${px.RemainingCount})`);
						return false;
					}
					
					// 验证健康师
					if (!px.lqHytkJksyjList || px.lqHytkJksyjList.length === 0) {
						this.$message.error(`第${i + 1}个品项必须至少选择一个健康师`);
						return false;
					}
					
					// 计算健康师业绩总和
					let jksTotalYj = 0;
					let jksTotalLaborCost = 0;
					let jksTotalNumber = 0;
					
					for (let j = 0; j < px.lqHytkJksyjList.length; j++) {
						const jks = px.lqHytkJksyjList[j];
						
						// 验证健康师是否选择
						if (!jks.jks || !jks.jksxm) {
							this.$message.error(`第${i + 1}个品项的第${j + 1}个健康师必须选择`);
							return false;
						}
						
						// 验证健康师业绩必须填写
						if (!jks.jksyj || jks.jksyj.trim() === "") {
							this.$message.error(`第${i + 1}个品项的第${j + 1}个健康师业绩必须填写`);
							return false;
						}
						
						// 验证业绩为数字
						const yj = parseFloat(jks.jksyj);
						if (isNaN(yj) || yj < 0) {
							this.$message.error(`第${i + 1}个品项的第${j + 1}个健康师业绩必须为有效数字`);
							return false;
						}
						
						jksTotalYj += yj;
						jksTotalLaborCost += parseFloat(jks.laborCost) || 0;
						jksTotalNumber += parseInt(jks.kdpxNumber) || 0;
					}
					
					// 验证健康师业绩总和等于品项金额
					const pxTotalAmount = px.pxjg * px.projectNumber;
					if (Math.abs(jksTotalYj - pxTotalAmount) > 0.01) {
						this.$message.error(`第${i + 1}个品项的健康师业绩总和(${jksTotalYj.toFixed(2)})必须等于品项金额(${pxTotalAmount.toFixed(2)})`);
						return false;
					}
					
					// 验证健康师手工费总和等于品项手工费
					const pxTotalLaborCost = (px.sgf || 0) * px.projectNumber;
					if (Math.abs(jksTotalLaborCost - pxTotalLaborCost) > 0.01) {
						this.$message.error(`第${i + 1}个品项的健康师手工费总和(${jksTotalLaborCost.toFixed(2)})必须等于品项手工费(${pxTotalLaborCost.toFixed(2)})`);
						return false;
					}
					
					// 验证健康师次数总和等于品项次数
					if (jksTotalNumber !== px.projectNumber) {
						this.$message.error(`第${i + 1}个品项的健康师次数总和(${jksTotalNumber})必须等于品项次数(${px.projectNumber})`);
						return false;
					}
					
					// 如果是科美品项，验证科技部老师
					if (px.qt2 === '科美') {
						if (!px.lqHytkKjbsyjList || px.lqHytkKjbsyjList.length === 0) {
							this.$message.error(`第${i + 1}个品项是科美品项，必须至少选择一个科技部老师`);
							return false;
						}
						
						// 计算科技部老师业绩总和
						let kjbTotalYj = 0;
						let kjbTotalLaborCost = 0;
						let kjbTotalNumber = 0;
						
						for (let k = 0; k < px.lqHytkKjbsyjList.length; k++) {
							const kjb = px.lqHytkKjbsyjList[k];
							
							// 验证科技部老师是否选择
							if (!kjb.kjbls || !kjb.kjblsxm) {
								this.$message.error(`第${i + 1}个品项的第${k + 1}个科技部老师必须选择`);
								return false;
							}
							
							// 验证科技部老师业绩必须填写
							if (!kjb.kjblsyj || kjb.kjblsyj.trim() === "") {
								this.$message.error(`第${i + 1}个品项的第${k + 1}个科技部老师业绩必须填写`);
								return false;
							}
							
							// 验证业绩为数字
							const yj = parseFloat(kjb.kjblsyj);
							if (isNaN(yj) || yj < 0) {
								this.$message.error(`第${i + 1}个品项的第${k + 1}个科技部老师业绩必须为有效数字`);
								return false;
							}
							
							kjbTotalYj += yj;
							kjbTotalLaborCost += parseFloat(kjb.laborCost) || 0;
							kjbTotalNumber += parseInt(kjb.hdpxNumber) || 0;
						}
						
						// 验证科技部老师业绩总和等于品项金额
						if (Math.abs(kjbTotalYj - pxTotalAmount) > 0.01) {
							this.$message.error(`第${i + 1}个品项的科技部老师业绩总和(${kjbTotalYj.toFixed(2)})必须等于品项金额(${pxTotalAmount.toFixed(2)})`);
							return false;
						}
						
						// 验证科技部老师手工费总和等于品项手工费
						if (Math.abs(kjbTotalLaborCost - pxTotalLaborCost) > 0.01) {
							this.$message.error(`第${i + 1}个品项的科技部老师手工费总和(${kjbTotalLaborCost.toFixed(2)})必须等于品项手工费(${pxTotalLaborCost.toFixed(2)})`);
							return false;
						}
						
						// 验证科技部老师次数总和等于品项次数
						if (kjbTotalNumber !== px.projectNumber) {
							this.$message.error(`第${i + 1}个品项的科技部老师次数总和(${kjbTotalNumber})必须等于品项次数(${px.projectNumber})`);
							return false;
						}
					}
				}
				
				return true;
			},
			// 处理表单数据
			processFormData() {
				// 检查是否有科美品项
				const hasKemei = this.dataForm.lqHytkMxList.some(px => px.qt2 === '科美');
				
				// 设置是否有科技部
				this.dataForm.sfykjb = hasKemei ? "是" : "否";
				
				// 处理品项列表，转换为指定格式
				this.dataForm.lqHytkMxList = this.dataForm.lqHytkMxList.map(px => {
					// 计算退卡金额和总价
					const tkje = parseFloat(px.pxjg) * parseInt(px.projectNumber) || 0;
					const f_TotalPrice = tkje;
					
					// 处理健康师列表
					const lqHytkJksyjList = (px.lqHytkJksyjList || []).map(jks => ({
						jks: jks.jks || '',
						jksxm: jks.jksxm || '',
						jkszh: jks.jkszh || '',
						jksyj: parseFloat(jks.jksyj) || 0,
						f_jsjid: jks.jsjId || '',
						f_tkpxid: px.px || '',
						f_LaborCost: parseFloat(jks.laborCost) || 0,
						f_tkpxNumber: parseInt(px.projectNumber) || 0
					}));
					
					// 处理科技部老师列表
					const lqHytkKjbsyjList = (px.lqHytkKjbsyjList || []).map(kjb => ({
						kjbls: kjb.kjbls || '',
						kjblsxm: kjb.kjblsxm || '',
						kjblszh: kjb.kjblszh || '',
						kjblsyj: parseFloat(kjb.kjblsyj) || 0,
						f_tkpxid: px.px || '',
						f_LaborCost: parseFloat(kjb.laborCost) || 0,
						f_tkpxNumber: parseInt(px.projectNumber) || 0
					}));
					
					return {
						px: px.px || '',
						pxmc: px.pxmc || '',
						pxjg: parseFloat(px.pxjg) || 0,
						tkje: tkje,
						f_ProjectNumber: parseInt(px.projectNumber) || 0,
						f_SourceType: px.qt2 || '',
						f_TotalPrice: f_TotalPrice,
						lqHytkJksyjList: lqHytkJksyjList,
						lqHytkKjbsyjList: lqHytkKjbsyjList
					};
				});
			},
			// 品项健康师相关方法
			addPxJks(pxIndex) {
				if (!this.dataForm.lqHytkMxList[pxIndex].lqHytkJksyjList) {
					this.$set(this.dataForm.lqHytkMxList[pxIndex], 'lqHytkJksyjList', []);
				}
				let item = {
					"jks": "",
					"jksxm": "",
					"jkszh": "",
					"jksyj": "",
					"jsjId": "",
					"laborCost": 1,
					"kdpxNumber": 0
				}
				this.dataForm.lqHytkMxList[pxIndex].lqHytkJksyjList.push(item);
			},
			removePxJks(pxIndex, jksIndex) {
				this.dataForm.lqHytkMxList[pxIndex].lqHytkJksyjList.splice(jksIndex, 1);
			},
			// 品项科技部老师相关方法
			addPxKjb(pxIndex) {
				if (!this.dataForm.lqHytkMxList[pxIndex].lqHytkKjbsyjList) {
					this.$set(this.dataForm.lqHytkMxList[pxIndex], 'lqHytkKjbsyjList', []);
				}
				let item = {
					"kjbls": "",
					"kjblsyj": "",
					"kjblsxm": "",
					"kjblszh": "",
					"laborCost": 0,
					"hdpxNumber": 0
				}
				this.dataForm.lqHytkMxList[pxIndex].lqHytkKjbsyjList.push(item);
			},
			removePxKjb(pxIndex, kjbIndex) {
				this.dataForm.lqHytkMxList[pxIndex].lqHytkKjbsyjList.splice(kjbIndex, 1);
			},
			// 加载门店数据并设置默认门店
			loadStoreDataAndSetDefault() {
				console.log('开始加载门店数据和用户信息...');
				// 先加载门店数据
				this.loadStoreDataPromise().then(() => {
					// 门店数据加载完成后，获取用户信息
					return this.getCurrentUserStorePromise();
				}).then((userData) => {
					if (userData && userData.mdid) {
						const userStoreId = userData.mdid;
						console.log('用户门店ID:', userStoreId);
						console.log('门店选项列表:', this.mdOptions);

						// 检查用户门店ID是否在门店列表中
						const matchingStore = this.mdOptions.find(store => store.id === userStoreId);
						if (matchingStore) {
							this.dataForm.md = userStoreId;
							this.dataForm.mdmc = matchingStore.fullName;
							this.dataForm.mdbh = matchingStore.id;
							console.log('找到匹配的门店，设置默认门店ID:', userStoreId);
							console.log('匹配的门店信息:', matchingStore);
						} else {
							console.warn('用户门店ID在门店列表中未找到匹配项');
							console.log('用户门店ID:', userStoreId);
							console.log('可用门店ID列表:', this.mdOptions.map(s => s.id));
						}
					} else {
						console.warn('用户数据中没有门店ID，无法设置默认值');
					}
					
					// 加载健康师和科技部老师选项
					this.getjksOptions();
					this.getkjbOptions();
				}).catch(err => {
					console.error('加载数据失败:', err);
				});
			},
			// 加载门店数据
			loadStoreDataPromise() {
				// 使用原来的数据接口方式
				return previewDataInterface('730960205902251269').then(res => {
					console.log('门店API原始响应:', res);
					if (res.data && res.data.length > 0) {
						this.mdOptions = res.data;
						console.log('门店数据加载成功:', this.mdOptions);
						return res.data;
					} else {
						console.warn('门店数据为空');
						return [];
					}
				}).catch(err => {
					console.error('门店数据加载失败:', err);
					return [];
				});
			},
			// 获取当前用户门店信息
			getCurrentUserStorePromise() {
				return new Promise((resolve, reject) => {
					getInfo().then(res => {
						resolve(res.data.userInfo);
					}).catch(err => {
						console.error('获取当前用户信息失败:', err);
						reject(err);
					});
				});
			},
		}
	}
</script>

<style scoped>
/* 表单布局优化 */
.form-layout {
	margin: 0;
}

.form-layout .el-col {
	margin-bottom: 18px;
}

/* 表单行间距优化 */
.form-layout .el-form-item {
	margin-bottom: 0;
}

/* 表单项高度统一 */
.form-layout .el-form-item__content {
	line-height: 32px;
}

/* 表单项标签样式 */
.form-layout .el-form-item__label {
	line-height: 32px;
	padding-right: 12px;
	font-weight: 500;
}

/* 输入框高度统一 */
.form-layout .el-input__inner,
.form-layout .el-select .el-input__inner {
	height: 32px;
	line-height: 32px;
}

/* 单选框组样式 */
.form-layout .el-radio-group {
	line-height: 32px;
}

.form-layout .el-radio {
	margin-right: 20px;
	line-height: 32px;
}

/* 表格标题样式 */
.table-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 12px;
	padding: 12px 16px;
	background: #f5f7fa;
	border-radius: 6px;
	border-left: 4px solid #409EFF;
	box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.table-title {
	font-size: 15px;
	font-weight: 600;
	color: #303133;
}

/* 品项列表容器 */
.px-list-container {
	width: 100%;
	margin-top: 8px;
}

/* 品项项 */
.px-item {
	margin-bottom: 24px;
	border: 1px solid #e4e7ed;
	border-radius: 8px;
	background: #fff;
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
	overflow: hidden;
	transition: all 0.3s ease;
}

.px-item:hover {
	box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
}

/* 品项基本信息 */
.px-basic-info {
	background: #f8f9fa;
	padding: 20px;
	border-bottom: 1px solid #e4e7ed;
}

.px-item-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 18px;
}

.px-item-title {
	font-size: 16px;
	font-weight: 600;
	color: #303133;
}

/* 品项选择行 */
.px-select-row {
	margin-bottom: 15px;
}

/* 品项详细信息 */
.px-detail-info {
	background: #fff;
	padding: 15px;
	border-radius: 6px;
	border: 1px solid #e4e7ed;
	margin-bottom: 15px;
}

.px-detail-row {
	display: flex;
	flex-wrap: wrap;
	gap: 20px;
	margin-bottom: 15px;
}

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

.px-detail-label {
	font-size: 14px;
	color: #606266;
	font-weight: 500;
	margin-right: 8px;
}

.px-detail-value {
	font-size: 14px;
	color: #303133;
	font-weight: 600;
}

/* 消费数量输入行 */
.px-consumption-row {
	display: flex;
	align-items: center;
	gap: 10px;
}

/* 人员业绩区域 */
.px-staff-section {
	padding: 18px 20px;
	border-bottom: 1px solid #e4e7ed;
}

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

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

.px-staff-title {
	font-size: 14px;
	font-weight: 600;
	color: #409EFF;
}

.px-staff-list {
	display: flex;
	flex-direction: column;
	gap: 10px;
}

.px-staff-row {
	width: 100%;
}

.px-staff-item {
	display: flex;
	flex-direction: column;
	padding: 12px 16px;
	border: 1px solid #e4e7ed;
	border-radius: 6px;
	background: #fafafa;
	transition: all 0.2s ease;
}

.px-staff-item:hover {
	background: #f5f7fa;
	border-color: #c0c4cc;
}

.px-staff-info {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 10px;
}

.px-staff-name {
	font-size: 14px;
	font-weight: 600;
	color: #303133;
}

.px-staff-fields {
	display: flex;
	flex-wrap: wrap;
	gap: 15px;
	align-items: flex-end;
}

.px-staff-field {
	display: flex;
	flex-direction: column;
	gap: 4px;
}

.px-staff-field label {
	font-size: 12px;
	color: #606266;
	font-weight: 500;
	white-space: nowrap;
}

/* 科技部老师提示信息 */
.px-staff-tip {
	display: flex;
	align-items: center;
	padding: 12px 16px;
	background: #f0f9ff;
	border: 1px solid #b3d8ff;
	border-radius: 6px;
	color: #409eff;
	font-size: 14px;
}

.px-staff-tip i {
	margin-right: 8px;
	font-size: 16px;
}

/* 输入框组样式 */
.el-input-group__append {
	background: #f5f7fa;
	border-color: #dcdfe6;
	color: #606266;
}

/* 响应式布局 */
@media (max-width: 1200px) {
	.form-layout .el-col[class*="el-col-8"] {
		width: 50%;
		margin-bottom: 16px;
	}
}

@media (max-width: 768px) {
	.form-layout .el-col {
		margin-bottom: 12px;
	}

	.form-layout .el-col[class*="el-col-8"] {
		width: 100%;
		padding-left: 0;
		padding-right: 0;
		margin-bottom: 16px;
	}

	.px-basic-fields {
		flex-direction: column;
		align-items: stretch;
		gap: 16px;
	}

	.px-field {
		width: 100%;
		min-width: auto;
	}
}
</style>
