<template>
    <div class="workcase-detail">
        <!-- Header -->
        <header class="detail-header">
            <!-- Left Part -->
            <div class="header-left">
                <div class="workcase-info">
                    <span class="workcase-id">{{ formData.workcaseId || '新建工单' }}</span>
                    <span v-if="mode === 'view' && formData.status" class="status-badge" :class="statusClass(formData.status)">
                        {{ statusLabel(formData.status) }}
                    </span>
                    <span v-if="mode === 'view' && formData.emergency" class="urgency-badge" :class="urgencyClass(formData.emergency)">
                        {{ urgencyLabel(formData.emergency) }}
                    </span>
                </div>
            </div>

            <!-- Right Part -->
            <div class="header-right">
                <button v-if="mode === 'view' && formData.workcaseId" class="view-chat-btn" @click="handleViewChat">
                    <MessageSquare :size="14" />
                    查看对话
                </button>
            </div>
        </header>

        <!-- Main Content -->
        <main class="detail-main">
            <!-- 工单信息表格 -->
            <div class="info-table">
                <!-- 客户姓名 & 联系电话 -->
                <div class="table-row">
                    <div class="table-label">客户姓名</div>
                    <div class="table-value">
                        <ElInput v-if="mode !== 'view'" v-model="formData.username" placeholder="请输入客户姓名" size="small" />
                        <span v-else>{{ formData.username || '-' }}</span>
                    </div>
                    <div class="table-label">联系电话</div>
                    <div class="table-value">
                        <ElInput v-if="mode !== 'view'" v-model="formData.phone" placeholder="请输入联系电话" size="small" />
                        <span v-else>{{ formData.phone || '-' }}</span>
                    </div>
                </div>

                <!-- 设备名称 & 故障类型 -->
                <div class="table-row">
                    <div class="table-label">设备名称</div>
                    <div class="table-value">
                        <ElInput v-if="mode !== 'view'" v-model="formData.device" placeholder="请输入设备名称" size="small" />
                        <span v-else>{{ formData.device || '-' }}</span>
                    </div>
                    <div class="table-label">故障类型</div>
                    <div class="table-value">
                        <ElSelect v-if="mode !== 'view'" v-model="formData.type" placeholder="请选择故障类型" size="small">
                            <ElOption v-for="item in faultTypes" :key="item" :label="item" :value="item" />
                        </ElSelect>
                        <span v-else>{{ formData.type || '-' }}</span>
                    </div>
                </div>

                <!-- 现场地址 -->
                <div class="table-row">
                    <div class="table-label">现场地址</div>
                    <div class="table-value table-value-full">
                        <ElInput v-if="mode !== 'view'" v-model="formData.address" placeholder="请输入现场地址" size="small" />
                        <span v-else>{{ formData.address || '-' }}</span>
                    </div>
                </div>

                <!-- 故障描述 -->
                <div class="table-row">
                    <div class="table-label">故障描述</div>
                    <div class="table-value table-value-full">
                        <ElInput 
                            v-if="mode !== 'view'" 
                            v-model="formData.description" 
                            type="textarea" 
                            :rows="3"
                            placeholder="请详细描述故障现象"
                            size="small" 
                        />
                        <span v-else>{{ formData.description || '-' }}</span>
                    </div>
                </div>

                <!-- 设备铭牌 -->
                <div class="table-row">
                    <div class="table-label">设备铭牌</div>
                    <div class="table-value table-value-full">
                        <ElInput v-if="mode !== 'view'" v-model="formData.deviceNamePlate" placeholder="请输入设备铭牌" size="small" />
                        <span v-else>{{ formData.deviceNamePlate || '-' }}</span>
                    </div>
                </div>

                <!-- 铭牌照片 -->
                <div class="table-row" v-if="formData.deviceNamePlateImg">
                    <div class="table-label">铭牌照片</div>
                    <div class="table-value table-value-full">
                        <div class="nameplate-photo" @click="previewNameplateImage">
                            <img :src="getImageUrl(formData.deviceNamePlateImg)" alt="设备铭牌" />
                        </div>
                    </div>
                </div>

                <!-- 紧急程度 -->
                <div class="table-row" v-if="mode !== 'view'">
                    <div class="table-label">紧急程度</div>
                    <div class="table-value table-value-full">
                        <ElSelect v-model="formData.emergency" placeholder="请选择紧急程度" size="small">
                            <ElOption label="普通" value="normal" />
                            <ElOption label="紧急" value="emergency" />
                        </ElSelect>
                    </div>
                </div>

                <!-- 处理人 (仅查看模式) -->
                <div class="table-row" v-if="mode === 'view'">
                    <div class="table-label">处理人</div>
                    <div class="table-value">
                        <span>{{ formData.processorName || '未指派' }}</span>
                    </div>
                    <div class="table-label">创建时间</div>
                    <div class="table-value">
                        <span>{{ formData.createTime || '-' }}</span>
                    </div>
                </div>
            </div>

            <!-- 故障照片 -->
            <div class="photos-section" v-if="mode !== 'create' || formData.imgs?.length">
                <div class="section-title">
                    <ImageIcon :size="18" class="title-icon" />
                    故障照片
                </div>
                <div class="photos-grid">
                    <div v-for="(img, index) in formData.imgs" :key="index" class="photo-item">
                        <img :src="getImageUrl(img)" alt="故障照片" />
                    </div>
                    <div v-if="mode !== 'view'" class="photo-upload">
                        <Plus :size="32" />
                    </div>
                </div>
            </div>

            <!-- 处理记录 (仅查看模式) -->
            <div class="timeline-section" v-if="mode === 'view' && processList.length > 0">
                <div class="section-title">
                    <div class="title-left">
                        <div class="title-bar"></div>
                        处理记录
                    </div>
                    <!-- 工单处理人记录工单过程 - 仅在处理中状态显示-->
                    <ElButton
                        v-if="isProcessor && (formData.status === 'processing')"
                        type="primary"
                        size="small"
                        @click="showAddProcessDialog = true"
                    >
                        添加处理记录
                    </ElButton>
                </div>
                <div class="timeline-content">
                    <div v-for="(item, index) in processList" :key="index" class="timeline-item">
                        <div class="timeline-dot" :class="getTimelineDotClass(item.action)"></div>
                        <div class="timeline-line" v-if="index < processList.length - 1"></div>
                        <div class="timeline-body">
                            <div class="timeline-header">
                                <span class="timeline-time">{{ getTime(item.createTime) }}</span>
                                <span class="timeline-date">{{ getDate(item.createTime) }}</span>
                            </div>
                            <div class="timeline-info">
                                <span class="timeline-action">{{ getActionText(item.action) }}:</span>
                                <span class="timeline-desc">{{ item.message }}</span>
                            </div>
                            <!-- 附件列表 -->
                            <div v-if="item.files && item.files.length > 0" class="timeline-files">
                                <div class="files-label">附件：</div>
                                <div class="files-list">
                                    <a 
                                        v-for="fileId in item.files" 
                                        :key="fileId" 
                                        :href="getFileDownloadUrl(fileId)" 
                                        target="_blank"
                                        class="file-link"
                                    >
                                        <span class="file-icon">{{ getFileIcon(fileId) }}</span>
                                        <span class="file-name">{{ getFileName(fileId) }}</span>
                                    </a>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </main>

        <!-- Footer Actions -->
        <footer class="detail-footer">
            <ElButton @click="handleCancel">{{ mode === 'view' ? '关闭' : '取消' }}</ElButton>
            <ElButton v-if="mode === 'create'" type="primary" @click="handleSubmit">创建工单</ElButton>

            <!-- 来客视角：只能撤销自己创建的工单 -->
            <ElButton
                v-if="mode === 'view' && isCreator && formData.status !== 'done'"
                type="danger"
            >
                撤销工单
            </ElButton>

            <!-- 员工视角：可以指派、转派、完成工单 -->
            <ElButton
                v-if="mode === 'view' && !isCreator && formData.status === 'pending'"
                type="warning"
                @click="handleAssign"
            >
                指派工程师
            </ElButton>
            <ElButton
                v-if="mode === 'view' && !isCreator && (formData.status === 'processing')"
                type="warning"
                @click="handleRedeploy"
            >
                转派工程师
            </ElButton>
            <ElButton
                v-if="mode === 'view' && !isCreator && (formData.status === 'processing')"
                type="success"
                @click="handleComplete"
            >
                完成工单
            </ElButton>
        </footer>

        <!-- ChatMessage Dialog -->
        <ElDialog v-model="showChatMessage" title="对话详情" width="800px" class="chat-dialog">
            <ChatMessage v-if="showChatMessage" :room-id="currentRoomId" />
        </ElDialog>

        <!-- Add Process Record Dialog -->
        <ElDialog v-model="showAddProcessDialog" title="添加处理记录" width="600px">
            <div class="add-process-form">
                <div class="form-item">
                    <label class="form-label">处理内容</label>
                    <ElInput
                        v-model="processForm.message"
                        type="textarea"
                        :rows="4"
                        placeholder="请详细描述处理过程、发现的问题或解决方案..."
                        maxlength="500"
                        show-word-limit
                    />
                </div>
                <div class="form-item" style="margin-top: 16px;">
                    <label class="form-label">附件（可选）</label>
                    <FileUpload
                        ref="processFileUploadRef"
                        mode="content"
                        :max-count="5"
                        :max-size="10 * 1024 * 1024"
                        accept="image/*,.pdf,.doc,.docx,.xls,.xlsx"
                        v-model:file-list="processUploadedFiles"
                        @upload-success="handleProcessUploadSuccess"
                        @upload-error="handleProcessUploadError"
                    />
                </div>
            </div>
            <template #footer>
                <ElButton @click="handleCloseProcessDialog">取消</ElButton>
                <ElButton type="primary" @click="submitProcessRecord" :loading="submittingProcess">提交</ElButton>
            </template>
        </ElDialog>

        <!-- Assign/Redeploy Dialog -->
        <WorkcaseAssign
            v-model="showAssignDialog"
            :workcase-id="formData.workcaseId || ''"
            :current-processor="formData.processor || ''"
            :action="assignAction"
            @success="handleAssignSuccess"
        />
    </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted, computed } from 'vue'
import { ChatMessage } from '@/views/public/ChatRoom/'
import { ElButton, ElInput, ElSelect, ElOption, ElDialog, ElMessage, ElLoading } from 'element-plus'
import { MessageSquare, ImageIcon as ImageIcon, Plus } from 'lucide-vue-next'
import type { TbWorkcaseDTO, TbWorkcaseProcessDTO } from '@/types/workcase/workcase'
import type { TbSysFileDTO } from 'shared/types'
import { workcaseAPI } from '@/api/workcase'
import { fileAPI } from 'shared/api/file'
import { FileUpload } from 'shared/components'
import { WorkcaseAssign } from '@/components'
import { FILE_DOWNLOAD_URL } from '@/config'

interface Props {
    mode?: 'view' | 'edit' | 'create'
    workcaseId?: string  // 查看/编辑模式传入 workcaseId，组件内部加载数据
    roomId?: string      // 创建模式传入 roomId
}

const props = withDefaults(defineProps<Props>(), {
    mode: 'view',
    workcaseId: '',
    roomId: ''})

const emit = defineEmits<{
    cancel: []
    submit: [data: TbWorkcaseDTO]
    assign: [workcaseId: string]
    complete: [workcaseId: string]
    created: [workcaseId: string]  // 创建成功事件
}>()

const loading = ref(false)
const formData = ref<TbWorkcaseDTO>({
})

// 故障类型选项（与微信端保持一致）
const faultTypes = ['电气系统故障', '机械故障', '控制系统故障', '油路系统故障', '其他故障']

const showChatMessage = ref(false)
const currentRoomId = ref<string>('')
const processList = ref<TbWorkcaseProcessDTO[]>([])

// 文件信息缓存 (fileId -> TbSysFileDTO)
const fileInfoCache = ref<Map<string, TbSysFileDTO>>(new Map())

// 当前登录用户ID
const userId = ref<string>('')
// 判断是否是处理人
const isProcessor = computed(() => {
	return formData.value.processor === userId.value
})
// 判断是否是创建人
const isCreator = computed(() => {
	return formData.value.creator === userId.value
})

// 添加处理记录相关
const showAddProcessDialog = ref(false)
const submittingProcess = ref(false)
const processForm = ref({
	message: '',
	fileIds: [] as string[]
})

// 已上传的文件列表（用于显示）
const processUploadedFiles = ref<TbSysFileDTO[]>([])

// 指派/转派相关
const showAssignDialog = ref(false)
const assignAction = ref<'assign' | 'redeploy'>('assign')

// 加载工单详情
const loadWorkcaseDetail = async (workcaseId: string) => {
    if (!workcaseId) return
    
    loading.value = true
    try {
        const res = await workcaseAPI.getWorkcaseById(workcaseId)
        if (res.success && res.data) {
            formData.value = res.data
            currentRoomId.value = res.data.roomId || ''
            // 加载处理记录
            await loadProcessList(workcaseId)
        } else {
            ElMessage.error(res.message || '加载工单详情失败')
        }
    } catch (error) {
        console.error('加载工单详情失败:', error)
        ElMessage.error('加载工单详情失败')
    } finally {
        loading.value = false
    }
}

// 加载处理记录
const loadProcessList = async (workcaseId: string) => {
    try {
        const res = await workcaseAPI.getWorkcaseProcessList({ workcaseId })
        if (res.success && res.dataList) {
            processList.value = res.dataList
            // 加载所有文件信息
            await loadFilesInfo(res.dataList)
        }
    } catch (error) {
        console.error('加载处理记录失败:', error)
    }
}

// 加载处理记录中的文件信息
const loadFilesInfo = async (processes: TbWorkcaseProcessDTO[]) => {
    // 收集所有文件ID
    const fileIds: string[] = []
    processes.forEach(p => {
        if (p.files) {
            // 处理 files 可能是字符串或数组的情况
            const filesArray = Array.isArray(p.files) ? p.files : [p.files]
            filesArray.forEach(id => {
                if (id && !fileInfoCache.value.has(id)) {
                    fileIds.push(id)
                }
            })
        }
    })
    
    console.log('需要查询的文件ID:', fileIds)
    
    if (fileIds.length === 0) return
    
    // 逐个查询文件信息
    for (const fileId of fileIds) {
        try {
            console.log('查询文件信息:', fileId)
            const res = await fileAPI.getFileById(fileId)
            console.log('文件信息结果:', res)
            if (res.success && res.data) {
                fileInfoCache.value.set(fileId, res.data)
            }
        } catch (error) {
            console.error(`加载文件信息失败: ${fileId}`, error)
        }
    }
}

// 获取文件信息
const getFileInfo = (fileId: string): TbSysFileDTO | undefined => {
    return fileInfoCache.value.get(fileId)
}

// 获取时间线圆点样式类
const 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'
    }
}

// 获取动作文本
const getActionText = (action?: string): string => {
    const map: Record<string, string> = {
        create: '工单创建',
        info: '记录信息',
        assign: '指派工程师',
        redeploy: '转派工程师',
        repeal: '撤销工单',
        finish: '完成工单'
    }
    return map[action || ''] || '未知操作'
}

// 获取时间部分
const getTime = (datetime?: string): string => {
    if (!datetime) return ''
    return datetime.split(' ')[1] || ''
}

// 获取日期部分
const getDate = (datetime?: string): string => {
    if (!datetime) return ''
    return datetime.split(' ')[0] || ''
}

function getImageUrl(fileId: string): string {
    if (!fileId) return ''
    if (fileId.startsWith('http://') || fileId.startsWith('https://')) {
        return fileId
    }
    return `${FILE_DOWNLOAD_URL}${fileId}`
}

// 获取文件下载URL
function getFileDownloadUrl(fileId: string): string {
    if (!fileId) return ''
    return `${FILE_DOWNLOAD_URL}${fileId}`
}

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

// 获取文件图标
function getFileIcon(fileId: string): string {
    const fileInfo = fileInfoCache.value.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: '📊',
        ppt: '📽️',
        pptx: '📽️',
        zip: '📦',
        rar: '📦',
        txt: '📃'
    }
    return iconMap[ext] || '📎'
}

// 初始化
onMounted(() => {
    // 获取当前登录用户ID
    const loginDomain = JSON.parse(localStorage.getItem('loginDomain') || '{}')
    userId.value = loginDomain?.userInfo?.userId || ''

    if (props.mode === 'view' || props.mode === 'edit') {
        // 查看/编辑模式：通过 workcaseId 加载数据
        loadWorkcaseDetail(props.workcaseId)
    } else if (props.mode === 'create') {
        // 创建模式：初始化空表单，设置 roomId
        formData.value = {
            roomId: props.roomId,
            username: loginDomain?.userInfo?.username || '',
            phone: loginDomain?.user?.phone || '',
            userId: userId.value,
            emergency: 'normal',
            imgs: []
        }
    }
})

// 监听 workcaseId 变化
watch(() => props.workcaseId, (newVal) => {
    if (newVal && (props.mode === 'view' || props.mode === 'edit')) {
        loadWorkcaseDetail(newVal)
    }
})

const statusLabel = (status: string) => {
    const map: Record<string, string> = {
        pending: '待处理',
        process: '处理中',
        processing: '处理中',
        done: '已完成'
    }
    return map[status] || status
}

const statusClass = (status: string) => {
    const map: Record<string, string> = {
        pending: 'status-pending',
        process: 'status-processing',
        processing: 'status-processing',
        done: 'status-done'
    }
    return map[status] || ''
}

const urgencyLabel = (urgency: string) => {
    const map: Record<string, string> = {
        normal: '普通',
        emergency: '紧急'
    }
    return map[urgency] || urgency
}

const urgencyClass = (urgency: string) => {
    const map: Record<string, string> = {
        normal: 'urgency-normal',
        emergency: 'urgency-emergency'
    }
    return map[urgency] || ''
}

const handleViewChat = () => {
    showChatMessage.value = true
}

const previewNameplateImage = () => {
    if (!formData.value.deviceNamePlateImg) return
    // TODO: 使用图片预览组件
    window.open(formData.value.deviceNamePlateImg, '_blank')
}

const handleCancel = () => {
    emit('cancel')
}

const handleSubmit = async () => {
    if (props.mode === 'create' || props.mode === 'edit') {
        // 校验必填项
        if (!formData.value.username) {
            ElMessage.warning('请输入客户姓名')
            return
        }
        if (!formData.value.phone) {
            ElMessage.warning('请输入联系电话')
            return
        }
        if (!formData.value.device) {
            ElMessage.warning('请输入设备名称')
            return
        }
        if (!formData.value.type) {
            ElMessage.warning('请选择故障类型')
            return
        }
        if (!formData.value.address) {
            ElMessage.warning('请输入现场地址')
            return
        }
        if (!formData.value.description) {
            ElMessage.warning('请输入故障描述')
            return
        }
        
        if (props.mode === 'create') {
            // 创建工单
            loading.value = true
            try {
                const res = await workcaseAPI.createWorkcase(formData.value)
                if (res.success && res.data) {
                    ElMessage.success('工单创建成功')
                    emit('created', res.data.workcaseId!)
                } else {
                    ElMessage.error(res.message || '创建失败')
                }
            } catch (error) {
                console.error('创建工单失败:', error)
                ElMessage.error('创建工单失败')
            } finally {
                loading.value = false
            }
        } else {
            // 编辑模式，触发 submit 事件
            emit('submit', formData.value)
        }
    }
}

const handleAssign = () => {
    assignAction.value = 'assign'
    showAssignDialog.value = true
}

const handleComplete = () => {
    emit('complete', formData.value.workcaseId!)
}

// 处理转派
const handleRedeploy = () => {
    assignAction.value = 'redeploy'
    showAssignDialog.value = true
}

// 指派/转派成功回调
const handleAssignSuccess = async () => {
    // 重新加载工单详情
    if (formData.value.workcaseId) {
        await loadWorkcaseDetail(formData.value.workcaseId)
    }
    // 触发事件通知父组件
    if (assignAction.value === 'assign') {
        emit('assign', formData.value.workcaseId!)
    }
}

// 处理记录文件上传组件引用
const processFileUploadRef = ref<InstanceType<typeof FileUpload>>()

// 处理记录上传成功回调
const handleProcessUploadSuccess = (files: TbSysFileDTO[]) => {
    console.log('文件上传成功:', files)
}

// 处理记录上传失败回调
const handleProcessUploadError = (error: string) => {
    ElMessage.error(error)
}

// 关闭处理记录弹窗
const handleCloseProcessDialog = () => {
    showAddProcessDialog.value = false
    processForm.value = { message: '', fileIds: [] }
    processUploadedFiles.value = []
    if (processFileUploadRef.value) {
        processFileUploadRef.value.clearFiles()
    }
}

// 提交处理记录
const submitProcessRecord = async () => {
    if (!processForm.value.message.trim()) {
        ElMessage.warning('请输入处理内容')
        return
    }

    if (!formData.value.workcaseId) {
        ElMessage.error('工单ID不存在')
        return
    }

    submittingProcess.value = true
    try {
        // 从已上传文件列表获取文件ID
        const fileIds = processUploadedFiles.value
            .map((f: TbSysFileDTO) => f.fileId)

        // 提交处理记录
        const params: TbWorkcaseProcessDTO = {
            workcaseId: formData.value.workcaseId,
            action: 'info',
            message: processForm.value.message,
            files: fileIds.length > 0 ? fileIds : undefined
        }

        const res = await workcaseAPI.createWorkcaseProcess(params)
        if (res.success) {
            ElMessage.success('处理记录添加成功')
            handleCloseProcessDialog()
            // 重新加载处理记录
            if (formData.value.workcaseId) {
                await loadProcessList(formData.value.workcaseId)
            }
        } else {
            ElMessage.error(res.message || '添加失败')
        }
    } catch (error) {
        console.error('添加处理记录失败:', error)
        ElMessage.error('添加处理记录失败')
    } finally {
        submittingProcess.value = false
    }
}
</script>

<style scoped lang="scss">
@import url("./WorkcaseDetail.scss");
</style>