<template>
	<el-dialog :title="!dataForm.id ? '新增' : '修改'" :close-on-click-modal="false" :visible.sync="visible" width="800px">
		<el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="120px">
			<el-row :gutter="20">
				<el-col :span="12">
					<el-form-item label="活动名称" prop="eventName">
						<el-input v-model="dataForm.eventName" placeholder="请输入活动名称" />
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="活动编号" prop="eventNumber">
						<el-input v-model="dataForm.eventNumber" placeholder="请输入活动编号" />
					</el-form-item>
				</el-col>
			</el-row>
			<el-row :gutter="20">
				<el-col :span="12">
					<el-form-item label="活动负责人" prop="eventCoordinator">
						<user-select v-model="dataForm.eventCoordinator" placeholder="请选择活动负责人" clearable></user-select>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="活动类型" prop="eventType">
						<el-select v-model="dataForm.eventType" placeholder="请选择活动类型" clearable style="width: 100%">
							<el-option v-for="item in eventTypeOptions" :key="item.id" :label="item.fullName" :value="item.id"></el-option>
						</el-select>
					</el-form-item>
				</el-col>
			</el-row>
			<el-row :gutter="20">
				<el-col :span="12">
					<el-form-item label="开始时间" prop="startTime">
						<el-date-picker
							v-model="dataForm.startTime"
							type="datetime"
							placeholder="选择开始时间"
							value-format="yyyy-MM-dd HH:mm:ss"
							style="width: 100%"
						/>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="结束时间" prop="endTime">
						<el-date-picker
							v-model="dataForm.endTime"
							type="datetime"
							placeholder="选择结束时间"
							value-format="yyyy-MM-dd HH:mm:ss"
							style="width: 100%"
						/>
					</el-form-item>
				</el-col>
			</el-row>
			
			<!-- 成员管理 -->
			<el-divider content-position="left">活动成员</el-divider>
			<div class="member-management">
				<!-- 活动类型为3时显示批量导入 -->
				<div v-if="dataForm.eventType == '3'" class="import-section">
					<div class="import-header">
						<el-upload
							ref="upload"
							:action="uploadUrl"
							:headers="uploadHeaders"
							:data="uploadData"
							:file-list="fileList"
							:before-upload="beforeUpload"
							:on-success="handleUploadSuccess"
							:on-error="handleUploadError"
							:auto-upload="true"
							accept=".xlsx,.xls"
							:limit="1"
							:on-exceed="handleExceed"
						>
							<el-button type="primary" size="small" icon="el-icon-upload">导入Excel文件</el-button>
						</el-upload>
						<div class="import-tips">
							<!-- <el-link type="info" @click="downloadTemplate">下载模板</el-link> -->
							<span class="member-count">共 {{ dataForm.members.length }} 人</span>
						</div>
					</div>
					<!-- 导入结果显示 -->
					<div v-if="dataForm.members.length > 0 || importResult.failData.length > 0" class="import-result">
						<!-- 标签页切换 -->
						<el-tabs v-model="activeTab" type="card" style="margin-top: 10px;">
							<el-tab-pane label="成功数据" name="success">
								<template slot="label">
									<span>成功数据 <el-badge :value="dataForm.members.length" class="item" /></span>
								</template>
								<el-table :data="dataForm.members" border >
									<el-table-column prop="userId" label="用户" width="150">
										<template slot-scope="scope">
											<user-select v-model="scope.row.userId" placeholder="请选择用户" clearable size="small"></user-select>
										</template>
									</el-table-column>
									<el-table-column prop="depId" label="部门" width="150">
										<template slot-scope="scope">
											<el-select v-model="scope.row.depId" placeholder="请选择部门" clearable filterable size="small" style="width: 100%">
												<el-option v-for="item in departmentOptions" :key="item.id" :label="item.fullName" :value="item.id"></el-option>
											</el-select>
										</template>
									</el-table-column>
									<el-table-column prop="storeId" label="门店" width="150">
										<template slot-scope="scope">
											<el-select v-model="scope.row.storeId" placeholder="请选择门店" clearable filterable size="small" style="width: 100%">
												<el-option v-for="item in storeOptions" :key="item.id" :label="item.fullName" :value="item.id"></el-option>
											</el-select>
										</template>
									</el-table-column>
									<el-table-column prop="teamName" label="团队名称" min-width="180">
										<template slot-scope="scope">
											<el-input v-model="scope.row.teamName" placeholder="请输入团队名称" size="small" />
										</template>
									</el-table-column>
									<el-table-column prop="targetCount" label="目标张数" width="120" align="center">
										<template slot-scope="scope">
											<el-input-number v-model="scope.row.targetCount" :min="1" :max="999" size="small" style="width: 100%" />
										</template>
									</el-table-column>
									<el-table-column label="操作" width="80" align="center">
										<template slot-scope="scope">
											<el-button type="text" size="small" @click="removeMember(scope.$index)">删除</el-button>
										</template>
									</el-table-column>
								</el-table>
							</el-tab-pane>
							<el-tab-pane label="失败数据" name="fail" v-if="importResult.failData.length > 0">
								<template slot="label">
									<span>失败数据 <el-badge :value="importResult.failCount" class="item" type="danger" /></span>
								</template>
								<el-table :data="importResult.failData" border>
									<el-table-column prop="RowNumber" label="行号" width="80" align="center" />
									<el-table-column prop="Name" label="姓名" width="120" />
									<el-table-column prop="MobilePhone" label="手机号" width="130" />
									<el-table-column prop="TeamName" label="团队名称" width="150" />
									<el-table-column prop="StoreName" label="门店" width="150" />
									<el-table-column prop="TargetCount" label="目标数量" width="100" align="center" />
									<el-table-column prop="ErrorMessage" label="错误信息" min-width="200" show-overflow-tooltip />
								</el-table>
							</el-tab-pane>
						</el-tabs>
					</div>
				</div>
				
				<!-- 其他活动类型显示逐条添加 -->
				<div v-else>
					<div class="member-header">
						<el-button type="primary" size="small" icon="el-icon-plus" @click="addMember">添加成员</el-button>
						<span class="member-count">共 {{ dataForm.members.length }} 人</span>
					</div>
					<el-table :data="dataForm.members" border style="margin-top: 10px;">
						<el-table-column prop="userId" label="用户" width="150">
							<template slot-scope="scope">
								<user-select v-model="scope.row.userId" placeholder="请选择用户" clearable size="small"></user-select>
							</template>
						</el-table-column>
						<el-table-column prop="depId" label="部门" width="150">
							<template slot-scope="scope">
								<el-select v-model="scope.row.depId" placeholder="请选择部门" clearable filterable size="small" style="width: 100%">
									<el-option v-for="item in departmentOptions" :key="item.id" :label="item.fullName" :value="item.id"></el-option>
								</el-select>
							</template>
						</el-table-column>
						<el-table-column prop="storeId" label="门店" width="150">
							<template slot-scope="scope">
								<el-select v-model="scope.row.storeId" placeholder="请选择门店" clearable filterable size="small" style="width: 100%">
									<el-option v-for="item in storeOptions" :key="item.id" :label="item.fullName" :value="item.id"></el-option>
								</el-select>
							</template>
						</el-table-column>
						<el-table-column prop="teamName" label="团队名称" min-width="180">
							<template slot-scope="scope">
								<el-input v-model="scope.row.teamName" placeholder="请输入团队名称" size="small" />
							</template>
						</el-table-column>
						<el-table-column prop="targetCount" label="目标张数" width="120" align="center">
							<template slot-scope="scope">
								<el-input-number v-model="scope.row.targetCount" :min="1" :max="999" size="small" style="width: 100%" />
							</template>
						</el-table-column>
						<el-table-column label="操作" width="80" align="center">
							<template slot-scope="scope">
								<el-button type="text" size="small" @click="removeMember(scope.$index)">删除</el-button>
							</template>
						</el-table-column>
					</el-table>
				</div>
			</div>
		</el-form>
		<span slot="footer" class="dialog-footer">
			<el-button @click="visible = false">取消</el-button>
			<el-button type="primary" @click="dataFormSubmit()">确定</el-button>
		</span>
	</el-dialog>
</template>

<script>
import request from '@/utils/request'
import { getLqEventInfo, createLqEvent, updateLqEvent } from '@/api/extend/lqevent'
import { getStoreSelector } from '@/api/extend/store'

export default {
	name: 'LqEventForm',
	data() {
		return {
			visible: false,
			dataForm: {
				id: '',
				eventName: '',
				eventNumber: '',
				eventCoordinator: '',
				eventType: '',
				startTime: '',
				endTime: '',
				members: []
			},
			memberCount: 0,
			// 选择器选项数据
			departmentOptions: [],
			storeOptions: [],
			eventTypeOptions: [],
			// 文件上传相关
			uploadUrl: 'http://lvqian.antissoft.com/api/Extend/lqevent/import-users',
			uploadHeaders: {
				'Authorization': this.$store.getters.token
			},
			uploadData: {
				eventId: ''
			},
			fileList: [],
			// 导入结果显示
			activeTab: 'success',
			importResult: {
				successData: [],
				failData: [],
				successCount: 0,
				failCount: 0
			},
			dataRule: {
				eventName: [
					{ required: true, message: '活动名称不能为空', trigger: 'blur' }
				],
				eventNumber: [
					{ required: true, message: '活动编号不能为空', trigger: 'blur' }
				],
				eventCoordinator: [
					{ required: true, message: '请选择活动负责人', trigger: 'change' }
				],
				eventType: [
					{ required: true, message: '请选择活动类型', trigger: 'change' }
				],
				startTime: [
					{ required: true, message: '开始时间不能为空', trigger: 'change' }
				],
				endTime: [
					{ required: true, message: '结束时间不能为空', trigger: 'change' }
				]
			}
		}
	},
	methods: {
		init(id) {
			this.dataForm.id = id || ''
			this.visible = true
			this.$nextTick(() => {
				this.$refs['dataForm'].resetFields()
				// 加载选择器数据
				this.loadSelectorData()
				if (this.dataForm.id) {
					this.getInfo()
				} else {
					this.dataForm.members = []
					this.memberCount = 0
				}
			})
		},
		// 加载选择器数据
		loadSelectorData() {
			this.getDepartmentOptions()
			this.getStoreOptions()
			this.getEventTypeOptions()
		},
		// 获取部门选项
		getDepartmentOptions() {
			request({
				url: `/api/permission/Organize/96240625-934F-490B-8AA6-0BC775B18468/Department`,
				method: 'GET',
			}).then((res) => {
				if (res.code == 200 && res.data.list.length > 0) {
					this.departmentOptions = res.data.list.map(item => ({
						fullName: item.fullName,
						id: item.id,
					}));
				} else {
					this.departmentOptions = [];
				}
			})
		},
		// 获取门店选项
		getStoreOptions() {
			getStoreSelector().then(response => {
				if (response.code === 200 && response.data) {
					this.storeOptions = response.data.list.map(item => ({
						id: item.id,
						fullName: item.fullName || item.name
					}))
				}
			}).catch(err => {
				console.error('获取门店选项失败:', err)
			})
		},
		// 获取活动类型选项
		getEventTypeOptions() {
			request({
				url: '/api/Extend/lqevent/event-types',
				method: 'GET'
			}).then(response => {
				if (response.code === 200 && response.data) {
					this.eventTypeOptions = response.data.map(item => ({
						id: item.Value,
						fullName: item.Name
					}))
				}
			}).catch(err => {
				console.error('获取活动类型选项失败:', err)
				this.eventTypeOptions = []
			})
		},
		// 获取信息
		getInfo() {
			getLqEventInfo(this.dataForm.id).then(response => {
				this.dataForm = response.data
                this.dataForm.members = response.data.Members || []
				this.memberCount = this.dataForm.members ? this.dataForm.members.length : 0
				
				// 转换时间戳为日期字符串格式
				if (this.dataForm.startTime) {
					this.dataForm.startTime = this.formatTimestamp(this.dataForm.startTime)
				}
				if (this.dataForm.endTime) {
					this.dataForm.endTime = this.formatTimestamp(this.dataForm.endTime)
				}
			})
		},
		// 时间戳转日期字符串
		formatTimestamp(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}`
		},
		// 添加成员
		addMember() {
			this.dataForm.members.push({
				id: '',
				eventId: this.dataForm.id || '',
				userId: '',
				depId: '',
				storeId: '',
				teamName: '',
				targetCount: 1
			})
			this.memberCount = this.dataForm.members.length
		},
		// 删除成员
		removeMember(index) {
			this.dataForm.members.splice(index, 1)
			this.memberCount = this.dataForm.members.length
		},
		// 文件上传前验证
		beforeUpload(file) {
			const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || 
							file.type === 'application/vnd.ms-excel'
			const isLt10M = file.size / 1024 / 1024 < 10

			if (!isExcel) {
				this.$message.error('只能上传Excel文件!')
				return false
			}
			if (!isLt10M) {
				this.$message.error('上传文件大小不能超过 10MB!')
				return false
			}
			
			// 设置活动ID
			this.uploadData.eventId = this.dataForm.id || ''
			return true
		},
		// 文件上传成功
		handleUploadSuccess(response, file, fileList) {
			if (response.code === 200) {
				console.log(JSON.stringify(response.data))
				const data = response.data
				
				// 保存导入结果数据
				this.importResult = {
					successData: data.SuccessData || [],
					failData: data.FailData || [],
					successCount: data.SuccessCount || 0,
					failCount: data.FailCount || 0
				}
				
				// 处理成功的数据
				if (data.SuccessData && data.SuccessData.length > 0) {
					// 将成功的数据添加到成员列表中
					data.SuccessData.forEach(successItem => {
						this.dataForm.members.push({
							id: successItem.Id,
							eventId: successItem.EventId,
							userId: successItem.UserId,
							depId: successItem.DepId,
							storeId: successItem.StoreId,
							teamName: successItem.TeamName,
							targetCount: successItem.TargetCount
						})
					})
				}
				
				// 更新成员数量
				this.memberCount = this.dataForm.members.length
				
				// 设置默认显示标签页
				this.activeTab = data.FailCount > 0 ? 'fail' : 'success'
				
				// 显示导入结果
				let message = `导入完成！成功：${data.SuccessCount || 0}条，失败：${data.FailCount || 0}条`
				if (data.FailCount > 0) {
					this.$message({
						message: message,
						type: 'warning',
						duration: 5000
					})
				} else {
					this.$message({
						message: message,
						type: 'success'
					})
				}
				
				// 清空文件列表
				this.fileList = []
			} else {
				this.$message.error(response.msg || '导入失败!')
			}
		},
		// 文件上传失败
		handleUploadError(err, file, fileList) {
			this.$message.error('文件上传失败，请重试!')
			console.error('上传失败:', err)
		},
		// 文件数量超出限制
		handleExceed(files, fileList) {
			this.$message.warning('只能上传一个文件，请先删除已选择的文件!')
		},
		// 下载模板
		downloadTemplate() {
			// 这里可以添加下载模板的逻辑
			this.$message.info('模板下载功能待实现')
		},
		// 表单提交
		dataFormSubmit() {
			this.$refs['dataForm'].validate((valid) => {
				if (valid) {
					// 验证时间
					if (this.dataForm.startTime && this.dataForm.endTime) {
						if (new Date(this.dataForm.startTime) >= new Date(this.dataForm.endTime)) {
							this.$message.error('结束时间必须大于开始时间')
							return
						}
					}
					
					// 验证成员信息（仅对非批量导入类型）
					if (this.dataForm.eventType !== '3') {
						for (let i = 0; i < this.dataForm.members.length; i++) {
							const member = this.dataForm.members[i]
							if (!member.userId || !member.depId || !member.storeId || !member.teamName || !member.targetCount) {
								this.$message.error(`第${i + 1}个成员信息不完整，请选择用户、部门、门店，填写团队名称和目标张数`)
								return
							}
						}
					}
					
					const data = { 
						id: this.dataForm.id,
						eventName: this.dataForm.eventName,
						eventNumber: this.dataForm.eventNumber,
						eventCoordinator: this.dataForm.eventCoordinator,
						eventType: this.dataForm.eventType,
						startTime: this.dataForm.startTime,
						endTime: this.dataForm.endTime,
						members: this.dataForm.members
					 }
					if (!data.id) {
						// 新增
						createLqEvent(data).then(() => {
							this.$message({
								message: '操作成功',
								type: 'success'
							})
							this.visible = false
							this.$emit('refreshDataList')
						})
					} else {
						// 修改
						updateLqEvent(data.id, data).then(() => {
							this.$message({
								message: '操作成功',
								type: 'success'
							})
							this.visible = false
							this.$emit('refreshDataList')
						})
					}
				}
			})
		}
	}
}
</script>

<style scoped>
.member-management {
	margin-top: 20px;
}

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

.import-section {
	margin-top: 10px;
}

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

.import-tips {
	display: flex;
	align-items: center;
	gap: 15px;
}

.member-count {
	color: #606266;
	font-size: 14px;
}

.dialog-footer {
	text-align: right;
}

/* 导入结果样式 */
.import-result {
	margin-top: 10px;
}

.import-result .el-tabs__item {
	padding: 0 15px;
}

.import-result .el-badge {
	margin-left: 5px;
}

.import-result .el-table {
	margin-top: 10px;
}
</style>
