<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>
								<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-date-picker>
                            <!-- :picker-options="startTimePickerOptions" -->
						</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="结束时间"
								>
                                <!-- :picker-options="endTimePickerOptions" -->
							</el-date-picker>
						</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-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">
				<!-- <div class="NCC-common-head">
					<div>
						<el-button type="text" icon="el-icon-download" @click="exportData()">导出</el-button>
					</div>
					<div class="NCC-common-head-right">
						<el-tooltip effect="dark" content="刷新" placement="top">
							<el-link icon="icon-ym icon-ym-Refresh NCC-common-head-icon" :underline="false" @click="reset()" />
						</el-tooltip>
						<screenfull isContainer />
					</div>
				</div> -->
				
				<NCC-table v-loading="listLoading" :data="records" has-c>
					<el-table-column prop="date" label="开单日期" align="left" width="120">
						<template slot-scope="scope">
							{{ formatDate(scope.row.date) }}
						</template>
					</el-table-column>
					<el-table-column prop="customerName" label="客户姓名" align="left" width="100" />
					<el-table-column prop="customerPhone" label="客户电话" align="left" width="120" />
					<el-table-column prop="goldTriangle" label="金三角" align="left" width="100" />
					<el-table-column prop="customerType" label="客户类型" align="left" width="100">
						<template slot-scope="scope">
							<el-tag :type="scope.row.customerType === '会员' ? 'success' : 'info'" size="small">
								{{ scope.row.customerType }}
							</el-tag>
						</template>
					</el-table-column>
					<el-table-column label="购买项目" align="left" min-width="200">
						<template slot-scope="scope">
							<div v-if="scope.row.purchasedItems && scope.row.purchasedItems.length > 0">
								<div v-for="item in scope.row.purchasedItems" :key="item.id" class="item-row">
									<span class="item-name">{{ item.itemName }}</span>
									<span class="item-info">({{ item.projectNumber }}次 × ¥{{ item.price }})</span>
								</div>
							</div>
							<span v-else class="no-data">无</span>
						</template>
					</el-table-column>
					<el-table-column label="赠送项目" align="left" min-width="200">
						<template slot-scope="scope">
							<div v-if="scope.row.giftedItems && scope.row.giftedItems.length > 0">
								<div v-for="item in scope.row.giftedItems" :key="item.id" 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>
								</div>
							</div>
							<span v-else class="no-data">无</span>
						</template>
					</el-table-column>
					<el-table-column label="体验项目" align="left" min-width="200">
						<template slot-scope="scope">
							<div v-if="scope.row.experienceItems && scope.row.experienceItems.length > 0">
								<div v-for="item in scope.row.experienceItems" :key="item.id" class="item-row">
									<span class="item-name">{{ item.itemName }}</span>
									<span class="item-info">({{ item.projectNumber }}次)</span>
								</div>
							</div>
							<span v-else class="no-data">无</span>
						</template>
					</el-table-column>
					<el-table-column label="健康师" align="left" min-width="150">
						<template slot-scope="scope">
							<div v-if="scope.row.healthTeachers && scope.row.healthTeachers.length > 0">
								<div v-for="teacher in scope.row.healthTeachers" :key="teacher.teacherId" class="teacher-row">
									<span class="teacher-name">{{ teacher.teacherName }}</span>
									<span class="teacher-performance">业绩: ¥{{ teacher.performance }}</span>
								</div>
							</div>
							<span v-else class="no-data">无</span>
						</template>
					</el-table-column>
					<el-table-column prop="paidAmount" label="已付金额" align="left" width="100">
						<template slot-scope="scope">
							<span class="amount-paid">¥{{ formatMoney(scope.row.paidAmount) }}</span>
						</template>
					</el-table-column>
					<el-table-column prop="debtAmount" label="欠款金额" align="left" width="100">
						<template slot-scope="scope">
							<span class="amount-debt">¥{{ formatMoney(scope.row.debtAmount) }}</span>
						</template>
					</el-table-column>
					<el-table-column prop="totalAmount" label="总金额" align="left" width="100">
						<template slot-scope="scope">
							<span class="amount-total">¥{{ formatMoney(scope.row.totalAmount) }}</span>
						</template>
					</el-table-column>
					<el-table-column prop="paymentMethod" label="支付方式" align="left" width="100" />
					<el-table-column prop="remark" label="备注" align="left" min-width="150">
						<template slot-scope="scope">
							{{ scope.row.remark || '无' }}
						</template>
					</el-table-column>
					<el-table-column label="开单时间" prop="createTime" align="left" width="150">
						<template slot-scope="scope">
							{{ formatTime(scope.row.createTime) }}
						</template>
					</el-table-column>
				</NCC-table>
			</div>
		</div>
	</div>
</template>

<script>
import request from '@/utils/request'

export default {
	name: 'BillingRecordSummary',
	data() {
		return {
			query: {
				storeId: undefined,
				startTime: undefined,
				endTime: undefined
			},
			storeOptions: [],
			summaryData: null,
			records: [],
			listLoading: false,
			startTimePickerOptions: {
				disabledDate: (time) => {
					const timeMs = time.getTime()
					const nowMs = Date.now()
					const ninetyDaysMs = 90 * 24 * 60 * 60 * 1000
					// 不能选择未来日期
					if (timeMs > nowMs) return true
					// 若已选择结束时间：开始时间需在 [end-90天, end] 区间内
					if (this.query.endTime) {
						const minStart = this.query.endTime - ninetyDaysMs
						return timeMs < minStart || timeMs > this.query.endTime
					}
					return false
				}
			},
			endTimePickerOptions: {
				disabledDate: (time) => {
					const timeMs = time.getTime()
					const nowMs = Date.now()
					const ninetyDaysMs = 90 * 24 * 60 * 60 * 1000
					// 不能选择未来日期
					if (timeMs > nowMs) return true
					// 若已选择开始时间：结束时间需在 [start, start+90天] 区间内
					if (this.query.startTime) {
						const maxEnd = this.query.startTime + ninetyDaysMs
						return timeMs < this.query.startTime || timeMs > maxEnd
					}
					return false
				}
			}
		}
	},
	created() {
		this.initStoreOptions()
		this.setDefaultTimeRange()
	},
	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)
			})
		},
		
		// 设置默认时间范围（最近三个月）
		setDefaultTimeRange() {
			const now = new Date()
			const threeMonthsAgo = new Date()
			threeMonthsAgo.setMonth(now.getMonth() - 3)
			
			this.query.startTime = threeMonthsAgo.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
			}
			
			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
			}
			this.summaryData = null
			this.records = []
			this.setDefaultTimeRange()
		},
		
		// 导出数据
		exportData() {
			if (!this.query.storeId) {
				this.$message({
					type: 'warning',
					message: '请先选择门店并查询数据',
					duration: 1500
				})
				return
			}
			
			const params = {
				storeId: this.query.storeId,
				startTime: this.query.startTime,
				endTime: this.query.endTime
			}
			
			// 这里可以调用导出接口
			this.$message({
				type: 'info',
				message: '导出功能开发中...',
				duration: 1500
			})
		},
		
		// 格式化金额
		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}`
		}
	}
}
</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;
}

// 响应式设计
@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>
