﻿<template>
	<el-dialog 
		:title="dialogTitle" 
		:close-on-click-modal="false" 
		:visible.sync="visible" 
		class="NCC-dialog NCC-dialog_center" 
		lock-scroll 
		width="900px"
		:before-close="handleClose">
		
		<!-- 基本信息 -->
		<el-form ref="basicForm" :model="dataForm" size="small" label-width="100px" label-position="right" :disabled="!!isDetail" :rules="rules">
			<el-row :gutter="15">
				<el-col :span="12">
					<el-form-item label="月份" prop="yf">
						<el-date-picker
							v-model="monthValue"
							type="month"
							placeholder="请选择月份"
							format="yyyyMM"
							value-format="yyyyMM"
							:style='{"width":"100%"}'
							@change="onMonthChange">
						</el-date-picker>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="门店" prop="md">
						<el-select 
							v-model="dataForm.md" 
							placeholder="请选择门店" 
							clearable 
							:style='{"width":"100%"}' 
							@change="onStoreChange"
							filterable>
							<el-option
								v-for="store in storeList"
								:key="store.id"
								:label="store.name"
								:value="store.id">
							</el-option>
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="24">
					<el-form-item label="金三角" prop="jsj">
						<el-input 
							v-model="dataForm.jsj" 
							placeholder="请输入金三角名称" 
							clearable 
							:style='{"width":"100%"}' 
							maxlength="50">
						</el-input>
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
		
		<!-- 成员管理 -->
		<div class="member-section">
			<div class="section-title">
				<span>{{ isDetail ? '成员信息' : '成员管理' }}</span>
				<div class="member-actions" v-if="!isDetail">
					<el-button type="primary" icon="el-icon-plus" @click="addMember" size="small">添加成员</el-button>
					<el-button type="warning" icon="el-icon-refresh" @click="refreshMembers" size="small">刷新</el-button>
					<span class="member-count">共 {{ members.length }} 人</span>
				</div>
				<span class="member-count" v-if="isDetail">共 {{ members.length }} 人</span>
			</div>
			
			<el-table :data="members" border style="width: 100%; margin-top: 10px;" :header-cell-style="{ background: '#f5f7fa', color: '#606266', fontWeight: 'bold' }">
				<el-table-column type="index" label="序号" min-width="80" align="center" />
				<el-table-column prop="userName" label="姓名" min-width="120">
					<template slot-scope="scope">
						<el-input v-if="!isDetail" v-model="scope.row.userName" size="small" placeholder="请输入姓名" />
						<div v-else class="member-name">
							<i class="el-icon-user"></i>
							<span>{{ scope.row.userName }}</span>
						</div>
					</template>
				</el-table-column>
				<el-table-column prop="userId" label="用户" min-width="180">
					<template slot-scope="scope">
						<el-select 
							v-if="!isDetail"
							v-model="scope.row.userId" 
							placeholder="选择用户" 
							size="small" 
							@change="onUserChange(scope.$index, $event)"
							filterable
							style="width: 100%;">
							<el-option
								v-for="user in availableUsers"
								:key="user.id"
								:label="user.name"
								:value="user.id">
							</el-option>
						</el-select>
						<div v-else class="user-info">
							<i class="el-icon-user-solid"></i>
							<span>{{ scope.row.userId }}</span>
						</div>
					</template>
				</el-table-column>
				<el-table-column label="是否顾问" min-width="120" align="center">
					<template slot-scope="scope">
						<el-radio-group v-if="!isDetail" v-model="scope.row.isLeader" size="small">
							<el-radio :label="1">是</el-radio>
							<el-radio :label="0">否</el-radio>
						</el-radio-group>
						<el-tag v-else :type="scope.row.isLeader === 1 ? 'success' : 'info'" size="small" effect="dark">
							<i class="el-icon-star-on" v-if="scope.row.isLeader === 1"></i>
							<i class="el-icon-star-off" v-else></i>
							{{ scope.row.isLeader === 1 ? '是' : '否' }}
						</el-tag>
					</template>
				</el-table-column>
				<el-table-column label="排序" min-width="100" align="center">
					<template slot-scope="scope">
						<el-input-number 
							v-if="!isDetail"
							v-model="scope.row.sortOrder" 
							:min="1" 
							:max="999" 
							size="small"
							style="width: 100%;" />
						<el-tag v-else type="info" size="small">{{ scope.row.sortOrder }}</el-tag>
					</template>
				</el-table-column>
				<el-table-column prop="status" label="状态" min-width="100" align="center" v-if="isDetail">
					<template slot-scope="scope">
						<el-tag :type="scope.row.status === 'ACTIVE' ? 'success' : 'info'" size="small" effect="dark">
							<i class="el-icon-check" v-if="scope.row.status === 'ACTIVE'"></i>
							<i class="el-icon-close" v-else></i>
							{{ scope.row.status === 'ACTIVE' ? '活跃' : '非活跃' }}
						</el-tag>
					</template>
				</el-table-column>
				<el-table-column label="操作" min-width="120" align="center" v-if="!isDetail">
					<template slot-scope="scope">
						<el-button type="danger" icon="el-icon-delete" @click="removeMember(scope.$index)" size="small" plain>删除</el-button>
					</template>
				</el-table-column>
			</el-table>
		</div>
		
		<span slot="footer" class="dialog-footer">
			<el-button @click="handleClose">取 消</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'
	
	export default {
		components: {},
		props: [],
		data() {
			return {
				loading: false,
				visible: false,
				isDetail: false,
				isManageMembers: false,
				dataForm: {
					id: '',
					yf: '',
					md: '',
					jsj: ''
				},
				members: [],
				storeList: [],
				availableUsers: [],
				monthValue: null, // 月份选择器的值
				rules: {
					yf: [
						{ required: true, message: '月份不能为空', trigger: 'blur' },
						{ pattern: /^\d{6}$/, message: '月份格式必须为yyyyMM', trigger: 'blur' }
					],
					md: [
						{ required: true, message: '门店不能为空', trigger: 'change' }
					],
					jsj: [
						{ required: true, message: '金三角名称不能为空', trigger: 'blur' }
					]
				}
			}
		},
		computed: {
			dialogTitle() {
				if (this.isDetail) return '金三角详情'
				if (this.isManageMembers) return '管理成员'
				return this.dataForm.id ? '编辑金三角' : '新建金三角'
			}
		},
		watch: {},
		created() {},
		mounted() {},
		methods: {
			goBack() {
				this.$emit('refresh')
			},
			init(id, isDetail, isManageMembers) {
				this.dataForm.id = id || 0
				this.visible = true
				this.isDetail = isDetail || false
				this.isManageMembers = isManageMembers || false
				this.members = []
				
				this.$nextTick(() => {
					this.$refs['basicForm'] && this.$refs['basicForm'].resetFields()
					this.loadStoreList()
					if (this.dataForm.id) {
						this.loadData()
					}
				})
			},
			loadData() {
				// 加载基本信息
				request({
					url: '/api/Extend/LqYcsdJsj/' + this.dataForm.id,
					method: 'get'
				}).then(res => {
					this.dataForm = res.data
					// 同步月份选择器的值
					this.monthValue = this.dataForm.yf
					// 门店变化后更新可用用户（不清空成员）
					if (this.dataForm.md) {
						this.loadUsersByStore(this.dataForm.md)
					}
				})
				
				// 加载成员信息
				request({
					url: '/api/Extend/LqYcsdJsj/' + this.dataForm.id + '/detail',
					method: 'get'
				}).then(res => {
					this.members = res.data.members || []
				})
			},
			loadStoreList() {
				// 加载门店列表
				request({
					url: '/api/Extend/LqMdxx/Selector',
					method: 'GET'
				}).then(res => {
					this.storeList = res.data.list.map(item => ({
						id: item.id,
						name: item.fullName
					}))
				}).catch(() => {
					this.storeList = []
				})
			},
			onStoreChange() {
				// 门店变化时更新可用用户
				if (this.dataForm.md) {
					this.loadUsersByStore(this.dataForm.md)
				} else {
					this.availableUsers = []
				}
				// 清空已选择的成员
				this.members = []
			},
			loadUsersByStore(storeId) {
				// 根据门店ID加载用户
				request({
					url: '/api/Extend/User/Selector',
					method: 'GET',
					params: {
						mdid: storeId
					}
				}).then(res => {
					this.availableUsers = res.data.map(item => ({
						id: item.id,
						name: item.realName,
						storeId: item.mdid
					}))
				}).catch(() => {
					this.availableUsers = []
				})
			},
			onUserChange(index, userId) {
				// 用户选择变化时自动填充姓名
				const selectedUser = this.availableUsers.find(user => user.id === userId)
				if (selectedUser) {
					this.$set(this.members[index], 'userName', selectedUser.name)
				}
			},
			onMonthChange(value) {
				// 月份选择器变化时更新dataForm.yf
				this.dataForm.yf = value
			},
			dataFormSubmit() {
				this.$refs['basicForm'].validate((valid) => {
					if (valid) {
						// 验证多人战队必须有顾问
						if (this.members.length >= 2) {
							const hasLeader = this.members.some(m => m.isLeader === 1)
							if (!hasLeader) {
								this.$message.error('两人或两人以上的战队必须有一个顾问')
								this.activeTab = 'members'
								return
							}
						}
						
						const submitData = {
							...this.dataForm,
							members: this.members
						}
						
						if (!this.dataForm.id) {
							// 新建
							request({
								url: `/api/Extend/LqYcsdJsj`,
								method: 'post',
								data: submitData,
							}).then((res) => {
								this.$message({
									message: res.msg,
									type: 'success',
									duration: 1000,
									onClose: () => {
										this.visible = false
										this.$emit('refresh', true)
									}
								})
							})
						} else {
							// 编辑
							request({
								url: '/api/Extend/LqYcsdJsj/' + this.dataForm.id,
								method: 'PUT',
								data: submitData
							}).then((res) => {
								this.$message({
									message: res.msg,
									type: 'success',
									duration: 1000,
									onClose: () => {
										this.visible = false
										this.$emit('refresh', true)
									}
								})
							})
						}
					}
				})
			},
			// 成员管理方法
			addMember() {
				if (!this.dataForm.md) {
					this.$message.warning('请先选择门店')
					return
				}
				this.members.push({
					userId: '',
					userName: '',
					isLeader: 0,
					sortOrder: this.members.length + 1
				})
			},
			removeMember(index) {
				this.$confirm('确定要删除这个成员吗？', '提示', {
					type: 'warning'
				}).then(() => {
					this.members.splice(index, 1)
					// 重新排序
					this.members.forEach((member, index) => {
						member.sortOrder = index + 1
					})
				})
			},
			refreshMembers() {
				if (this.dataForm.id) {
					this.loadData()
				}
			},
			handleClose() {
				this.visible = false
			}
		}
	}
</script>

<style scoped>
/* 基本信息区域 */
.el-form {
	background: #f8f9fa;
	padding: 20px;
	border-radius: 8px;
	margin-bottom: 20px;
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
	border: 1px solid #e9ecef;
}

.el-form-item__label {
	font-weight: 600;
	color: #2c3e50;
}

/* 成员管理区域 */
.member-section {
	margin-top: 20px;
	padding: 20px;
	border: 1px solid #e1e8ed;
	border-radius: 8px;
	background: #fff;
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.section-title {
	display: flex;
	align-items: center;
	justify-content: space-between;
	margin-bottom: 16px;
	font-size: 18px;
	font-weight: 700;
	color: #2c3e50;
	border-bottom: 2px solid #3498db;
	padding-bottom: 8px;
}

.member-actions {
	display: flex;
	align-items: center;
	gap: 12px;
}

.member-count {
	color: #7f8c8d;
	font-size: 14px;
	font-weight: 500;
	background: #ecf0f1;
	padding: 4px 12px;
	border-radius: 20px;
}

/* 表格样式 */
.el-table {
	margin-top: 16px;
	border-radius: 8px;
	overflow: hidden;
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.el-table th {
	background: #409EFF !important;
	color: #fff !important;
	font-weight: 600;
}

.el-table tbody tr:hover > td {
	background-color: #f8f9fa !important;
}

/* 成员信息显示 */
.member-name, .user-info {
	display: flex;
	align-items: center;
	gap: 8px;
	color: #2c3e50;
	font-weight: 500;
}

.member-name i, .user-info i {
	color: #3498db;
	font-size: 16px;
}

/* 标签样式 */
.el-tag {
	border-radius: 16px;
	font-weight: 500;
	padding: 4px 12px;
}

.el-tag i {
	margin-right: 4px;
}

/* 按钮样式 */
.el-button {
	border-radius: 6px;
	font-weight: 500;
	transition: all 0.3s ease;
}

.el-button:hover {
	transform: translateY(-1px);
	box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

/* 输入框样式 */
.el-input, .el-select, .el-input-number {
	border-radius: 6px;
}

.el-input__inner, .el-textarea__inner {
	border-radius: 6px;
	transition: all 0.3s ease;
}

.el-input__inner:focus, .el-textarea__inner:focus {
	border-color: #3498db;
	box-shadow: 0 0 0 2px rgba(52, 152, 219, 0.2);
}

/* 对话框样式 */
.NCC-dialog {
	border-radius: 8px;
	overflow: hidden;
}

.el-dialog__header {
	background: #409EFF;
	color: #fff;
	padding: 20px;
}

.el-dialog__title {
	font-weight: 600;
	font-size: 18px;
}

.el-dialog__body {
	padding: 30px;
	background: #f8f9fa;
}

.el-dialog__footer {
	background: #fff;
	padding: 20px 30px;
	border-top: 1px solid #e9ecef;
}

/* 响应式设计 */
@media (max-width: 768px) {
	.member-actions {
		flex-direction: column;
		align-items: flex-start;
		gap: 8px;
	}
	
	.action-buttons {
		flex-direction: column;
		width: 100%;
	}
	
	.action-buttons .el-button {
		width: 100%;
	}
}

/* 动画效果 */
.member-section {
	animation: fadeInUp 0.5s ease-out;
}

@keyframes fadeInUp {
	from {
		opacity: 0;
		transform: translateY(20px);
	}
	to {
		opacity: 1;
		transform: translateY(0);
	}
}

/* 滚动条样式 */
.el-table__body-wrapper::-webkit-scrollbar {
	width: 6px;
	height: 6px;
}

.el-table__body-wrapper::-webkit-scrollbar-track {
	background: #f1f1f1;
	border-radius: 3px;
}

.el-table__body-wrapper::-webkit-scrollbar-thumb {
	background: #c1c1c1;
	border-radius: 3px;
}

.el-table__body-wrapper::-webkit-scrollbar-thumb:hover {
	background: #a8a8a8;
}
</style>