<template>
	<view class="container">
		<!-- 统计类型切换 -->
		<view class="stat-tabs">
			<view 
				class="stat-tab" 
				:class="{ active: currentStatType === 'task' }" 
				@click="switchStatType('task')"
			>
				任务统计
			</view>
			<view 
				class="stat-tab" 
				:class="{ active: currentStatType === 'service' }" 
				@click="switchStatType('service')"
			>
				服务单统计
			</view>
		</view>
		
		<!-- 日期范围和筛选 -->
		<view class="date-filter-bar mb16">
			<view class="date-range" @click="showDatePicker = true">
				<image class="w32 h32" src="https://ysrw-1395926010.cos.ap-chengdu.myqcloud.com/image/icon_time.png" mode=""></image>
				<text class="date-text">{{ dateRangeText }}</text>
				<text class="arrow-down">▼</text>
			</view>
			<view class="filter-btn" @click="showFilter = true">
				<image class="w32 h32" src="https://ysrw-1395926010.cos.ap-chengdu.myqcloud.com/image/icon_select.png" mode=""></image>
				<text>筛选</text>
			</view>
		</view>

		<!-- 内容区域 - 动态显示不同的统计表格 -->
		<template v-if="currentStatType === 'task'">
			<!-- 任务完成统计表格 -->
			<statistics-table 
				:summary-title="summaryTitle.task[0]" 
				:summary-stats="summaryStats.taskComplete" 
				:columns="tableColumns.task"
				:table-data="tableData.taskComplete" 
				:loading="loading.task" 
				@load-more="loadMore('task')"
			>
			</statistics-table>

			<!-- 任务创建统计表格 -->
			<statistics-table 
				:summary-title="summaryTitle.task[1]" 
				:summary-stats="summaryStats.taskCreate" 
				:columns="tableColumns.task"
				:table-data="tableData.taskCreate" 
				:loading="loading.task" 
				@load-more="loadMore('task')"
			>
			</statistics-table>
		</template>

		<template v-else-if="currentStatType === 'service'">
			<!-- 服务单统计表格 -->
			<statistics-table 
				:summary-title="summaryTitle.service[0]" 
				:summary-stats="summaryStats.service" 
				:columns="tableColumns.service"
				:table-data="tableData.service" 
				:loading="loading.service" 
				@load-more="loadMore('service')"
			>
			</statistics-table>

			<statistics-table 
				:summary-title="summaryTitle.service[1]" 
				:summary-stats="summaryStats.service" 
				:columns="tableColumns.service"
				:table-data="tableData.service" 
				:loading="loading.service" 
				@load-more="loadMore('service')"
			>
			</statistics-table>
		</template>

		<!-- 日期选择弹窗 -->
		<view class="date-picker-popup" v-if="showDatePicker" @click="showDatePicker = false">
			<view class="date-picker-content" @click.stop>
				<view class="picker-header">
					<view class="picker-cancel" @click="showDatePicker = false">取消</view>
					<view class="picker-title">选择日期范围</view>
					<view class="picker-confirm" @click="confirmDateRange">确定</view>
				</view>
				<view class="picker-body">
					<view class="date-item">
						<text class="date-label">开始日期</text>
						<picker mode="date" :value="tempDateRange.startDate" @change="onStartDateChange">
							<view class="date-value">{{ tempDateRange.startDate || '请选择' }}</view>
						</picker>
					</view>
					<view class="date-item">
						<text class="date-label">结束日期</text>
						<picker mode="date" :value="tempDateRange.endDate" @change="onEndDateChange">
							<view class="date-value">{{ tempDateRange.endDate || '请选择' }}</view>
						</picker>
					</view>
				</view>
			</view>
		</view>

		<!-- 筛选弹窗 -->
		<view class="filter-popup" v-if="showFilter" @click="closeFilter">
			<view class="filter-content" @click.stop>
				<view class="filter-header">
					<view class="filter-title">筛选</view>
					<image class="filter-close-btn" src="https://ysrw-1395926010.cos.ap-chengdu.myqcloud.com/image/icon_cross.png" @click="closeFilter"></image>
				</view>

				<!-- 根据统计类型显示不同的筛选条件 -->
				<template v-if="currentStatType === 'task'">
					<!-- 任务类型筛选 -->
					<view class="filter-group">
						<view class="group-label">任务类型</view>
						<view class="filter-tags">
							<view class="filter-tag" :class="{ active: tempSelectedTaskType.includes(item.dictValue) }"
								v-for="(item, index) in taskTypeDict" :key="index" @click="toggleTaskType(item.dictValue)">
								{{ item.dictLabel }}
							</view>
						</view>
					</view>

					<!-- 任务状态筛选 -->
					<view class="filter-group">
						<view class="group-label">任务状态</view>
						<view class="filter-tags">
							<view class="filter-tag" :class="{ active: tempSelectedTaskStatus.includes(item.dictValue) }"
								v-for="(item, index) in taskStatusDict" :key="index" @click="toggleTaskStatus(item.dictValue)">
								{{ item.dictLabel }}
							</view>
						</view>
					</view>
				</template>

				<template v-else-if="currentStatType === 'service'">
					<!-- 服务单类型筛选 -->
					<view class="filter-group">
						<view class="group-label">服务单类型</view>
						<view class="filter-tags">
							<view class="filter-tag" :class="{ active: tempSelectedServiceType === item.value }"
								v-for="(item, index) in serviceTypeOptions" :key="index" @click="selectServiceType(item.value)">
								{{ item.label }}
							</view>
						</view>
					</view>

					<!-- 服务单状态筛选 -->
					<view class="filter-group">
						<view class="group-label">服务单状态</view>
						<view class="filter-tags">
							<view class="filter-tag" :class="{ active: tempSelectedServiceStatus === item.value }"
								v-for="(item, index) in serviceStatusOptions" :key="index"
								@click="selectServiceStatus(item.value)">
								{{ item.label }}
							</view>
						</view>
					</view>
				</template>

				<!-- 操作按钮 -->
				<view class="filter-actions">
					<view class="reset-btn" @click="resetFilters">重置</view>
					<view class="confirm-btn" @click="confirmFilters">确定</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import utils from '@/utils/common.js'
	import StatisticsTable from '@/components/StatisticsTable.vue'
	import { getTaskCompleteStats, getTaskCreateStats } from '@/api/task.js'
	export default {
		components: {
			StatisticsTable
		},
		data() {
			return {
				userInfo: uni.getStorageSync("userInfo")||'',
				statusBarHeight: uni.getSystemInfoSync().statusBarHeight + 'px',
				showDatePicker: false,
				showFilter: false,
				currentStatType: 'task', // 当前统计类型: task-任务统计, service-服务单统计
				
				// 日期范围
				dateRange: {
					startDate: '2025-12-01',
					endDate: '2025-12-25'
				},
				tempDateRange: {
					startDate: '2025-12-01',
					endDate: '2025-12-25'
				},
				
				// 任务统计筛选
				selectedTaskType: [],
				selectedTaskStatus: [],
				tempSelectedTaskType: [],
				tempSelectedTaskStatus: [],
				
				// 服务单统计筛选
				selectedServiceType: 'all',
				selectedServiceStatus: '',
				tempSelectedServiceType: 'all',
				tempSelectedServiceStatus: '',
				
				// 服务单类型选项
				serviceTypeOptions: [{
						label: '全部类型',
						value: 'all'
					},
					{
						label: '技术咨询',
						value: 'techConsultation'
					},
					{
						label: '售后服务',
						value: 'afterSales'
					},
					{
						label: '安装服务',
						value: 'installation'
					},
					{
						label: '维修服务',
						value: 'repair'
					},
					{
						label: '投诉建议',
						value: 'complaint'
					}
				],
				
				// 服务单状态选项
				serviceStatusOptions: [{
						label: '待处理',
						value: 'pending'
					},
					{
						label: '处理中',
						value: 'processing'
					},
					{
						label: '已完成',
						value: 'completed'
					},
					{
						label: '已关闭',
						value: 'closed'
					},
					{
						label: '已取消',
						value: 'cancelled'
					}
				],
				
				// 统计标题（分开存储）
				summaryTitle: {
					service: [ '汇总统计', '明细统计'],
					task: ['任务完成统计', '任务创建统计']
				},
				
				// 统计数据
				summaryStats: {
					taskComplete: [{
						label: '总积分',
						value: 300
					}],
					taskCreate: [{
						label: '总积分',
						value: 1000
					}],
					service: [{
						label: '总积分',
						value: 45
					}]
				},
				
				// 表格列定义
				tableColumns: {
					task: [{
						title: '归属',
						key: 'deptName',
						width: '20%'
					},
					{
						title: '类型',
						key: 'taskType',
						width: '20%'
					},
					{
						title: '数量',
						key: 'count',
						width: '15%'
					},
					{
						title: '客户',
						key: 'companyUserName',
						width: '20%'
					},{"title": "业务员",
					"key": "doctorName",
					"width": "20%"
					},
					{
						title: '积分',
						key: 'totalPoints',
						width: '25%'
					}],
					service: [{
							title: '项目归属',
							key: 'serviceNo',
							width: '25%'
						},
						{
							title: '类型',
							key: 'serviceType',
							width: '20%'
						},
						{
							title: '数量',
							key: 'customerName',
							width: '20%'
						},
						{
							title: '客户',
							key: 'statusText',
							width: '20%',
							slot: true
						},
						{
							title: '业务员',
							key: 'createTime',
							width: '25%'
						},
						{
							title: '积分',
							key: 'createTime',
							width: '25%'
						}
					]
				},
				
				// 表格数据
			tableData: {
				taskComplete: [
				],
				taskCreate: [
				],
				service: [{
					serviceNo: '学术研究',
					serviceType: '技术咨询',
					customerName: '李*华',
					status: 'completed',
					statusText: '已完成',
					createTime: '2025-12-25'
				},
				{
					serviceNo: '学术研究',
					serviceType: '售后服务',
					customerName: '张*伟',
					status: 'processing',
					statusText: '处理中',
					createTime: '2025-12-24'
				},
				{
					serviceNo: '学术研究',
					serviceType: '安装服务',
					customerName: '王*芳',
					status: 'pending',
					statusText: '待处理',
					createTime: '2025-12-23'
				}
				]
			},
			taskTypeDict: [],//任务类型
			taskStatusDict: [],//任务状态
			
			// 加载状态
				loading: {
					task: false,
					service: false
				}
			}
		},
		computed: {
			dateRangeText() {
				return `${this.dateRange.startDate} 至 ${this.dateRange.endDate}`
			}
		},
		watch: {
			showFilter(newVal) {
				if (newVal) {
					// 打开弹窗时，同步临时选择值
					if (this.currentStatType === 'task') {
						this.tempSelectedTaskType = [...this.selectedTaskType]
						this.tempSelectedTaskStatus = [...this.selectedTaskStatus]
					} else {
						this.tempSelectedServiceType = this.selectedServiceType
						this.tempSelectedServiceStatus = this.selectedServiceStatus
					}
				}
			},
			currentStatType(newVal) {
				// 切换统计类型时，重置筛选条件（可选）
				this.resetFilters()
				// 重新加载数据
				this.loadData()
			}
		},
		onLoad: async function(options) {
			try {
				this.taskTypeDict = await utils.getDicts("task_type");//任务类型
				this.taskStatusDict = await utils.getDicts("task_status");//任务状态
			} catch (e) {
				console.log('获取字典数据失败:', e)
			}
		this.loadData()
			
		},
		onReachBottom() {
			this.loadMore(this.currentStatType)
		},
		methods: {
			// 切换统计类型
			switchStatType(type) {
				if (this.currentStatType !== type) {
					this.currentStatType = type
				}
			},
			
			goBack() {
				uni.navigateBack()
			},
			
			onStartDateChange(e) {
				this.tempDateRange.startDate = e.detail.value
			},
			
			onEndDateChange(e) {
				this.tempDateRange.endDate = e.detail.value
			},
			
			confirmDateRange() {
				if (!this.tempDateRange.startDate || !this.tempDateRange.endDate) {
					uni.showToast({
						icon: 'none',
						title: '请选择完整的日期范围'
					})
					return
				}
				if (new Date(this.tempDateRange.startDate) > new Date(this.tempDateRange.endDate)) {
					uni.showToast({
						icon: 'none',
						title: '开始日期不能大于结束日期'
					})
					return
				}
				this.dateRange = {
					...this.tempDateRange
				}
				this.showDatePicker = false
				this.loadData()
			},
			
			closeFilter() {
				// 关闭弹窗时，恢复临时选择值为当前选择值
				if (this.currentStatType === 'task') {
					this.tempSelectedTaskType = this.selectedTaskType
					this.tempSelectedTaskStatus = this.selectedTaskStatus
				} else {
					this.tempSelectedServiceType = this.selectedServiceType
					this.tempSelectedServiceStatus = this.selectedServiceStatus
				}
				this.showFilter = false
			},
			
			// 任务筛选相关方法
			toggleTaskType(value) {
				const index = this.tempSelectedTaskType.indexOf(value);
				if (index > -1) {
					// 已选中，取消选择
					this.tempSelectedTaskType.splice(index, 1);
				} else {
					// 未选中，添加选择
					this.tempSelectedTaskType.push(value);
				}
			},
			
			toggleTaskStatus(value) {
				const index = this.tempSelectedTaskStatus.indexOf(value);
				if (index > -1) {
					// 已选中，取消选择
					this.tempSelectedTaskStatus.splice(index, 1);
				} else {
					// 未选中，添加选择
					this.tempSelectedTaskStatus.push(value);
				}
			},
			
			// 服务单筛选相关方法
			selectServiceType(value) {
				if (this.tempSelectedServiceType === value) {
					this.tempSelectedServiceType = ''
				} else {
					this.tempSelectedServiceType = value
				}
			},
			
			selectServiceStatus(value) {
				if (this.tempSelectedServiceStatus === value) {
					this.tempSelectedServiceStatus = ''
				} else {
					this.tempSelectedServiceStatus = value
				}
			},
			
			resetFilters() {
				if (this.currentStatType === 'task') {
					this.tempSelectedTaskType = []
					this.tempSelectedTaskStatus = []
				} else {
					this.tempSelectedServiceType = 'all'
					this.tempSelectedServiceStatus = ''
				}
			},
			
			confirmFilters() {
				if (this.currentStatType === 'task') {
					this.selectedTaskType = [...this.tempSelectedTaskType]
					this.selectedTaskStatus = [...this.tempSelectedTaskStatus]
				} else {
					this.selectedServiceType = this.tempSelectedServiceType
					this.selectedServiceStatus = this.tempSelectedServiceStatus
				}
				this.showFilter = false
				this.loadData()
			},
			
			async loadData() {
				try {
					uni.showLoading({
						title: '加载中...'
					})
					
					// 根据当前统计类型加载数据
					if (this.currentStatType === 'task') {
						// 加载任务统计数据
						// 获取用户信息
						const userInfo = uni.getStorageSync('userInfo')
						
						// 构建请求参数
						const params = {
							companyId: userInfo.companyId || 1,
							pageNum: 1,
							pageSize: 10
						}
						
						// 如果有选中的任务类型，添加到请求参数中
						if (this.selectedTaskType && this.selectedTaskType.length > 0) {
							params.taskTypes = this.selectedTaskType.join(',')
						}
						
						// 如果有选中的任务状态，添加到请求参数中
						if (this.selectedTaskStatus && this.selectedTaskStatus.length > 0) {
							params.taskStatuses = this.selectedTaskStatus.join(',')
						}
						
						// 调用任务完成统计接口
						const completeStatsRes = await getTaskCompleteStats(params)
						// 调用任务创建统计接口
						const createStatsRes = await getTaskCreateStats(params)
						
						// 处理返回的数据
					if (completeStatsRes.code === 200) {
						// 更新任务完成统计数据
						console.log('任务完成统计数据:', completeStatsRes)
						// 更新表格数据
						this.tableData.taskComplete = completeStatsRes.rows.map(item => ({
							...item,
							taskType: item.taskType || '无类型'
						}))
						// 更新汇总统计
						this.summaryStats.taskComplete = [{
							label: '总任务数',
							value: completeStatsRes.total || 0
						}, {
							label: '总积分',
							value: completeStatsRes.rows.reduce((sum, item) => sum + (item.totalPoints || 0), 0)
						}]
					}
					
					if (createStatsRes.code === 200) {
						// 更新任务创建统计数据
						console.log('任务创建统计数据:', createStatsRes)
						// 更新表格数据
						this.tableData.taskCreate = createStatsRes.rows.map(item => ({
							...item,
							taskType: item.taskType || '无类型'
						}))
						// 更新汇总统计
						this.summaryStats.taskCreate = [{
							label: '总任务数',
							value: createStatsRes.total || 0
						}, {
							label: '总积分',
							value: createStatsRes.rows.reduce((sum, item) => sum + (item.totalPoints || 0), 0)
						}]
					}
						
						uni.hideLoading()
						
					} else {
						// 加载服务单统计数据
						// 模拟数据
						setTimeout(() => {
							uni.hideLoading()
							// 这里可以更新数据
						}, 500)
					}
					
				} catch (e) {
					uni.hideLoading()
					console.error('加载数据失败', e)
				}
			},
			
			async loadMore(type) {
				// 根据类型加载更多数据
				this.loading[type] = true
				// 模拟加载更多
				setTimeout(() => {
					if (type === 'task') {
						// 添加更多任务数据
						this.tableData.task.push(...this.getMoreTaskData())
					} else {
						// 添加更多服务单数据
						this.tableData.service.push(...this.getMoreServiceData())
					}
					this.loading[type] = false
				}, 1000)
			},
			
			getMoreTaskData() {
				// 返回更多任务数据
				return [{
						taskType: '更多任务',
						points: '30',
						applicant: '测试*员',
						status: 'completed',
						statusText: '已完成',
						receiveTime: '2025-09-26'
					},
					{
						taskType: '更多任务2',
						points: '50',
						applicant: '测试*员2',
						status: 'pendingReview',
						statusText: '待审核',
						receiveTime: '2025-09-27'
					}
				]
			},
			
			getMoreServiceData() {
				// 返回更多服务单数据
				return [{
					serviceNo: 'FW20251222004',
					serviceType: '维修服务',
					customerName: '赵*强',
					status: 'closed',
					statusText: '已关闭',
					createTime: '2025-12-22'
				},
				{
					serviceNo: 'FW20251221005',
					serviceType: '投诉建议',
					customerName: '孙*丽',
					status: 'cancelled',
					statusText: '已取消',
					createTime: '2025-12-21'
				}
				]
			},
			
			// 根据taskType获取任务类型名称
			getTaskTypeName(taskType) {
				// 任务类型映射
				const taskTypeMap = {
					'1': '医生坐诊',
					'2': '科普讲座',
					'3': '学术讲座',
					'4': '科普文章',
					'5': '科普短视频',
					'6': '科普长视频',
					'7': '空中课堂',
					'8': '用药调研',
					'9': '问卷调研',
					'10': '社群咨询',
					'11': '健康问答'
				}
				return taskTypeMap[taskType] || '未知类型'
			}
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		min-height: 100vh;
		background: #f7f8fa;
		padding-bottom: 20rpx;
	}
	
	/* 统计类型切换样式 */
	.stat-tabs {
		display: flex;
		background: #fff;
		padding: 24rpx;
		
		.stat-tab {
			flex: 1;
			text-align: center;
			padding: 20rpx 0;
			font-size: 32rpx;
			color: #999;
			position: relative;
			
			&.active {
				color: #333333;
				font-weight: bold;
				
				&::after {
					content: '';
					position: absolute;
					bottom: 0;
					left: 50%;
					transform: translateX(-50%);
					width: 60rpx;
					height: 6rpx;
					background: #388BFF;
					border-radius: 3rpx;
				}
			}
		}
	}
	
	.date-filter-bar {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 24rpx;
		background: #fff;
		
		.date-range {
			display: flex;
			align-items: center;
			gap: 8rpx;
			
			.date-text {
				font-family: PingFang SC, PingFang SC;
				font-weight: 500;
				font-size: 28rpx;
				color: #333333;
			}
			
			.arrow-down {
				font-size: 20rpx;
				color: #333333;
			}
		}
		
		.filter-btn {
			display: flex;
			align-items: center;
			gap: 8rpx;
			font-size: 28rpx;
			color: #999999;
		}
	}
	
	.w32 {
		width: 32rpx;
	}
	
	.h32 {
		height: 32rpx;
	}
	
	.mb16 {
		margin-bottom: 16rpx;
	}
	
	.status-tag {
		padding: 4rpx 12rpx;
		border-radius: 4rpx;
		font-size: 24rpx;
		
		&.uncompleted,
		&.pending {
			background: #FFF3E0;
			color: #FF9800;
		}
		
		&.completed {
			background: #E8F5E9;
			color: #4CAF50;
		}
		
		&.pendingReview {
			background: #E3F2FD;
			color: #2196F3;
		}
		
		&.rejected {
			background: #FFEBEE;
			color: #F44336;
		}
		
		&.processing {
			background: #E3F2FD;
			color: #2196F3;
		}
		
		&.closed,
		&.cancelled {
			background: #F5F5F5;
			color: #9E9E9E;
		}
	}
	
	/* 日期选择弹窗样式 */
	.date-picker-popup {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(0, 0, 0, 0.5);
		z-index: 999;
		display: flex;
		align-items: flex-end;
	}
	
	.date-picker-content {
		width: 100%;
		background: #fff;
		border-radius: 24rpx 24rpx 0 0;
		
		.picker-header {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 24rpx;
			
			.picker-cancel {
				font-size: 30rpx;
				color: #666;
			}
			
			.picker-title {
				font-size: 32rpx;
				font-weight: bold;
				color: #333;
			}
			
			.picker-confirm {
				font-size: 30rpx;
				color: #388BFF;
			}
		}
		
		.picker-body {
			padding: 24rpx;
			
			.date-item {
				display: flex;
				align-items: center;
				justify-content: space-between;
				padding: 24rpx 0;
				&:last-child {
					border-bottom: none;
				}
				
				.date-label {
					font-size: 30rpx;
					color: #333;
				}
				
				.date-value {
					font-size: 30rpx;
					color: #388BFF;
				}
			}
		}
	}
	
	/* 筛选弹窗样式 */
	.filter-popup {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(0, 0, 0, 0.5);
		z-index: 999;
		display: flex;
		align-items: flex-end;
	}
	
	.filter-content {
		width: 100%;
		background: #fff;
		border-radius: 24rpx 24rpx 0 0;
		padding: 24rpx;
		max-height: 80vh;
		overflow-y: auto;
		
		.filter-header {
			display: flex;
			align-items: center;
			justify-content: center;
			margin-bottom: 32rpx;
			position: relative;
			
			.filter-title {
				font-size: 32rpx;
				font-weight: bold;
				color: #333;
			}
			
			.filter-close-btn {
				width: 44rpx;
				height: 44rpx;
				position: absolute;
				right: 0;
			}
		}
		
		.filter-group {
			margin-bottom: 40rpx;
			
			.group-label {
				font-size: 28rpx;
				font-weight: bold;
				color: #333;
				margin-bottom: 20rpx;
			}
			
			.filter-tags {
				display: flex;
				flex-wrap: wrap;
				gap: 20rpx;
				
				.filter-tag {
					padding: 12rpx 24rpx;
					font-size: 28rpx;
					color: #333;
					background: #F7F8FA;
					border-radius: 70rpx;
					
					&.active {
						background: rgba(56, 139, 255, 0.15);
						color: #388BFF;
					}
				}
			}
		}
		
		.filter-actions {
			display: flex;
			gap: 24rpx;
			margin-top: 40rpx;
			padding-top: 24rpx;
			border-top: 1rpx solid #f0f0f0;
			
			.reset-btn,
			.confirm-btn {
				flex: 1;
				height: 88rpx;
				line-height: 88rpx;
				text-align: center;
				border-radius: 200rpx;
				font-size: 28rpx;
			}
			
			.reset-btn {
				background: #fff;
				color: #388BFF;
				border: 2rpx solid #388BFF;
			}
			
			.confirm-btn {
				background: #388BFF;
				color: #fff;
			}
		}
	}
</style>