<template>
	<!-- #ifdef APP -->
	<scroll-view style="flex:1">
	<!-- #endif -->
	<view class="page">
		<!-- 导航栏 -->
		<view class="nav" :style="{ paddingTop: headerPaddingTop + 'px', height: headerTotalHeight + 'px' }">
			<view class="nav-back" @tap="goBack">
				<view class="nav-back-icon"></view>
			</view>
			<text class="nav-title">{{ mode === 'create' ? '创建工单' : '工单详情' }}</text>
			<view class="nav-capsule"></view>
		</view>

		<!-- 内容区域 -->
		<scroll-view class="content" scroll-y="true" :style="{ marginTop: headerTotalHeight + 'px' }">
			<!-- 工单头部 -->
			<view class="header-card">
				<view class="header-info">
					<text class="workcase-id">{{ workcase.workcaseId }}</text>
					<view class="header-tags">
						<view class="status-badge" :class="getStatusClass(workcase.status)">
							<text class="badge-text">{{ getStatusText(workcase.status) }}</text>
						</view>
						<view class="urgency-badge" :class="workcase.emergency === 'emergency' ? 'urgent' : 'normal'">
							<text class="badge-text">{{ workcase.emergency === 'emergency' ? '紧急' : '普通' }}</text>
						</view>
					</view>
				</view>
				<view class="header-action" v-if="workcase.workcaseId" @tap="handleViewChat">
					<text class="action-btn">查看对话</text>
				</view>
			</view>

			<!-- 工单信息表单 -->
			<view class="section">
				<view class="form-container">
					<!-- 客户姓名 -->
					<view class="form-item">
						<text class="form-label">客户姓名<text class="required" v-if="mode === 'create'">*</text></text>
						<input v-if="mode === 'create'" class="form-input" v-model="workcase.username" placeholder="请输入客户姓名" />
						<text v-else class="form-value">{{ workcase.username || '-' }}</text>
					</view>

					<!-- 联系电话 -->
					<view class="form-item">
						<text class="form-label">联系电话<text class="required" v-if="mode === 'create'">*</text></text>
						<input v-if="mode === 'create'" class="form-input" v-model="workcase.phone" placeholder="请输入联系电话" />
						<text v-else class="form-value">{{ workcase.phone || '-' }}</text>
					</view>

					<!-- 设备名称 -->
					<view class="form-item">
						<text class="form-label">设备名称<text class="required" v-if="mode === 'create'">*</text></text>
						<input v-if="mode === 'create'" class="form-input" v-model="workcase.device" placeholder="请输入设备名称" />
						<text v-else class="form-value">{{ workcase.device || '-' }}</text>
					</view>

					<!-- 故障类型 -->
					<view class="form-item">
						<text class="form-label">故障类型<text class="required" v-if="mode === 'create'">*</text></text>
						<picker v-if="mode === 'create'" class="form-picker" :value="typeIndex" :range="faultTypes" @change="onTypeChange">
							<view class="picker-content">
								<text class="picker-text">{{ workcase.type || '请选择故障类型' }}</text>
								<text class="picker-arrow">></text>
							</view>
						</picker>
						<text v-else class="form-value">{{ workcase.type || '-' }}</text>
					</view>

					<!-- 紧急程度 -->
					<view class="form-item" v-if="mode === 'create'">
						<text class="form-label">紧急程度</text>
						<picker class="form-picker" :value="emergencyIndex" :range="emergencies" @change="onEmergencyChange">
							<view class="picker-content">
								<text class="picker-text">{{ emergencies[emergencyIndex] }}</text>
								<text class="picker-arrow">></text>
							</view>
						</picker>
					</view>

					<!-- 现场地址 -->
					<view class="form-item">
						<text class="form-label">现场地址<text class="required" v-if="mode === 'create'">*</text></text>
						<input v-if="mode === 'create'" class="form-input" v-model="workcase.address" placeholder="请输入现场地址" />
						<text v-else class="form-value">{{ workcase.address || '-' }}</text>
					</view>

					<!-- 故障描述 -->
					<view class="form-item">
						<text class="form-label">故障描述<text class="required" v-if="mode === 'create'">*</text></text>
						<textarea v-if="mode === 'create'" class="form-textarea" v-model="workcase.description" placeholder="请详细描述故障现象..." maxlength="500" />
						<text v-else class="form-value">{{ workcase.description || '-' }}</text>
					</view>

					<!-- 设备铭牌 -->
					<view class="form-item">
						<text class="form-label">设备铭牌<text class="required" v-if="mode === 'create'">*</text></text>
						<input v-if="mode === 'create'" class="form-input" v-model="workcase.deviceNamePlate" placeholder="请输入设备铭牌"/>
						<text v-else class="form-value">{{ workcase.deviceNamePlate || '-' }}</text>
					</view>

					<!-- 铭牌照片 -->
					<view class="form-item">
						<text class="form-label">铭牌照片</text>
						<!-- 创建模式：上传铭牌 -->
						<view v-if="mode === 'create'" class="nameplate-upload">
							<view v-if="workcase.deviceNamePlateImg" class="nameplate-preview" @tap="previewNameplateImage">
								<image class="nameplate-image" :src="getImageUrl(workcase.deviceNamePlateImg)" mode="aspectFit" />
								<view class="nameplate-delete" @tap.stop="deleteNameplateImage">
									<text class="delete-icon">×</text>
								</view>
							</view>
							<view v-else class="nameplate-placeholder" @tap="chooseNameplateImage">
								<text class="upload-plus">+</text>
								<text class="upload-text">上传设备铭牌</text>
							</view>
						</view>
						<!-- 查看模式：显示铭牌 -->
						<view v-else-if="workcase.deviceNamePlateImg" class="nameplate-photo" @tap="previewNameplateImage">
							<image class="nameplate-image" :src="getImageUrl(workcase.deviceNamePlateImg)" mode="aspectFit" />
						</view>
						<text v-else class="form-value">-</text>
					</view>

					<!-- 处理人 -->
					<view class="form-item" v-if="mode !== 'create'">
						<text class="form-label">处理人</text>
						<text class="form-value">{{ workcase.processorName || '未指派' }}</text>
					</view>

					<!-- 创建时间 -->
					<view class="form-item" v-if="mode !== 'create'">
						<text class="form-label">创建时间</text>
						<text class="form-value">{{ workcase.createTime || '-' }}</text>
					</view>
				</view>
			</view>

			<!-- 故障图片 -->
			<view class="section">
				<view class="section-title">
					<view class="title-icon">📷</view>
					<text class="title-text">故障图片<text class="required" v-if="mode === 'create'">*</text></text>
				</view>
				<view class="photos-grid">
					<view class="photo-item" v-for="(img, index) in workcase.imgs" :key="index" @tap="previewFaultImages(index)">
						<image class="photo-image" :src="getImageUrl(img)" mode="aspectFill" />
						<view v-if="mode === 'create'" class="photo-delete" @tap.stop="deleteFaultImage(index)">
							<text class="delete-icon">×</text>
						</view>
					</view>
					<view v-if="mode === 'create' && workcase.imgs.length < 9" class="photo-upload" @tap="chooseFaultImages">
						<text class="upload-plus">+</text>
						<text class="upload-text">添加图片</text>
					</view>
				</view>
				<text v-if="mode === 'create'" class="upload-tip">最多上传9张图片，支持拍照或从相册选择</text>
			</view>

			<!-- 处理记录 -->
			<view class="section" v-if="mode !== 'create' && processList.length > 0">
				<view class="section-title">
					<view class="title-bar"></view>
					<text class="title-text">处理记录</text>
				</view>
				<!-- 处理人记录处理过程 - 仅在处理中状态显示 -->
				<view v-if="isProcessor && workcase.status === 'processing'" class="add-process-section">
					<button class="add-process-btn" type="primary" size="mini" @tap="navigateToAddProcess">
						添加处理记录
					</button>
				</view>
				<view class="timeline">
					<view class="timeline-item" v-for="(item, index) in processList" :key="index">
						<view class="timeline-dot" :class="getTimelineDotClass(item.status)"></view>
						<view class="timeline-line" v-if="index < processList.length - 1"></view>
						<view class="timeline-body">
							
							<view class="timeline-header">
								<text class="timeline-time">{{ getTime(item.createTime) }}</text>
								<text class="timeline-date">{{ getDate(item.createTime) }}</text>
							</view>
							<view class="timeline-info">
								<text class="timeline-action" >{{ getActionText(item.action) }}:</text>
								<text class="timeline-desc">{{ item.message }}</text>
							</view>
							<!-- 附件列表 -->
							<view class="timeline-files" v-if="item.files && item.files.length > 0">
								<text class="files-label">附件：</text>
								<view class="files-list">
									<view 
										class="file-link" 
										v-for="fileId in item.files" 
										:key="fileId"
										@tap="previewOrDownloadFile(fileId)"
									>
										<text class="file-icon">{{ getFileIcon(fileId) }}</text>
										<text class="file-name">{{ getFileName(fileId) }}</text>
									</view>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>

			<!-- 底部占位 -->
			<view class="footer-placeholder"></view>
		</scroll-view>

		<!-- 底部操作栏 -->
		<view class="footer-actions">
			<view class="action-button" @tap="goBack">
				<text class="button-text">{{ mode === 'create' ? '取消' : '关闭' }}</text>
			</view>
			<view class="action-button primary" v-if="mode === 'create'" @tap="submitWorkcase">
				<text class="button-text">提交工单</text>
			</view>

			<!-- 来客视角：只能撤销自己创建的工单 -->
			<view
				class="action-button danger"
				v-if="mode !== 'create' && isCreator && workcase.status !== 'done'"
				@tap="handleRevoke"
			>
				<text class="button-text">撤销工单</text>
			</view>

			<!-- 员工视角：可以指派、转派、完成工单 -->
			<view
				class="action-button warning"
				v-if="mode !== 'create' && !isCreator && workcase.status === 'pending'"
				@tap="handleAssign"
			>
				<text class="button-text">指派工程师</text>
			</view>
			<view
				class="action-button warning"
				v-if="mode !== 'create' && !isCreator && workcase.status === 'processing'"
				@tap="handleRedeployBtn"
			>
				<text class="button-text">转派工程师</text>
			</view>
			<view
				class="action-button success"
				v-if="mode !== 'create' && !isCreator && workcase.status === 'processing'"
				@tap="handleComplete"
			>
				<text class="button-text">完成工单</text>
			</view>
		</view>

		<!-- 添加处理记录弹窗（使用 v-if 控制显示） -->
		<view v-if="showAddProcessDialog" class="process-modal-overlay" @tap="closeAddProcessDialog">
			<view class="process-modal" @tap.stop>
				<view class="modal-header">
					<text class="modal-title">添加处理记录</text>
					<view class="modal-close" @tap="closeAddProcessDialog">
						<text>×</text>
					</view>
				</view>
				<view class="modal-body">
					<view class="form-item">
						<text class="form-label">处理内容</text>
						<textarea
							class="form-textarea"
							v-model="processForm.message"
							placeholder="请详细描述处理过程、发现的问题或解决方案..."
							maxlength="500"
						/>
						<text class="char-count">{{ processForm.message.length }}/500</text>
					</view>
					<view class="form-item">
						<text class="form-label">附件（可选）</text>
						<view class="file-upload-section">
							<view class="file-list">
								<view class="file-item" v-for="(file, index) in processForm.files" :key="index">
									<text class="file-name">{{ file.name }}</text>
									<view class="file-delete" @tap="deleteProcessFile(index)">
										<text>×</text>
									</view>
								</view>
							</view>
							<button
								class="upload-btn"
								size="mini"
								@tap="chooseProcessFile"
								v-if="processForm.files.length < 5"
							>
								选择文件
							</button>
							<text class="upload-tip">最多上传5个文件</text>
						</view>
					</view>
				</view>
				<view class="modal-footer">
					<button class="modal-btn" @tap="closeAddProcessDialog">取消</button>
					<button class="modal-btn primary" type="primary" @tap="submitProcessRecord" :loading="submittingProcess">
						提交
					</button>
				</view>
			</view>
		</view>

		<!-- 指派/转派工程师弹窗 -->
		<view v-if="showAssignDialog" class="process-modal-overlay" @tap="closeAssignDialog">
			<view class="process-modal" @tap.stop>
				<view class="modal-header">
					<text class="modal-title">{{ assignDialogTitle }}</text>
					<view class="modal-close" @tap="closeAssignDialog">
						<text>×</text>
					</view>
				</view>
				<view class="modal-body">
					<view class="form-item">
						<text class="form-label">选择工程师</text>
						<picker 
							class="form-picker" 
							:value="selectedEngineerIndex" 
							:range="availableEngineers" 
							range-key="username"
							@change="onEngineerChange"
						>
							<view class="picker-content">
								<text class="picker-text" v-if="assignForm.processorName">{{ assignForm.processorName }}</text>
								<text class="picker-text placeholder" v-else>请选择工程师</text>
								<view class="picker-arrow-icon"></view>
							</view>
						</picker>
						<view v-if="loadingEngineers" class="loading-tip">
							<text>加载中...</text>
						</view>
					</view>
					<view class="form-item">
						<text class="form-label">备注说明（可选）</text>
						<textarea
							class="form-textarea"
							v-model="assignForm.message"
							placeholder="请输入指派/转派说明..."
							maxlength="200"
						/>
					</view>
					<view class="form-item">
						<text class="form-label">附件（可选）</text>
						<view class="file-upload-section">
							<view class="file-list" v-if="assignForm.files.length > 0">
								<view class="file-item" v-for="(file, index) in assignForm.files" :key="index">
									<text class="file-name">{{ file.name }}</text>
									<view class="file-delete" @tap="deleteAssignFile(index)">
										<text>×</text>
									</view>
								</view>
							</view>
							<button
								class="upload-btn"
								size="mini"
								@tap="chooseAssignFile"
								v-if="assignForm.files.length < 5"
							>
								选择文件
							</button>
							<text class="upload-tip">最多上传5个文件</text>
						</view>
					</view>
				</view>
				<view class="modal-footer">
					<button class="modal-btn" @tap="closeAssignDialog">取消</button>
					<button class="modal-btn primary" type="primary" @tap="submitAssign" :loading="submittingAssign">
						确定
					</button>
				</view>
			</view>
		</view>
	</view>
	<!-- #ifdef APP -->
	</scroll-view>
	<!-- #endif -->
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, computed } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import type { TbWorkcaseDTO, TbWorkcaseProcessDTO, WorkcaseProcessVO } from '@/types/workcase'
import type { CustomerServiceVO } from '@/types/workcase/chatRoom'
import { workcaseAPI, fileAPI, workcaseChatAPI } from '@/api'

// 响应式数据
const headerPaddingTop = ref<number>(44)
const headerTotalHeight = ref<number>(88)
const workcaseId = ref<string>('')
const mode = ref<'view' | 'create'>('view')

// 表单选项
const faultTypes = ref<string[]>(['电气系统故障', '机械故障', '控制系统故障', '油路系统故障', '其他故障'])
const typeIndex = ref<number>(0)
const emergencies = ref<string[]>(['普通', '紧急'])
const emergencyIndex = ref<number>(0)
const userId = JSON.parse(uni.getStorageSync('loginDomain')).userInfo.userId

// 工单数据
const workcase = reactive<TbWorkcaseDTO>({})

// 处理记录
const processList = reactive<WorkcaseProcessVO[]>([])

// 文件信息缓存
const fileInfoCache = reactive<Map<string, any>>(new Map())

// 判断是否是处理人
const isProcessor = computed(() => {
	return workcase.processor === userId
})

// 判断是否是创建人
const isCreator = computed(() => {
	return workcase.creator === userId
})

// 添加处理记录相关
const showAddProcessDialog = ref(false)
const submittingProcess = ref(false)
const processForm = reactive({
	message: '',
	files: [] as Array<{ name: string; fileId: string }>
})

// 指派/转派相关
const showAssignDialog = ref(false)
const assignDialogTitle = ref('指派工程师')
const assignAction = ref<'assign' | 'redeploy'>('assign')
const submittingAssign = ref(false)
const loadingEngineers = ref(false)
const availableEngineers = ref<CustomerServiceVO[]>([])
const selectedEngineerIndex = ref(-1)
const assignForm = reactive({
    processor: '',
    processorName: '',
    message: '',
    files: [] as Array<{ name: string; fileId: string }>
})

// 获取图片 URL（通过 fileId）
function getImageUrl(fileId: string): string {
	// 如果已经是完整 URL，直接返回
	if (fileId.startsWith('http://') || fileId.startsWith('https://')) {
		return fileId
	}
	// 否则通过 fileId 构建下载 URL
	return fileAPI.getDownloadUrl(fileId)
}

// 生命周期
onLoad((options: any) => {
	
	// 处理 mode 参数
	if (options.mode === 'create') {
		mode.value = 'create'
		// create 模式必须从上一页带入 roomId（前端先建 room 的策略）
		const roomId = options.roomId || ''
		const deviceCodeParam = decodeURIComponent(options.deviceCode || '')
		if (!roomId) {
			uni.showToast({ title: '缺少roomId，无法创建工单', icon: 'none' })
			// 直接退出，避免后续提交失败
			setTimeout(() => uni.navigateBack(), 800)
			return
		}
		// 只使用 loginDomain（没有就空）
		let username = ''
		let phone = ''
		let userId = ''
		try {
			const loginDomainRaw = uni.getStorageSync('loginDomain')
			if (loginDomainRaw) {
				const loginDomain = typeof loginDomainRaw === 'string' ? JSON.parse(loginDomainRaw) : loginDomainRaw
				username = loginDomain?.userInfo?.username || ''
				phone = loginDomain?.user?.phone || ''
				userId = loginDomain?.userInfo?.userId || ''
			}
		} catch (e) {
			console.error('读取loginDomain失败:', e)
		}

		// 使用 Object.assign 更新 reactive 对象
		Object.assign(workcase, {
			username,
			phone,
			userId,
			roomId,
			deviceCode: deviceCodeParam,
			deviceNamePlate: deviceCodeParam,
			device: '',
			type: '',
			address: '',
			description: '',
			emergency: 'normal',
			imgs: []
		})
	} else if (options.workcaseId) {
			// 查看模式
			workcaseId.value = options.workcaseId
			mode.value = 'view'
			loadWorkcaseDetail(workcaseId.value)
		}
})

onMounted(() => {
	const windowInfo = uni.getWindowInfo()
	const statusBarHeight = windowInfo.statusBarHeight || 44
	
	// #ifdef MP-WEIXIN
	try {
		const menuButtonInfo = uni.getMenuButtonBoundingClientRect()
		headerPaddingTop.value = menuButtonInfo.top
		headerTotalHeight.value = menuButtonInfo.bottom + 8
	} catch (e) {
		headerPaddingTop.value = statusBarHeight
		headerTotalHeight.value = statusBarHeight + 44
	}
	// #endif
	// #ifndef MP-WEIXIN
	headerPaddingTop.value = statusBarHeight
	headerTotalHeight.value = statusBarHeight + 44
	// #endif
})

// 加载工单详情
async function loadWorkcaseDetail(workcaseId : string) {
		uni.showLoading({ title: '加载中...' })
		try {
			const res = await workcaseAPI.getWorkcaseById(workcaseId)
			if (res.success && res.data) {
				// 使用 Object.assign 更新 reactive 对象
				Object.assign(workcase, res.data)
				console.log('工单详情:', workcase)
				// 加载处理记录
				await loadProcessList(workcaseId)
			} else {
				uni.showToast({ title: res.message || '加载失败', icon: 'none' })
			}
		} catch (error) {
			console.error('加载工单详情失败:', error)
			uni.showToast({ title: '加载失败', icon: 'none' })
		} finally {
			uni.hideLoading()
		}
	}

// 加载处理记录
async function loadProcessList(workcaseId: string) {
	try {
		const res = await workcaseAPI.getWorkcaseProcessList({ workcaseId: workcaseId })
		if (res.success && res.dataList) {
			// 清空并重新填充 reactive 数组
			processList.length = 0
			processList.push(...res.dataList)
			console.log('处理记录:', processList)
			// 加载文件信息
			await loadFilesInfo(res.dataList)
		}
	} catch (error) {
		console.error('加载处理记录失败:', error)
	}
}

// 加载处理记录中的文件信息
async function loadFilesInfo(processes: TbWorkcaseProcessDTO[]) {
	// 收集所有文件ID
	const fileIds: string[] = []
	processes.forEach(p => {
		if (p.files) {
			const filesArray = Array.isArray(p.files) ? p.files : [p.files]
			filesArray.forEach(id => {
				if (id && !fileInfoCache.has(id)) {
					fileIds.push(id)
				}
			})
		}
	})
	
	if (fileIds.length === 0) return
	
	// 逐个查询文件信息
	for (const fileId of fileIds) {
		try {
			const res = await fileAPI.getFileById(fileId)
			if (res.success && res.data) {
				fileInfoCache.set(fileId, res.data)
			}
		} catch (error) {
			console.error(`加载文件信息失败: ${fileId}`, error)
		}
	}
}

// 获取文件名
function getFileName(fileId: string): string {
	const fileInfo = fileInfoCache.get(fileId)
	return fileInfo?.name || fileId.substring(0, 8) + '...'
}

// 获取文件图标
function getFileIcon(fileId: string): string {
	const fileInfo = fileInfoCache.get(fileId)
	if (!fileInfo) return '📎'
	
	const ext = (fileInfo.extension || fileInfo.name?.split('.').pop() || '').toLowerCase()
	const iconMap: Record<string, string> = {
		jpg: '🖼️',
		jpeg: '🖼️',
		png: '🖼️',
		gif: '🖼️',
		webp: '🖼️',
		pdf: '📄',
		doc: '📝',
		docx: '📝',
		xls: '📊',
		xlsx: '📊'
	}
	return iconMap[ext] || '📎'
}

// 预览或下载文件
function previewOrDownloadFile(fileId: string) {
	const fileInfo = fileInfoCache.get(fileId)
	const fileUrl = fileAPI.getDownloadUrl(fileId)
	
	// 如果是图片，预览
	if (fileInfo) {
		const ext = (fileInfo.extension || fileInfo.name?.split('.').pop() || '').toLowerCase()
		if (['jpg', 'jpeg', 'png', 'gif', 'webp'].includes(ext)) {
			uni.previewImage({
				urls: [fileUrl],
				current: 0
			})
			return
		}
	}
	
	// 其他文件，打开文档或复制链接
	uni.showActionSheet({
		itemList: ['复制下载链接', '打开文档'],
		success: (res) => {
			if (res.tapIndex === 0) {
				uni.setClipboardData({
					data: fileUrl,
					success: () => {
						uni.showToast({ title: '链接已复制', icon: 'success' })
					}
				})
			} else if (res.tapIndex === 1) {
				uni.downloadFile({
					url: fileUrl,
					success: (downloadRes) => {
						if (downloadRes.statusCode === 200) {
							uni.openDocument({
								filePath: downloadRes.tempFilePath,
								fail: () => {
									uni.showToast({ title: '无法打开此文件', icon: 'none' })
								}
							})
						}
					},
					fail: () => {
						uni.showToast({ title: '下载失败', icon: 'none' })
					}
				})
			}
		}
	})
}

function getTime(datetime: string): string{
	return datetime.split(" ")[1]
}
function getDate(datetime: string): string{
	return datetime.split(" ")[0]
}

// 获取状态样式类
function getStatusClass(status?: string): string {
	switch (status) {
		case 'pending': return 'status-pending'
		case 'processing': return 'status-processing'
		case 'done': return 'status-done'
		default: return 'status-pending'
	}
}

// 获取状态文本
function getStatusText(status?: string): string {
	switch (status) {
		case 'pending': return '待处理'
		case 'processing': return '处理中'
		case 'done': return '已完成'
		default: return '未知'
	}
}

// 获取时间线圆点样式类
function getTimelineDotClass(action?: string): string {
	switch (action) {
		case 'create':
		case 'info':
			return 'dot-system'
		case 'assign':
		case 'redeploy':
			return 'dot-manager'
		case 'finish':
			return 'dot-engineer'
		case 'repeal':
			return 'dot-cancel'
		default:
			return 'dot-system'
	}
}

// 获取动作文本
function getActionText(action?: string): string {
	switch (action) {
		case 'create':
			return '工单创建'
		case 'info':
			return '记录信息'
		case 'assign':
			return '指派工程师'
		case 'redeploy':
			return '转派工程师'
		case 'repeal':
			return '撤销工单'
		case 'finish':
			return '完成工单'
		default:
			return '未知操作'
	}
}

// 查看对话
function handleViewChat() {
	if (!workcase.roomId) {
		uni.showToast({ title: '未关联聊天室', icon: 'none' })
		return
	}
	uni.navigateTo({
		url: `/pages/chatRoom/chatRoom/chatRoom?roomId=${workcase.roomId}`
	})
}

// 指派工程师
function handleAssign() {
	assignAction.value = 'assign'
	assignDialogTitle.value = '指派工程师'
	openAssignDialog()
}

// 完成工单
function handleComplete() {
	uni.showModal({
		title: '完成确认',
		content: '确认完成该工单？',
		success: async (res) => {
			if (res.confirm) {
				try {
					const params: TbWorkcaseProcessDTO = {
						workcaseId: workcase.workcaseId,
						action: 'finish',
						message: '工单完成'
					}
					const result = await workcaseAPI.createWorkcaseProcess(params)
					if (result.success) {
						uni.showToast({ title: '工单已完成', icon: 'success' })
						// 重新加载工单详情
						if (workcase.workcaseId) {
							await loadWorkcaseDetail(workcase.workcaseId)
						}
					} else {
						uni.showToast({ title: result.message || '操作失败', icon: 'none' })
					}
				} catch (error) {
					console.error('完成工单失败:', error)
					uni.showToast({ title: '操作失败', icon: 'none' })
				}
			}
		}
	})
}

// 转派工程师
function handleRedeploy() {
	assignAction.value = 'redeploy'
	assignDialogTitle.value = '转派工程师'
	openAssignDialog()
}

// 打开指派/转派弹窗
async function openAssignDialog() {
	assignForm.processor = ''
	assignForm.processorName = ''
	assignForm.message = ''
	assignForm.files = []
	selectedEngineerIndex.value = -1
	showAssignDialog.value = true
	await loadAvailableEngineers()
}

// 关闭指派/转派弹窗
function closeAssignDialog() {
	showAssignDialog.value = false
}

// 选择指派/转派附件
function chooseAssignFile() {
	uni.chooseMessageFile({
		count: 5 - assignForm.files.length,
		type: 'all',
		success: async (res) => {
			uni.showLoading({ title: '上传中...' })
			try {
				for (const file of res.tempFiles) {
					const uploadRes = await fileAPI.uploadFile(file.path, {
						module: 'workcase',
						optsn: workcase.workcaseId || 'temp'
					}, file.name)
					if (uploadRes.success && uploadRes.data?.fileId) {
						assignForm.files.push({
							name: file.name,
							fileId: uploadRes.data.fileId
						})
					}
				}
				uni.hideLoading()
				uni.showToast({ title: '上传成功', icon: 'success' })
			} catch (error) {
				uni.hideLoading()
				console.error('上传文件失败:', error)
				uni.showToast({ title: '上传失败', icon: 'none' })
			}
		},
		fail: () => {
			// 如果 chooseMessageFile 不支持，尝试使用 chooseImage
			uni.chooseImage({
				count: 5 - assignForm.files.length,
				sizeType: ['compressed'],
				sourceType: ['album', 'camera'],
				success: async (imgRes) => {
					uni.showLoading({ title: '上传中...' })
					try {
						for (const filePath of imgRes.tempFilePaths) {
							const fileName = filePath.split('/').pop() || '图片.jpg'
							const uploadRes = await fileAPI.uploadFile(filePath, {
								module: 'workcase',
								optsn: workcase.workcaseId || 'temp'
							}, fileName)
							if (uploadRes.success && uploadRes.data?.fileId) {
								assignForm.files.push({
									name: fileName,
									fileId: uploadRes.data.fileId
								})
							}
						}
						uni.hideLoading()
						uni.showToast({ title: '上传成功', icon: 'success' })
					} catch (error) {
						uni.hideLoading()
						console.error('上传文件失败:', error)
						uni.showToast({ title: '上传失败', icon: 'none' })
					}
				}
			})
		}
	})
}

// 删除指派/转派附件
function deleteAssignFile(index: number) {
	assignForm.files.splice(index, 1)
}

// 加载可用工程师列表（排除当前处理人）
async function loadAvailableEngineers() {
	loadingEngineers.value = true
	try {
		const res = await workcaseChatAPI.getCustomerServicePage({
			filter: {},
			pageParam: { page: 1, pageSize: 100 }
		})
		if (res.success && res.dataList) {
			// 排除当前处理人
			availableEngineers.value = res.dataList.filter(
				(engineer: CustomerServiceVO) => engineer.userId !== workcase.processor
			)
		}
	} catch (error) {
		console.error('加载工程师列表失败:', error)
		uni.showToast({ title: '加载工程师列表失败', icon: 'none' })
	} finally {
		loadingEngineers.value = false
	}
}

// 选择工程师
function onEngineerChange(e: any) {
	const index = e.detail.value
	selectedEngineerIndex.value = index
	if (index >= 0 && index < availableEngineers.value.length) {
		const engineer = availableEngineers.value[index]
		assignForm.processor = engineer.userId || ''
		assignForm.processorName = engineer.username || ''
	}
}

// 提交指派/转派
async function submitAssign() {
	if (!assignForm.processor) {
		uni.showToast({ title: '请选择工程师', icon: 'none' })
		return
	}

	if (!workcase.workcaseId) {
		uni.showToast({ title: '工单ID不存在', icon: 'none' })
		return
	}

	submittingAssign.value = true
	try {
		const params: TbWorkcaseProcessDTO = {
			workcaseId: workcase.workcaseId,
			action: assignAction.value,
			processor: assignForm.processor,
			message: assignForm.message || (assignAction.value === 'assign' ? '工单指派' : '工单转派'),
			files: assignForm.files.map(f => f.fileId)
		}

		const res = await workcaseAPI.createWorkcaseProcess(params)
		if (res.success) {
			uni.showToast({ 
				title: assignAction.value === 'assign' ? '指派成功' : '转派成功', 
				icon: 'success' 
			})
			closeAssignDialog()
			// 重新加载工单详情
			if (workcase.workcaseId) {
				await loadWorkcaseDetail(workcase.workcaseId)
			}
		} else {
			uni.showToast({ title: res.message || '操作失败', icon: 'none' })
		}
	} catch (error) {
		console.error('指派/转派失败:', error)
		uni.showToast({ title: '操作失败', icon: 'none' })
	} finally {
		submittingAssign.value = false
	}
}

// 表单选择器事件
function onTypeChange(e: any) {
	typeIndex.value = e.detail.value
	workcase.type = faultTypes.value[e.detail.value]
}

function onEmergencyChange(e: any) {
	emergencyIndex.value = e.detail.value
	workcase.emergency = emergencyIndex.value === 0 ? 'normal' : 'emergency'
}

// 选择故障图片
async function chooseFaultImages() {
	uni.chooseImage({
		count: 9 - (workcase.imgs?.length || 0),
		sizeType: ['compressed'],
		sourceType: ['camera', 'album'],
		success: async (res) => {
			if (!workcase.imgs) {
				workcase.imgs = []
			}

			// 上传图片到服务器
			uni.showLoading({ title: '上传中...' })
			try {
				const uploadPromises = res.tempFilePaths.map((filePath, index) => {
					const fileName = `故障图片_${Date.now()}_${index}.jpg`
					return fileAPI.uploadFile(filePath, {
						module: 'workcase',
						optsn: workcase.workcaseId || 'temp'
					}, fileName)
				})

				const results = await Promise.all(uploadPromises)

				// 使用 fileId 添加图片
				results.forEach(result => {
					if (result.success && result.data?.fileId) {
						// 存储 fileId，用于提交时使用
						workcase.imgs!.push(result.data.fileId)
					}
				})

				uni.hideLoading()
				uni.showToast({ title: '上传成功', icon: 'success' })
			} catch (error) {
				uni.hideLoading()
				console.error('上传图片失败:', error)
				uni.showToast({ title: '上传失败', icon: 'none' })
			}
		},
		fail: (err) => {
			console.log('选择图片失败:', err)
		}
	})
}

// 删除故障图片
function deleteFaultImage(index: number) {
	if (workcase.imgs) {
		workcase.imgs.splice(index, 1)
	}
}

// 选择铭牌照片
async function chooseNameplateImage() {
	uni.chooseImage({
		count: 1,
		sizeType: ['compressed'],
		sourceType: ['camera', 'album'],
		success: async (res) => {
			// 上传铭牌照片到服务器
			uni.showLoading({ title: '上传中...' })
			try {
				const fileName = `设备铭牌_${Date.now()}.jpg`
				const result = await fileAPI.uploadFile(res.tempFilePaths[0], {
					module: 'workcase',
					optsn: workcase.workcaseId || 'temp'
				}, fileName)

				if (result.success && result.data?.fileId) {
					workcase.deviceNamePlateImg = result.data.fileId
					uni.hideLoading()
					uni.showToast({ title: '上传成功', icon: 'success' })
				} else {
					uni.hideLoading()
					uni.showToast({ title: '上传失败', icon: 'none' })
				}
			} catch (error) {
				uni.hideLoading()
				console.error('上传铭牌照片失败:', error)
				uni.showToast({ title: '上传失败', icon: 'none' })
			}
		},
		fail: (err) => {
			console.log('选择图片失败:', err)
		}
	})
}

// 删除铭牌照片
function deleteNameplateImage() {
	workcase.deviceNamePlateImg = ''
}

// 预览铭牌照片
function previewNameplateImage() {
	if (!workcase.deviceNamePlateImg) return
	const imageUrl = getImageUrl(workcase.deviceNamePlateImg)
	uni.previewImage({
		urls: [imageUrl],
		current: 0
	})
}

// 预览故障图片
function previewFaultImages(index: number) {
	if (!workcase.imgs || workcase.imgs.length === 0) return
	// 将 fileId 数组转换为 URL 数组
	const imageUrls = workcase.imgs.map(fileId => getImageUrl(fileId))
	uni.previewImage({
		urls: imageUrls,
		current: index
	})
}

// 提交工单
async function submitWorkcase() {
	// 校验必填项
	if (!workcase.username) {
		uni.showToast({ title: '请输入客户姓名', icon: 'none' })
		return
	}
	if (!workcase.phone) {
		uni.showToast({ title: '请输入联系电话', icon: 'none' })
		return
	}
	if (!workcase.device) {
		uni.showToast({ title: '请输入设备名称', icon: 'none' })
		return
	}
	if (!workcase.type) {
		uni.showToast({ title: '请选择故障类型', icon: 'none' })
		return
	}
	if (!workcase.address) {
		uni.showToast({ title: '请输入现场地址', icon: 'none' })
		return
	}
	if (!workcase.description) {
		uni.showToast({ title: '请输入故障描述', icon: 'none' })
		return
	}
	if (!workcase.deviceNamePlate) {
		uni.showToast({ title: '请输入设备铭牌', icon: 'none' })
		return
	}
	if (!workcase.imgs || workcase.imgs.length === 0) {
		uni.showToast({ title: '请至少上传一张故障图片', icon: 'none' })
		return
	}

	uni.showLoading({ title: '提交中...' })

	try {
		// 调用 API 提交工单
		const res = await workcaseAPI.createWorkcase(workcase)
		uni.hideLoading()

		if (res.success && res.data) {
			uni.showToast({
				title: '工单创建成功',
				icon: 'success'
			})
			// 创建成功后直接回到该聊天室（闭环）
			setTimeout(() => {
				uni.redirectTo({
					url: `/pages/chatRoom/chatRoom/chatRoom?roomId=${workcase.roomId}&workcaseId=${res.data.workcaseId || ''}`
				})
			}, 600)
		} else {
			uni.showToast({
				title: res.message || '创建失败',
				icon: 'none'
			})
		}
	} catch (error) {
		uni.hideLoading()
		console.error('提交工单失败:', error)
		uni.showToast({
			title: '提交失败，请重试',
			icon: 'none'
		})
	}
}

// 撤销工单
function handleRevoke() {
	uni.showModal({
		title: '撤销确认',
		content: '确认撤销该工单？撤销后无法恢复',
		success: (res) => {
			if (res.confirm) {
				// TODO: 调用 API 撤销工单
				uni.showToast({
					title: '工单已撤销',
					icon: 'success'
				})
			}
		}
	})
}

// 转派工程师
function handleRedeployBtn() {
	handleRedeploy()
}

// 导航到添加处理记录（或直接显示弹窗）
function navigateToAddProcess() {
	showAddProcessDialog.value = true
}

// 关闭添加处理记录弹窗
function closeAddProcessDialog() {
	showAddProcessDialog.value = false
}

// 选择处理记录附件
async function chooseProcessFile() {
	uni.chooseFile({
		count: 5 - processForm.files.length,
		extension: ['.jpg', '.jpeg', '.png', '.pdf', '.doc', '.docx', '.xls', '.xlsx'],
		success: async (res) => {
			uni.showLoading({ title: '上传中...' })
			try {
				const uploadPromises = res.tempFiles.map(async (file) => {
					const result = await fileAPI.uploadFile(file.path, {
						module: 'workcase',
						optsn: workcase.workcaseId || 'temp'
					}, file.name)
					if (result.success && result.data?.fileId) {
						return {
							name: file.name,
							fileId: result.data.fileId
						}
					}
					return null
				})

				const results = await Promise.all(uploadPromises)
				results.forEach(result => {
					if (result) {
						processForm.files.push(result)
					}
				})

				uni.hideLoading()
				uni.showToast({ title: '上传成功', icon: 'success' })
			} catch (error) {
				uni.hideLoading()
				console.error('上传文件失败:', error)
				uni.showToast({ title: '上传失败', icon: 'none' })
			}
		}
	})
}

// 删除处理记录附件
function deleteProcessFile(index: number) {
	processForm.files.splice(index, 1)
}

// 提交处理记录
async function submitProcessRecord() {
	if (!processForm.message.trim()) {
		uni.showToast({ title: '请输入处理内容', icon: 'none' })
		return
	}

	if (!workcase.workcaseId) {
		uni.showToast({ title: '工单ID不存在', icon: 'none' })
		return
	}

	submittingProcess.value = true
	try {
		const fileIds = processForm.files.map(f => f.fileId)
		const params: TbWorkcaseProcessDTO = {
			workcaseId: workcase.workcaseId,
			action: 'info',
			message: processForm.message,
			files: fileIds.length > 0 ? fileIds : undefined
		}

		const res = await workcaseAPI.createWorkcaseProcess(params)
		if (res.success) {
			uni.showToast({ title: '处理记录添加成功', icon: 'success' })
			closeAddProcessDialog()
			// 重置表单
			processForm.message = ''
			processForm.files = []
			// 重新加载处理记录
			if (workcase.workcaseId) {
				await loadProcessList(workcase.workcaseId)
			}
		} else {
			uni.showToast({ title: res.message || '添加失败', icon: 'none' })
		}
	} catch (error) {
		console.error('添加处理记录失败:', error)
		uni.showToast({ title: '添加失败', icon: 'none' })
	} finally {
		submittingProcess.value = false
	}
}

// 返回上一页
function goBack() {
	uni.navigateBack()
}
</script>

<style lang="scss" scoped>
@import "./workcaseDetail.scss";
</style>