<template>
	<div class="NCC-common-layout">
		<div class="NCC-common-layout-center">
			<!-- 筛选条件 -->
			<el-row class="NCC-common-search-box" :gutter="16">
				<el-form @submit.native.prevent>
					<el-col :span="6">
						<el-form-item label="门店" required>
							<el-select v-model="query.storeId" placeholder="请选择门店" clearable filterable @change="handleStoreChange">
								<el-option v-for="store in storeOptions" :key="store.id" :label="store.dm" :value="store.id" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="开始时间">
							<el-date-picker 
								v-model="query.startTime" 
								type="datetime" 
								value-format="timestamp" 
								format="yyyy-MM-dd HH:mm:ss" 
								placeholder="开始时间"
							/>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="结束时间">
							<el-date-picker 
								v-model="query.endTime" 
								type="datetime" 
								value-format="timestamp" 
								format="yyyy-MM-dd HH:mm:ss" 
								placeholder="结束时间"
							/>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="品项">
							<el-select
								v-model="query.itemId"
								placeholder="请选择品项"
								filterable
								clearable
								:style='{"width":"100%"}'>
								<el-option
									v-for="item in itemOptions"
									:key="item.id"
									:label="item.xmmc"
									:value="item.id">
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="会员">
							<el-select
								v-model="query.memberId"
								placeholder="请选择会员"
								filterable
								remote
								:remote-method="remoteMemberMethod"
								:loading="memberLoading"
								clearable
								:style='{"width":"100%"}'>
								<el-option
									v-for="item in memberOptions"
									:key="item.id"
									:label="`${item.khmc}(${item.sjh || ''} ${item.gsmdName || ''})`"
									:value="item.id">
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="品项类型">
							<el-select
								v-model="query.ItemCategory"
								placeholder="请选择品项类型"
								filterable
								clearable
								:style='{"width":"100%"}'>
								<el-option
									v-for="item in itemTypeOptions"
									:key="item.value"
									:label="item.label"
									:value="item.value">
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item label="健康师">
							<el-select
								v-model="query.HealthCoachId"
								placeholder="请选择健康师"
								filterable
								clearable
								:style='{"width":"100%"}'>
								<el-option
									v-for="item in healthCoachOptions"
									:key="item.id"
									:label="item.fullName"
									:value="item.id">
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="6">
						<el-form-item>
							<el-button type="primary" icon="el-icon-search" @click="search()">查询</el-button>
							<el-button icon="el-icon-refresh-right" @click="reset()">重置</el-button>
							<el-button icon="el-icon-download" @click="exportExcel()">导出Excel</el-button>
							<el-button icon="el-icon-setting" @click="showColumnDialog = true">字段设置</el-button>
						</el-form-item>
					</el-col>
				</el-form>
			</el-row>

			<!-- 统计卡片 -->
			<div class="statistics-cards" v-if="summaryData">
				<el-row :gutter="16">
					<el-col :span="6">
						<div class="statistics-card">
							<div class="card-icon">
								<i class="el-icon-document"></i>
							</div>
							<div class="card-content">
								<div class="card-title">总开单数</div>
								<div class="card-value">{{ summaryData.totalCount || 0 }}</div>
							</div>
						</div>
					</el-col>
					<el-col :span="6">
						<div class="statistics-card">
							<div class="card-icon">
								<i class="el-icon-money"></i>
							</div>
							<div class="card-content">
								<div class="card-title">总金额</div>
								<div class="card-value">¥{{ formatMoney(summaryData.totalAmount) }}</div>
							</div>
						</div>
					</el-col>
					<el-col :span="6">
						<div class="statistics-card">
							<div class="card-icon">
								<i class="el-icon-success"></i>
							</div>
							<div class="card-content">
								<div class="card-title">已付金额</div>
								<div class="card-value">¥{{ formatMoney(summaryData.totalPaidAmount) }}</div>
							</div>
						</div>
					</el-col>
					<el-col :span="6">
						<div class="statistics-card">
							<div class="card-icon">
								<i class="el-icon-warning"></i>
							</div>
							<div class="card-content">
								<div class="card-title">欠款金额</div>
								<div class="card-value">¥{{ formatMoney(summaryData.totalDebt) }}</div>
							</div>
						</div>
					</el-col>
				</el-row>
				<el-row :gutter="16" style="margin-top: 16px;">
					<el-col :span="6">
						<div class="statistics-card">
							<div class="card-icon">
								<i class="el-icon-goods"></i>
							</div>
							<div class="card-content">
								<div class="card-title">购买项目</div>
								<div class="card-value">{{ summaryData.totalPurchasedItems || 0 }}</div>
							</div>
						</div>
					</el-col>
					<el-col :span="6">
						<div class="statistics-card">
							<div class="card-icon">
								<i class="el-icon-present"></i>
							</div>
							<div class="card-content">
								<div class="card-title">赠送项目</div>
								<div class="card-value">{{ summaryData.totalGiftedItems || 0 }}</div>
							</div>
						</div>
					</el-col>
					<el-col :span="6">
						<div class="statistics-card">
							<div class="card-icon">
								<i class="el-icon-star-on"></i>
							</div>
							<div class="card-content">
								<div class="card-title">体验项目</div>
								<div class="card-value">{{ summaryData.totalExperienceItems || 0 }}</div>
							</div>
						</div>
					</el-col>
					<el-col :span="6">
						<div class="statistics-card">
							<div class="card-icon">
								<i class="el-icon-user"></i>
							</div>
							<div class="card-content">
								<div class="card-title">健康师人数</div>
								<div class="card-value">{{ summaryData.totalHealthTeachers || 0 }}</div>
							</div>
						</div>
					</el-col>
				</el-row>
			</div>

			<!-- 数据表格 -->
			<div class="NCC-common-layout-main NCC-flex-main table-wrapper">
				<el-table 
					v-loading="listLoading" 
					:data="records" 
					border
					class="NCC-common-table"
					:height="tableHeight"
					@sort-change="handleSortChange">
					<el-table-column 
						v-for="col in visibleColumns" 
						:key="col.prop"
						:prop="col.prop" 
						:label="col.label" 
						:width="col.width"
						:min-width="col.minWidth"
						:sortable="col.sortable ? 'custom' : false"
						:align="col.align || 'left'">
						<template slot-scope="scope">
							<!-- 开单日期 -->
							<span v-if="col.prop === 'date'">
								{{ formatDate(scope.row.date) }}
							</span>
							<!-- 客户类型 -->
							<el-tag v-else-if="col.prop === 'customerType'" :type="scope.row.customerType === '会员' ? 'success' : 'info'" size="small">
								{{ scope.row.customerType }}
							</el-tag>
							<!-- 购买项目 -->
							<div v-else-if="col.prop === 'purchasedItems'">
								<div v-if="scope.row.purchasedItems && scope.row.purchasedItems.length > 0">
									<div v-for="(item, itemIndex) in scope.row.purchasedItems" :key="`purchased-${scope.$index}-${itemIndex}-${item.id || itemIndex}`" class="item-row">
										<span class="item-name">{{ item.itemName }}</span>
										<span class="item-info">({{ item.projectNumber }}次 × ¥{{ item.price }})</span>
										<span class="item-info">({{ item.itemCategory }})</span>
									</div>
								</div>
								<span v-else class="no-data">无</span>
							</div>
							<!-- 赠送项目 -->
							<div v-else-if="col.prop === 'giftedItems'">
								<div v-if="scope.row.giftedItems && scope.row.giftedItems.length > 0">
									<div v-for="(item, itemIndex) in scope.row.giftedItems" :key="`gifted-${scope.$index}-${itemIndex}-${item.id || itemIndex}`" class="item-row">
										<span class="item-name">{{ item.itemName }}</span>
										<span class="item-info">({{ item.projectNumber }}次)</span>
										<span v-if="item.remark" class="item-remark">{{ item.remark }}</span>
										<span class="item-info">({{ item.itemCategory }})</span>
									</div>
								</div>
								<span v-else class="no-data">无</span>
							</div>
							<!-- 体验项目 -->
							<div v-else-if="col.prop === 'experienceItems'">
								<div v-if="scope.row.experienceItems && scope.row.experienceItems.length > 0">
									<div v-for="(item, itemIndex) in scope.row.experienceItems" :key="`experience-${scope.$index}-${itemIndex}-${item.id || itemIndex}`" class="item-row">
										<span class="item-name">{{ item.itemName }}</span>
										<span class="item-info">({{ item.projectNumber }}次)</span>
										<span class="item-info">({{ item.itemCategory }})</span>
									</div>
								</div>
								<span v-else class="no-data">无</span>
							</div>
							<!-- 健康师 -->
							<div v-else-if="col.prop === 'healthTeachers'">
								<div v-if="scope.row.healthTeachers && scope.row.healthTeachers.length > 0">
									<div v-for="(teacher, teacherIndex) in scope.row.healthTeachers" :key="`teacher-${scope.$index}-${teacherIndex}-${teacher.teacherId || teacher.teacherName || teacherIndex}`" class="teacher-row">
										<span class="teacher-name">{{ teacher.teacherName }}</span>
										<span class="teacher-performance">业绩: ¥{{ teacher.performance }}</span>
										<span class="item-info">({{teacher.itemName+ ' '+ teacher.itemCategory }})</span>
									</div>
								</div>
								<span v-else class="no-data">无</span>
							</div>
							<!-- 已付金额 -->
							<span v-else-if="col.prop === 'paidAmount'" class="amount-paid">
								¥{{ formatMoney(scope.row.paidAmount) }}
							</span>
							<!-- 欠款金额 -->
							<span v-else-if="col.prop === 'debtAmount'" class="amount-debt">
								¥{{ formatMoney(scope.row.debtAmount) }}
							</span>
							<!-- 总金额 -->
							<span v-else-if="col.prop === 'totalAmount'" class="amount-total">
								¥{{ formatMoney(scope.row.totalAmount) }}
							</span>
							<!-- 支付方式 -->
							<span v-else-if="col.prop === 'paymentMethod'">
								{{ scope.row.paymentMethod || '无' }}
							</span>
							<!-- 合作机构 -->
							<span v-else-if="col.prop === 'cooperationInstitutionName'">
								{{ scope.row.paymentMethod == '合作' ? (scope.row.cooperationInstitutionName || '无') : '无' }}
							</span>
							<!-- 结算结构 -->
							<span v-else-if="col.prop === 'paymentHospitalName'">
								{{ scope.row.paymentMethod != '合作' ? (scope.row.paymentHospitalName || '无') : '无' }}
							</span>
							<!-- 活动名称 -->
							<span v-else-if="col.prop === 'activityName'">
								{{ scope.row.activityName || '无' }}
							</span>
							<!-- 备注 -->
							<span v-else-if="col.prop === 'remark'">
								{{ scope.row.remark || '无' }}
							</span>
							<!-- 开单时间 -->
							<span v-else-if="col.prop === 'createTime'">
								{{ formatTime(scope.row.createTime) }}
							</span>
							<!-- 默认显示 -->
							<span v-else>
								{{ scope.row[col.prop] !== null && scope.row[col.prop] !== undefined ? scope.row[col.prop] : '无' }}
							</span>
						</template>
					</el-table-column>
					<template slot="empty">
						<el-empty description="暂无数据" :image-size="120"></el-empty>
					</template>
				</el-table>
			</div>
		</div>

		<!-- 字段设置弹窗 -->
		<el-dialog title="字段设置" :visible.sync="showColumnDialog" width="500px" append-to-body>
			<div class="column-settings">
				<div class="column-actions" style="margin-bottom: 15px;">
					<el-button size="small" @click="selectAllColumns">全选</el-button>
					<el-button size="small" @click="clearAllColumns">清空</el-button>
				</div>
				<el-checkbox-group v-model="selectedColumns">
					<el-checkbox 
						v-for="col in columnOptions" 
						:key="col.prop" 
						:label="col.prop"
						style="display: block; margin-bottom: 10px;">
						{{ col.label }}
					</el-checkbox>
				</el-checkbox-group>
			</div>
			<div slot="footer" class="dialog-footer">
				<el-button @click="showColumnDialog = false">取消</el-button>
				<el-button type="primary" @click="saveColumnSettings">确定</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
import request from '@/utils/request'
import { saveAs } from 'file-saver'

export default {
	name: 'BillingRecordSummary',
		data() {
			return {
				query: {
					storeId: undefined,
					startTime: undefined,
					endTime: undefined,
					itemId: undefined,
					memberId: undefined,
					ItemCategory: undefined,
					HealthCoachId: undefined
				},
				storeOptions: [],
				itemOptions: [],
				memberOptions: [],
				memberLoading: false,
				itemTypeOptions: [],
				healthCoachOptions: [],
				summaryData: null,
				records: [],
				listLoading: false,
				showColumnDialog: false,
				selectedColumns: [],
				sortInfo: {
					prop: '',
					order: ''
				},
			// 所有列配置
			columnOptions: [
				{ prop: 'date', label: '开单日期', width: 120, sortable: false, align: 'left' },
				{ prop: 'customerName', label: '客户姓名', width: 100, sortable: false, align: 'left' },
				{ prop: 'customerPhone', label: '客户电话', width: 120, sortable: false, align: 'left' },
				{ prop: 'goldTriangle', label: '金三角', width: 100, sortable: false, align: 'left' },
				{ prop: 'customerType', label: '客户类型', width: 100, sortable: false, align: 'left' },
				{ prop: 'purchasedItems', label: '购买项目', minWidth: 250, sortable: false, align: 'left' },
				{ prop: 'giftedItems', label: '赠送项目', minWidth: 200, sortable: false, align: 'left' },
				{ prop: 'experienceItems', label: '体验项目', minWidth: 200, sortable: false, align: 'left' },
				{ prop: 'healthTeachers', label: '健康师', minWidth: 250, sortable: false, align: 'left' },
				{ prop: 'paidAmount', label: '已付金额', width: 100, sortable: true, align: 'left' },
				{ prop: 'debtAmount', label: '欠款金额', width: 100, sortable: true, align: 'left' },
				{ prop: 'totalAmount', label: '总金额', width: 100, sortable: true, align: 'left' },
				{ prop: 'paymentMethod', label: '支付方式', width: 100, sortable: false, align: 'left' },
				{ prop: 'cooperationInstitutionName', label: '合作机构', width: 120, sortable: false, align: 'left' },
				{ prop: 'paymentHospitalName', label: '结算结构', width: 120, sortable: false, align: 'left' },
				{ prop: 'activityName', label: '活动名称', width: 120, sortable: false, align: 'left' },
				{ prop: 'remark', label: '备注', minWidth: 150, sortable: false, align: 'left' },
				{ prop: 'createTime', label: '开单时间', width: 150, sortable: true, align: 'left' }
			]
		}
	},
	computed: {
		// 可见的列
		visibleColumns() {
			return this.columnOptions.filter(col => this.selectedColumns.includes(col.prop))
		},
		// 计算表格高度
		tableHeight() {
			// 根据视口高度动态计算，减去筛选条件、统计卡片等的高度
			return 'calc(100vh - 400px)'
		}
	},
	created() {
		this.initStoreOptions()
		this.initItemOptions()
		this.initItemTypeOptions()
		this.initMemberOptions()
		this.initHealthCoachOptions()
		this.setDefaultTimeRange()
		this.initColumnSettings()
	},
	methods: {
		// 初始化门店选项
		initStoreOptions() {
			request({
				url: '/api/Extend/LqMdxx',
				method: 'GET',
				data: {
					currentPage: 1,
					pageSize: 1000
				}
			}).then(res => {
				this.storeOptions = res.data.list || []
			}).catch(err => {
				console.error('获取门店列表失败:', err)
			})
		},
		
		// 初始化品项选项
		initItemOptions() {
			request({
				url: '/api/Extend/LqXmzl',
				method: 'GET',
				data: {
					currentPage: 1,
					pageSize: 1000
				}
			}).then(res => {
				if (res.data && res.data.list) {
					this.itemOptions = res.data.list
				}
			}).catch(() => {
				this.itemOptions = []
			})
		},
		
		// 初始化品项类型选项（使用qt2字段数据）
		initItemTypeOptions() {
			request({
				url: '/api/Extend/lqxmzl/GetDistinctFieldData?fieldName=qt2',
				method: 'GET'
			}).then(res => {
				if (res.code == 200 && res.data && res.data.values) {
					this.itemTypeOptions = res.data.values.map(item => ({
						label: item,
						value: item
					}))
				} else {
					this.itemTypeOptions = []
				}
			}).catch(() => {
				this.itemTypeOptions = []
			})
		},
		
		// 初始化会员选项
		initMemberOptions() {
			request({
				url: '/api/Extend/LqKhxx',
				method: 'GET',
				data: {
					currentPage: 1,
					pageSize: 10
				}
			}).then(res => {
				if (res.code == 200 && res.data.list && res.data.list.length > 0) {
					this.memberOptions = res.data.list
				}
			}).catch(() => {
				this.memberOptions = []
			})
		},
		
		// 会员远程搜索
		remoteMemberMethod(query) {
			if (query !== '') {
				this.memberLoading = true
				request({
					url: '/api/Extend/LqKhxx',
					method: 'GET',
					data: {
						currentPage: 1,
						pageSize: 20,
						keyword: query
					}
				}).then(res => {
					this.memberLoading = false
					if (res.code == 200 && res.data.list && res.data.list.length > 0) {
						this.memberOptions = res.data.list
					} else {
						this.memberOptions = []
					}
				}).catch(() => {
					this.memberLoading = false
					this.memberOptions = []
				})
			} else {
				this.memberOptions = []
			}
		},
		
		// 初始化健康师选项
		initHealthCoachOptions() {
			// 如果选择了门店，则根据门店获取健康师；否则获取所有健康师
			const mdid = this.query.storeId ? `&mdid=${this.query.storeId}` : ''
			request({
				url: `/api/Extend/user?page=1&pageSize=1000${mdid}&gw=健康师`,
				method: 'GET'
			}).then(res => {
				if (res.code == 200 && res.data.list && res.data.list.length > 0) {
					this.healthCoachOptions = 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
					}))
				} else {
					this.healthCoachOptions = []
				}
			}).catch(() => {
				this.healthCoachOptions = []
			})
		},
		
		// 门店选择改变时重新加载健康师选项
		handleStoreChange() {
			// 清空健康师选择
			this.query.HealthCoachId = undefined
			// 重新加载健康师选项
			this.initHealthCoachOptions()
		},
		
		// 设置默认时间范围（本月1号到现在）
		setDefaultTimeRange() {
			const now = new Date()
			const firstDayOfMonth = new Date(now.getFullYear(), now.getMonth(), 1)
			
			this.query.startTime = firstDayOfMonth.getTime()
			this.query.endTime = now.getTime()
		},
		
		// 查询数据
		search() {
			if (!this.query.storeId) {
				this.$message({
					type: 'warning',
					message: '请选择门店',
					duration: 1500
				})
				return
			}
			
			this.listLoading = true
			
			const params = {
				storeId: this.query.storeId,
				startTime: this.query.startTime ? this.formatDateTime(this.query.startTime) : undefined,
				endTime: this.query.endTime ? this.formatDateTime(this.query.endTime) : undefined
			}
			
			if (this.query.itemId) {
				params.itemId = this.query.itemId
			}
			
			if (this.query.memberId) {
				params.memberId = this.query.memberId
			}
			
			if (this.query.ItemCategory) {
				params.ItemCategory = this.query.ItemCategory
			}
			
			if (this.query.HealthCoachId) {
				params.HealthCoachId = this.query.HealthCoachId
			}
			
			request({
				url: '/api/Extend/lqkdkdjlb/GetBillingRecordSummaryByStoreId',
				method: 'GET',
				data: params
			}).then(res => {
				if (res.data && res.data.data) {
					this.summaryData = res.data.data.summary
					this.records = res.data.data.records || []
				} else {
					this.summaryData = null
					this.records = []
				}
				this.listLoading = false
			}).catch(err => {
				console.error('查询失败:', err)
				this.$message({
					type: 'error',
					message: '查询失败，请重试',
					duration: 1500
				})
				this.listLoading = false
			})
		},
		
		// 重置查询条件
		reset() {
			this.query = {
				storeId: undefined,
				startTime: undefined,
				endTime: undefined,
				itemId: undefined,
				memberId: undefined,
				ItemCategory: undefined,
				HealthCoachId: undefined
			}
			this.summaryData = null
			this.records = []
			this.setDefaultTimeRange()
		},
		
		// 格式化金额
		formatMoney(amount) {
			if (!amount && amount !== 0) return '0.00'
			return Number(amount).toFixed(2)
		},
		
		// 格式化日期
		formatDate(dateStr) {
			if (!dateStr) return '无'
			return dateStr
		},
		
		// 格式化时间
		formatTime(timestamp) {
			if (!timestamp) return '无'
			const date = new Date(timestamp)
			return date.toLocaleString('zh-CN', {
				year: 'numeric',
				month: '2-digit',
				day: '2-digit',
				hour: '2-digit',
				minute: '2-digit',
				second: '2-digit'
			})
		},
		
		// 格式化日期时间（用于API传参）
		formatDateTime(timestamp) {
			if (!timestamp) return ''
			const date = new Date(timestamp)
			const year = date.getFullYear()
			const month = String(date.getMonth() + 1).padStart(2, '0')
			const day = String(date.getDate()).padStart(2, '0')
			const hours = String(date.getHours()).padStart(2, '0')
			const minutes = String(date.getMinutes()).padStart(2, '0')
			const seconds = String(date.getSeconds()).padStart(2, '0')
			return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
		},

		// 初始化列设置
		initColumnSettings() {
			// 默认显示所有列
			this.selectedColumns = this.columnOptions.map(col => col.prop)
			// 尝试从本地存储读取
			const savedColumns = localStorage.getItem('form1_column_settings')
			if (savedColumns) {
				try {
					const columns = JSON.parse(savedColumns)
					if (Array.isArray(columns) && columns.length > 0) {
						this.selectedColumns = columns
					}
				} catch (e) {
					console.error('读取列设置失败:', e)
				}
			}
		},

		// 全选列
		selectAllColumns() {
			this.selectedColumns = this.columnOptions.map(col => col.prop)
		},

		// 清空列
		clearAllColumns() {
			this.selectedColumns = []
		},

		// 保存列设置
		saveColumnSettings() {
			if (this.selectedColumns.length === 0) {
				this.$message({
					type: 'warning',
					message: '至少需要显示一列',
					duration: 1500
				})
				return
			}
			// 保存到本地存储
			localStorage.setItem('form1_column_settings', JSON.stringify(this.selectedColumns))
			this.showColumnDialog = false
			this.$message({
				type: 'success',
				message: '字段设置已保存',
				duration: 1500
			})
		},

		// 排序变化
		handleSortChange({ column, prop, order }) {
			this.sortInfo = {
				prop: prop || '',
				order: order || ''
			}
			this.sortList()
		},

		// 排序列表
		sortList() {
			if (!this.sortInfo.prop || !this.sortInfo.order) {
				return
			}

			const prop = this.sortInfo.prop
			const order = this.sortInfo.order
			const isAsc = order === 'ascending'

			this.records.sort((a, b) => {
				let aVal = a[prop]
				let bVal = b[prop]

				// 处理空值
				if (aVal === null || aVal === undefined) aVal = 0
				if (bVal === null || bVal === undefined) bVal = 0

				// 转换为数字进行比较
				aVal = Number(aVal)
				bVal = Number(bVal)

				if (isNaN(aVal)) aVal = 0
				if (isNaN(bVal)) bVal = 0

				if (isAsc) {
					return aVal - bVal
				} else {
					return bVal - aVal
				}
			})
		},

		// 导出Excel
		async exportExcel() {
			if (!this.records || this.records.length === 0) {
				this.$message({
					type: 'warning',
					message: '暂无数据可导出',
					duration: 1500
				})
				return
			}

			try {
				// 动态导入 xlsx 库
				const XLSX = await import('xlsx')
				
				// 构建表头
				const headers = [
					'开单日期',
					'客户姓名',
					'客户电话',
					'金三角',
					'客户类型',
					'健康师',
					'业绩金额',
					'相关品项',
					'分类',
					'类型',
					'单价',
					'次数',
					'品项金额',
					'已付金额',
					'欠款金额',
					'总金额',
					'支付方式',
					'合作机构',
					'结算结构',
					'活动名称',
					'备注',
					'开单时间'
				]
				
				// 构建数据行：以健康师为维度扁平化数据
				const dataRows = []
				this.records.forEach(row => {
					// 获取基础数据
					const baseData = {
						date: this.formatDate(row.date) || '无',
						customerName: row.customerName || '无',
						customerPhone: row.customerPhone || '无',
						goldTriangle: row.goldTriangle || '无',
						customerType: row.customerType || '无',
						paidAmount: `¥${this.formatMoney(row.paidAmount)}`,
						debtAmount: `¥${this.formatMoney(row.debtAmount)}`,
						totalAmount: `¥${this.formatMoney(row.totalAmount)}`,
						paymentMethod: row.paymentMethod || '无',
						cooperationInstitutionName: row.paymentMethod == '合作'?(row.cooperationInstitutionName || '无'):'无',
						paymentHospitalName: row.paymentMethod != '合作'?(row.paymentHospitalName || '无'):'无',
						activityName: row.activityName || '无',
						remark: row.remark || '无',
						createTime: this.formatTime(row.createTime) || '无'
					}
					
					// 获取健康师数据
					const healthTeachers = row.healthTeachers && row.healthTeachers.length > 0 
						? row.healthTeachers 
						: []
					
					// 获取购买项目数据
					const purchasedItems = row.purchasedItems && row.purchasedItems.length > 0 
						? row.purchasedItems 
						: []
					
					// 获取赠送项目数据
					const giftedItems = row.giftedItems && row.giftedItems.length > 0 
						? row.giftedItems 
						: []
					
					// 获取体验项目数据
					const experienceItems = row.experienceItems && row.experienceItems.length > 0 
						? row.experienceItems 
						: []
					
					// 如果没有健康师，创建一行空数据
					if (healthTeachers.length === 0) {
						const rowData = [
							baseData.date,
							baseData.customerName,
							baseData.customerPhone,
							baseData.goldTriangle,
							baseData.customerType,
							'无', // 健康师
							'¥0.00', // 业绩金额
							'无', // 相关品项
							'无', // 分类
							'无', // 类型
							'¥0.00', // 单价
							0, // 次数
							'¥0.00', // 品项金额
							baseData.paidAmount,
							baseData.debtAmount,
							baseData.totalAmount,
							baseData.paymentMethod,
							baseData.cooperationInstitutionName,
							baseData.paymentHospitalName,
							baseData.activityName,
							baseData.remark,
							baseData.createTime
						]
						dataRows.push(rowData)
						return
					}
					
					// 以健康师为维度展开数据
					healthTeachers.forEach((teacher, teacherIndex) => {
						// 根据健康师的 itemDetailId 匹配对应的项目
						const itemDetailId = teacher.itemDetailId || ''
						
						// 在购买项目中查找匹配的项
						let matchedItem = purchasedItems.find(item => item.id === itemDetailId)
						let itemType = '购买'
						
						// 如果购买项目中没有找到，在赠送项目中查找
						if (!matchedItem) {
							matchedItem = giftedItems.find(item => item.id === itemDetailId)
							itemType = '赠送'
						}
						
						// 如果赠送项目中也没有找到，在体验项目中查找
						if (!matchedItem) {
							matchedItem = experienceItems.find(item => item.id === itemDetailId)
							itemType = '体验'
						}
						
						// 计算品项金额（单价 * 次数）
						const price = matchedItem && matchedItem.price ? Number(matchedItem.price) : 0
						const projectNumber = matchedItem ? (Number(matchedItem.projectNumber) || 0) : 0
						const itemAmount = price * projectNumber
						
						// 构建行数据
						const rowData = [
							teacherIndex === 0 ? baseData.date : '', // 开单日期（只在第一行显示）
							teacherIndex === 0 ? baseData.customerName : '', // 客户姓名（只在第一行显示）
							teacherIndex === 0 ? baseData.customerPhone : '', // 客户电话（只在第一行显示）
							teacherIndex === 0 ? baseData.goldTriangle : '', // 金三角（只在第一行显示）
							teacherIndex === 0 ? baseData.customerType : '', // 客户类型（只在第一行显示）
							teacher.teacherName || '无', // 健康师
							teacher.performance ? `¥${this.formatMoney(teacher.performance)}` : '¥0.00', // 业绩金额
							matchedItem ? (matchedItem.itemName || '无') : (teacher.itemName || '无'), // 相关品项
							matchedItem ? (matchedItem.itemCategory || '无') : (teacher.itemCategory || '无'), // 分类
							matchedItem ? itemType : '无', // 类型（购买/赠送/体验）
							matchedItem && matchedItem.price ? `¥${this.formatMoney(matchedItem.price)}` : '¥0.00', // 单价
							matchedItem ? (matchedItem.projectNumber || 0) : 0, // 次数
							`¥${this.formatMoney(itemAmount)}`, // 品项金额（单价 * 次数）
							teacherIndex === 0 ? baseData.paidAmount : '', // 已付金额（只在第一行显示）
							teacherIndex === 0 ? baseData.debtAmount : '', // 欠款金额（只在第一行显示）
							teacherIndex === 0 ? baseData.totalAmount : '', // 总金额（只在第一行显示）
							teacherIndex === 0 ? baseData.paymentMethod : '', // 支付方式（只在第一行显示）
							teacherIndex === 0 ? baseData.cooperationInstitutionName : '', // 合作机构（只在第一行显示）
							teacherIndex === 0 ? baseData.paymentHospitalName : '', // 结算结构（只在第一行显示）
							teacherIndex === 0 ? baseData.activityName : '', // 活动名称（只在第一行显示）
							teacherIndex === 0 ? baseData.remark : '', // 备注（只在第一行显示）
							teacherIndex === 0 ? baseData.createTime : '' // 开单时间（只在第一行显示）
						]
						dataRows.push(rowData)
					})
				})
				
				// 合并表头和数据
				const excelData = [headers, ...dataRows]
				
				// 创建工作簿
				const ws = XLSX.utils.aoa_to_sheet(excelData)
				
				// 设置列宽
				ws['!cols'] = [
					{ wch: 12 }, // 开单日期
					{ wch: 12 }, // 客户姓名
					{ wch: 15 }, // 客户电话
					{ wch: 12 }, // 金三角
					{ wch: 12 }, // 客户类型
					{ wch: 12 }, // 健康师
					{ wch: 12 }, // 业绩金额
					{ wch: 20 }, // 相关品项
					{ wch: 12 }, // 分类
					{ wch: 10 }, // 类型
					{ wch: 12 }, // 单价
					{ wch: 10 }, // 次数
					{ wch: 12 }, // 品项金额
					{ wch: 12 }, // 已付金额
					{ wch: 12 }, // 欠款金额
					{ wch: 12 }, // 总金额
					{ wch: 12 }, // 支付方式
					{ wch: 15 }, // 合作机构
					{ wch: 15 }, // 结算结构
					{ wch: 15 }, // 活动名称
					{ wch: 20 }, // 备注
					{ wch: 20 }  // 开单时间
				]
				
				// 创建工作簿
				const wb = XLSX.utils.book_new()
				XLSX.utils.book_append_sheet(wb, ws, '开单记录汇总')
				
				// 生成文件名
				const store = this.storeOptions.find(s => s.id === this.query.storeId)
				const storeName = (store && store.dm) || '全部门店'
				const startTime = this.query.startTime ? this.formatDateTime(this.query.startTime).split(' ')[0] : ''
				const endTime = this.query.endTime ? this.formatDateTime(this.query.endTime).split(' ')[0] : ''
				const fileName = `开单记录汇总_${storeName}_${startTime}_${endTime}_${new Date().getTime()}.xlsx`
				
				// 导出文件
				const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'array' })
				saveAs(new Blob([wbout], { type: 'application/octet-stream' }), fileName)
				
				this.$message({
					type: 'success',
					message: '导出成功',
					duration: 1500
				})
			} catch (error) {
				console.error('导出失败:', error)
				if (error.message && error.message.includes('xlsx')) {
					this.$message({
						type: 'error',
						message: '导出失败：请先安装 xlsx 库，运行命令: npm install xlsx --save',
						duration: 3000
					})
				} else {
					this.$message({
						type: 'error',
						message: '导出失败：' + (error.message || '未知错误'),
						duration: 2000
					})
				}
			}
		}

	}
}
</script>

<style lang="scss" scoped>
.statistics-cards {
	margin-bottom: 20px;
}

.statistics-card {
	height: 100px;
	padding: 12px;
	border-radius: 12px;
	background: #fff;
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
	display: flex;
	align-items: center;
	
	.card-icon {
		width: 60px;
		height: 60px;
		border-radius: 8px;
		background: linear-gradient(135deg, #409EFF, #67C23A);
		display: flex;
		align-items: center;
		justify-content: center;
		margin-right: 16px;
		
		i {
			font-size: 24px;
			color: #fff;
		}
	}
	
	.card-content {
		flex: 1;
		
		.card-title {
			font-size: 14px;
			color: #909399;
			margin-bottom: 8px;
		}
		
		.card-value {
			font-size: 24px;
			font-weight: bold;
			color: #303133;
		}
	}
}

.item-row, .teacher-row {
	margin-bottom: 4px;
	
	&:last-child {
		margin-bottom: 0;
	}
}

.item-name, .teacher-name {
	font-weight: 500;
	color: #303133;
}

.item-info, .teacher-performance {
	font-size: 12px;
	color: #909399;
	margin-left: 8px;
}

.item-remark {
	font-size: 12px;
	color: #F56C6C;
	margin-left: 8px;
}

.no-data {
	color: #C0C4CC;
	font-style: italic;
}

.amount-paid {
	color: #67C23A;
	font-weight: 500;
}

.amount-debt {
	color: #F56C6C;
	font-weight: 500;
}

.amount-total {
	color: #409EFF;
	font-weight: 500;
}

.table-wrapper {
	height: 100%;
	overflow: hidden;
	
	::v-deep .el-table {
		width: 100%;
	}
	
	::v-deep .el-table__body-wrapper {
		overflow-y: auto;
		overflow-x: auto;
	}
	
	::v-deep .el-table__header-wrapper {
		overflow-x: auto;
		overflow-y: hidden;
		// 隐藏滚动条但保持滚动功能
		scrollbar-width: none; // Firefox
		-ms-overflow-style: none; // IE 和 Edge
		
		&::-webkit-scrollbar {
			display: none; // Chrome, Safari, Opera
			width: 0;
			height: 0;
		}
	}
}

// 响应式设计
@media (max-width: 768px) {
	.statistics-cards {
		.el-col {
			margin-bottom: 16px;
		}
	}
	
	.statistics-card {
		height: 80px;
		padding: 8px;
		
		.card-icon {
			width: 50px;
			height: 50px;
			margin-right: 12px;
			
			i {
				font-size: 20px;
			}
		}
		
		.card-content {
			.card-title {
				font-size: 12px;
			}
			
			.card-value {
				font-size: 18px;
			}
		}
	}
}
</style>
