<template>
	<!-- 任务归属选择组件 -->
	<view>
		<!-- 触发区域 -->
		<slot name="trigger" :openPicker="openPicker" :value="displayValue">
			<view class="picker-trigger" @click="openPicker">
				<view class="trigger-label">{{ label }}</view>
				<view class="trigger-value" :class="{ placeholder: !displayValue }">
					{{ displayValue || placeholder }}
				</view>
				<image class="trigger-icon" src="https://ysrw-1395926010.cos.ap-chengdu.myqcloud.com/image/icon_more.png"></image>
			</view>
		</slot>

		<!-- 选择器弹出层 -->
		<u-popup :show="visible" mode="bottom" closeable round="20" @close="closePicker" :safeAreaInsetBottom="true"
			:zIndex="1001">
			<view class="task-belonging-picker">
				<!-- 标题栏 -->
				<view class="picker-header">
					<view class="picker-title">{{ title }}</view>
					<view class="picker-close" @click="closePicker">
						<text class="close-icon">×</text>
					</view>
				</view>

				<!-- 选项卡区域 -->
				<view class="tab-container">
					<scroll-view class="tab-scroll" scroll-x :scroll-left="scrollLeft">
						<view class="tab-list">
							<view v-for="(tab, index) in tabs" :key="index" class="tab-item"
								:class="{ active: currentTab === index }" @click="switchTab(index)">
								<text class="tab-text">{{ getTabTitle(tab, index) }}</text>
								<view v-if="currentTab === index" class="tab-indicator"></view>
							</view>
						</view>
					</scroll-view>
				</view>

				<!-- 列表区域 -->
				<scroll-view class="list-container" scroll-y :scroll-top="scrollTop">
					<view class="option-list">
						<view v-for="(item, index) in currentOptions" :key="item.id || index" class="option-item"
							:class="{ 
                selected: isOptionSelected(item),
                disabled: item.disabled
              }" @click="!item.disabled && selectOption(item)">
							<view class="option-content">
								<text class="option-name">{{ item.name }}</text>
								<view v-if="hasChildren(item)" class="option-arrow">
									<text class="arrow-icon">›</text>
								</view>
							</view>
							<view v-if="isOptionSelected(item)" class="option-selected">
								<text class="selected-icon">✓</text>
							</view>
						</view>
					</view>

					<!-- 空状态 -->
					<view v-if="currentOptions.length === 0" class="empty-state">
						<image class="empty-icon" src="https://ysrw-1395926010.cos.ap-chengdu.myqcloud.com/image/empty.png"></image>
						<text class="empty-text">暂无数据</text>
					</view>
				</scroll-view>

				<!-- 确定按钮 -->
				<view class="picker-footer">
					<view class="confirm-button" @click="confirmSelection">
						{{ confirmText }}
					</view>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	export default {
		name: 'TaskBelongingPicker',

		props: {
			// 是否显示弹出层
			show: {
				type: Boolean,
				default: false
			},

			// 标题
			title: {
				type: String,
				default: '任务归属'
			},

			// 标签文本
			label: {
				type: String,
				default: '任务归属'
			},

			// 占位符
			placeholder: {
				type: String,
				default: '请选择任务归属'
			},

			// 确认按钮文本
			confirmText: {
				type: String,
				default: '确定'
			},

			// 是否必填
			required: {
				type: Boolean,
				default: true
			},

			// 初始选中的值
			value: {
				type: [Array, String],
				default: () => []
			},

			// 数据源
			data: {
				type: Array,
				default: () => []
			},

			// 最大层级
			maxLevel: {
				type: Number,
				default: 7
			},

			// 字段映射
			fieldNames: {
				type: Object,
				default: () => ({
					label: 'name',
					value: 'id',
					children: 'children'
				})
			}
		},

		data() {
			return {
				visible: false,
				currentTab: 0,
				selectedPath: [], // 选中的路径
				tabs: [], // 选项卡数据
				scrollLeft: 0,
				scrollTop: 0,
				tempSelectedPath: [] // 临时选择的路径（用于取消时恢复）
			}
		},

		computed: {
			// 显示的值
			displayValue() {
				if (typeof this.value === 'string') {
					return this.value
				}

				if (Array.isArray(this.value) && this.value.length > 0) {
					return this.value.map(item => item[this.fieldNames.label]).join(' / ')
				}

				return ''
			},

			// 当前选项卡对应的选项列表
			currentOptions() {
				if (this.selectedPath.length === 0) {
					return this.data
				}

				// 根据当前选中的路径获取子级选项
				let current = this.data
				for (let i = 0; i < this.currentTab; i++) {
					if (this.selectedPath[i] && current) {
						const selectedItem = this.selectedPath[i]
						const childrenKey = this.fieldNames.children
						current = selectedItem[childrenKey] || []
					}
				}
				return current || []
			}
		},

		watch: {
			show: {
				immediate: true,
				handler(newVal) {
					this.visible = newVal
					if (newVal) {
						this.initPicker()
					}
				}
			},

			value: {
				deep: true,
				handler(newVal) {
					this.initSelectedPath(newVal)
				}
			},

			data: {
				deep: true,
				handler() {
					if (this.visible) {
						this.initTabs()
					}
				}
			}
		},

		created() {
			this.initSelectedPath(this.value)
		},

		methods: {
			// 初始化选择器
			initPicker() {
				this.initTabs()
				this.initSelectedPath(this.value)
				this.tempSelectedPath = [...this.selectedPath]
				this.currentTab = Math.max(this.selectedPath.length - 1, 0)
				this.scrollToTab(this.currentTab)
			},

			// 初始化选项卡
			initTabs() {
				const defaultTabs = [
					'中药事业部',
					'事业1组',
					'学术研究部',
					'湖南省药学服务公司',
					'中药事业部',
					'中药事业部',
					'中药事业部'
				]

				this.tabs = []
				for (let i = 0; i < this.maxLevel; i++) {
					this.tabs.push({
						title: defaultTabs[i] || `层级${i + 1}`,
						level: i
					})
				}
			},

			// 初始化选中的路径
			initSelectedPath(value) {
				if (typeof value === 'string') {
					// 如果是字符串，解析成数组
					this.selectedPath = []
				} else if (Array.isArray(value)) {
					this.selectedPath = [...value]
				} else {
					this.selectedPath = []
				}
			},

			// 获取选项卡标题
			getTabTitle(tab, index) {
				if (this.selectedPath[index]) {
					return this.selectedPath[index][this.fieldNames.label]
				}
				return tab.title
			},

			// 打开选择器
			openPicker() {
				this.visible = true
				this.$emit('open')
				this.$nextTick(() => {
					this.initPicker()
				})
			},

			// 关闭选择器
			closePicker() {
				this.visible = false
				this.selectedPath = [...this.tempSelectedPath]
				this.$emit('close')
				this.$emit('update:show', false)
			},

			// 切换选项卡
			switchTab(index) {
				if (index < 0 || index >= this.tabs.length) return

				this.currentTab = index
				this.scrollToTab(index)
				this.scrollTop = 0
			},

			// 滚动到指定选项卡
			scrollToTab(index) {
				this.$nextTick(() => {
					// 简单计算滚动位置，实际可以更精确
					this.scrollLeft = index * 100
				})
			},

			// 判断是否有子级
			hasChildren(item) {
				const childrenKey = this.fieldNames.children
				return item[childrenKey] && item[childrenKey].length > 0
			},

			// 判断选项是否被选中
			isOptionSelected(item) {
				const currentSelected = this.selectedPath[this.currentTab]
				if (!currentSelected) return false

				const valueKey = this.fieldNames.value
				return currentSelected[valueKey] === item[valueKey]
			},

			// 选择选项
			selectOption(item) {
				const valueKey = this.fieldNames.value
				const labelKey = this.fieldNames.label
				const childrenKey = this.fieldNames.children

				// 更新当前级别的选择
				this.selectedPath[this.currentTab] = {
					[valueKey]: item[valueKey],
					[labelKey]: item[labelKey]
				}

				// 复制子级数据（如果有）
				if (item[childrenKey]) {
					Object.assign(this.selectedPath[this.currentTab], {
						[childrenKey]: item[childrenKey]
					})
				}

				// 清空后续级别的选择
				for (let i = this.currentTab + 1; i < this.selectedPath.length; i++) {
					this.selectedPath[i] = null
				}

				// 如果有子级且未达到最大层级，自动切换到下一级
				if (this.hasChildren(item) && this.currentTab < this.tabs.length - 1) {
					setTimeout(() => {
						this.currentTab++
						this.scrollToTab(this.currentTab)
					}, 150)
				}

				// 触发选择事件
				this.$emit('select', {
					level: this.currentTab,
					item: item,
					path: this.getCurrentPath()
				})
			},

			// 获取当前选择的完整路径
			getCurrentPath() {
				return this.selectedPath.filter(item => item !== null)
			},

			// 确认选择
			confirmSelection() {
				const selectedPath = this.getCurrentPath()

				if (this.required && selectedPath.length === 0) {
					uni.showToast({
						title: '请选择任务归属',
						icon: 'none'
					})
					return
				}

				// 保存临时路径
				this.tempSelectedPath = [...selectedPath]

				// 构建显示文本
				const displayText = selectedPath
					.map(item => item[this.fieldNames.label])
					.join(' / ')

				this.visible = false

				// 触发确认事件
				this.$emit('confirm', {
					value: selectedPath,
					displayText: displayText
				})

				// 更新外部数据
				this.$emit('input', selectedPath)
				this.$emit('update:show', false)
			}
		}
	}
</script>

<style lang="scss" scoped>
	/* 触发区域样式 */
	.picker-trigger {
		display: flex;
		align-items: center;
		padding: 30rpx 0;
		border-bottom: 1px solid #EBEDF0;

		.trigger-label {
			font-size: 28rpx;
			color: #333;
			flex-shrink: 0;
		}

		.trigger-value {
			flex: 1;
			text-align: right;
			font-size: 28rpx;
			color: #333;
			padding-right: 16rpx;

			&.placeholder {
				color: #C8C9CC;
			}
		}

		.trigger-icon {
			width: 36rpx;
			height: 36rpx;
		}
	}

	/* 选择器弹出层样式 */
	.task-belonging-picker {
		height: 70vh;
		display: flex;
		flex-direction: column;
		background: #fff;
	}

	/* 头部样式 */
	.picker-header {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 32rpx 32rpx 24rpx;
		border-bottom: 1px solid #f0f0f0;
	}

	.picker-title {
		font-size: 32rpx;
		font-weight: 500;
		color: #333;
	}

	.picker-close {
		width: 48rpx;
		height: 48rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.close-icon {
		font-size: 40rpx;
		color: #999;
		line-height: 1;
	}

	/* 选项卡样式 */
	.tab-container {
		border-bottom: 1px solid #f0f0f0;
		background: #fff;
	}

	.tab-scroll {
		width: 100%;
		white-space: nowrap;
	}

	.tab-list {
		display: inline-flex;
		padding: 0 32rpx;
	}

	.tab-item {
		position: relative;
		padding: 24rpx 0;
		margin-right: 40rpx;
		flex-shrink: 0;

		&:last-child {
			margin-right: 0;
		}

		&.active {
			.tab-text {
				color: #576B95;
				font-weight: 500;
			}
		}
	}

	.tab-text {
		font-size: 28rpx;
		color: #666;
		line-height: 40rpx;
		white-space: nowrap;
	}

	.tab-indicator {
		position: absolute;
		bottom: 0;
		left: 0;
		right: 0;
		height: 4rpx;
		background: #576B95;
		border-radius: 2rpx;
	}

	/* 列表区域样式 */
	.list-container {
		flex: 1;
		padding: 0 32rpx;
	}

	.option-list {
		padding: 24rpx 0;
	}

	.option-item {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 24rpx 0;
		border-bottom: 1px solid #f5f5f5;

		&:last-child {
			border-bottom: none;
		}

		&.selected {
			.option-name {
				color: #576B95;
			}
		}

		&.disabled {
			opacity: 0.5;
			pointer-events: none;
		}
	}

	.option-content {
		flex: 1;
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.option-name {
		font-size: 28rpx;
		color: #333;
	}

	.option-arrow {
		margin-left: 16rpx;
	}

	.arrow-icon {
		font-size: 36rpx;
		color: #999;
	}

	.option-selected {
		margin-left: 16rpx;
	}

	.selected-icon {
		font-size: 32rpx;
		color: #576B95;
		font-weight: bold;
	}

	/* 空状态样式 */
	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 100rpx 0;

		.empty-icon {
			width: 200rpx;
			height: 200rpx;
			margin-bottom: 32rpx;
			opacity: 0.5;
		}

		.empty-text {
			font-size: 28rpx;
			color: #999;
		}
	}

	/* 底部按钮样式 */
	.picker-footer {
		padding: 24rpx 32rpx;
		border-top: 1px solid #f0f0f0;
		background: #fff;
	}

	.confirm-button {
		height: 80rpx;
		line-height: 80rpx;
		text-align: center;
		background: #576B95;
		border-radius: 40rpx;
		font-size: 28rpx;
		color: #fff;
		font-weight: 500;
	}
</style>