<template>
    <AdminLayout title="工单管理" info="查看和处理客户服务工单">
        <template #action>
            <el-button type="primary" @click="showCreateDialog = true">
                <el-icon><Plus /></el-icon>
                创建工单
            </el-button>
        </template>

        <div class="workcase-container">
            <!-- 筛选区域 -->
            <el-card class="filter-card">
                <div class="ticket-filters">
                    <el-radio-group v-model="statusFilter" @change="handleFilterChange">
                        <el-radio-button label="all">全部</el-radio-button>
                        <el-radio-button label="pending">待处理</el-radio-button>
                        <el-radio-button label="processing">处理中</el-radio-button>
                        <el-radio-button label="done">已完成</el-radio-button>
                    </el-radio-group>

                    <div class="filter-right">
                        <el-select v-model="typeFilter" placeholder="故障类型" clearable style="width: 140px;">
                            <el-option label="电气系统故障" value="electrical" />
                            <el-option label="机械故障" value="mechanical" />
                            <el-option label="控制系统故障" value="control" />
                            <el-option label="配件更换" value="parts" />
                            <el-option label="安装调试" value="install" />
                            <el-option label="其他" value="other" />
                        </el-select>
                        <el-select v-model="urgencyFilter" placeholder="紧急程度" clearable style="width: 120px;">
                            <el-option label="紧急" value="emergency" />
                            <el-option label="普通" value="normal" />
                        </el-select>
                        <el-input v-model="searchKeyword" placeholder="搜索工单号/客户/设备" style="width: 200px;" :prefix-icon="Search" clearable />
                    </div>
                </div>
            </el-card>

            <!-- 工单列表 -->
            <el-card>
                <el-table :data="filteredTickets" style="width: 100%" v-loading="loading">
                    <el-table-column prop="optsn" label="工单号" width="140">
                        <template #default="{ row }">
                            <span class="ticket-no">{{ row.optsn }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="username" label="客户信息" width="150">
                        <template #default="{ row }">
                            <div class="customer-info">
                                <span class="name">{{ row.username }}</span>
                                <span class="phone">{{ row.phone }}</span>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="type" label="故障类型" width="120">
                        <template #default="{ row }">
                            <el-tag size="small">{{ typeMap[row.type] || row.type }}</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="device" label="设备型号" width="120" />
                    <el-table-column prop="emergency" label="紧急程度" width="100">
                        <template #default="{ row }">
                            <el-tag :type="row.emergency === 'emergency' ? 'danger' : 'warning'" size="small">
                                {{ emergencyMap[row.emergency] || row.emergency }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="status" label="状态" width="100">
                        <template #default="{ row }">
                            <el-tag :type="getStatusType(row.status)" size="small">
                                {{ statusMap[row.status] || row.status }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="processor" label="处理人" width="100">
                        <template #default="{ row }">
                            <span v-if="row.processor">{{ row.processor }}</span>
                            <span v-else class="unassigned">未指派</span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="createTime" label="创建时间" width="160" />
                    <el-table-column label="操作" width="200" fixed="right">
                        <template #default="{ row }">
                            <el-button type="primary" link size="small" @click="viewDetail(row)">详情</el-button>
                            <el-button v-if="row.status === 'pending'" type="warning" link size="small" @click="assignTicket(row)">指派</el-button>
                            <el-button v-if="row.status === 'processing' || row.status === 'process'" type="success" link size="small" @click="completeTicket(row)">完成</el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <div class="table-pagination">
                    <el-pagination v-model:current-page="currentPage" :page-size="pageSize" :total="total" layout="total, prev, pager, next" @current-change="handlePageChange" />
                </div>
            </el-card>
        </div>

        <!-- 创建工单弹窗 -->
        <el-dialog v-model="showCreateDialog" title="创建工单" width="650px">
            <el-form :model="formData" label-width="90px">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="客户姓名" required>
                            <el-input v-model="formData.username" placeholder="请输入客户姓名" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="联系电话" required>
                            <el-input v-model="formData.phone" placeholder="请输入联系电话" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="故障类型" required>
                            <el-select v-model="formData.type" placeholder="请选择故障类型" style="width: 100%;">
                                <el-option label="电气系统故障" value="electrical" />
                                <el-option label="机械故障" value="mechanical" />
                                <el-option label="控制系统故障" value="control" />
                                <el-option label="配件更换" value="parts" />
                                <el-option label="安装调试" value="install" />
                                <el-option label="其他" value="other" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="紧急程度" required>
                            <el-select v-model="formData.emergency" placeholder="请选择紧急程度" style="width: 100%;">
                                <el-option label="紧急" value="emergency" />
                                <el-option label="普通" value="normal" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item label="设备型号" required>
                    <el-select v-model="formData.device" placeholder="请选择设备型号" style="width: 100%;">
                        <el-option label="TH-500GF" value="TH-500GF" />
                        <el-option label="TH-300D" value="TH-300D" />
                        <el-option label="TH-800GF" value="TH-800GF" />
                        <el-option label="S-200X" value="S-200X" />
                    </el-select>
                </el-form-item>
                <el-form-item label="故障描述">
                    <el-input v-model="formData.description" type="textarea" :rows="4" placeholder="请输入故障描述" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="showCreateDialog = false">取消</el-button>
                <el-button type="primary" @click="createTicket">创建</el-button>
            </template>
        </el-dialog>

        <!-- 工单详情弹窗 -->
        <el-dialog v-model="showDetailDialog" title="工单详情" width="900px" destroy-on-close>
            <WorkcaseDetail
                v-if="showDetailDialog"
                :workcase-id="currentWorkcase.workcaseId"
                mode="view"
                @cancel="showDetailDialog = false"
                @complete="handleCompleteFromDetail"
            />
        </el-dialog>

        <!-- 指派工单弹窗 -->
        <WorkcaseAssign
            v-model="showAssignDialog"
            :workcase-id="assignWorkcaseId"
            :current-processor="assignCurrentProcessor"
            action="assign"
            @success="handleAssignSuccess"
        />
    </AdminLayout>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import AdminLayout from '@/views/admin/AdminLayout.vue'
import { Plus, Search } from 'lucide-vue-next'
import { ElMessage, ElMessageBox } from 'element-plus'
import { workcaseAPI } from '@/api/workcase'
import WorkcaseDetail from '@/views/public/workcase/WorkcaseDetail/WorkcaseDetail.vue'
import { WorkcaseAssign } from '@/components'
import type { TbWorkcaseDTO, TbWorkcaseProcessDTO } from '@/types/workcase'
import type { PageRequest, PageParam } from 'shared/types'

const statusFilter = ref('all')
const typeFilter = ref('')
const urgencyFilter = ref('')
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const showCreateDialog = ref(false)
const showDetailDialog = ref(false)
const currentWorkcase = ref<TbWorkcaseDTO>({})
const loading = ref(false)

// 指派弹窗相关
const showAssignDialog = ref(false)
const assignWorkcaseId = ref('')
const assignCurrentProcessor = ref('')

const formData = ref<TbWorkcaseDTO>({
    username: '',
    phone: '',
    device: '',
    type: '',
    emergency: 'normal',
    description: ''
})

const workcaseList = ref<TbWorkcaseDTO[]>([])

// ========================= API 调用方法 =========================
/**
 * 加载工单列表
 */
const loadWorkcases = async () => {
    loading.value = true
    const filter: TbWorkcaseDTO = {
        roomId: '',
        deviceNamePlateImg: '',
    }
    if (statusFilter.value !== 'all') {
        filter.status = statusFilter.value as TbWorkcaseDTO['status']
    }
    if (typeFilter.value) {
        filter.type = typeFilter.value
    }
    if (urgencyFilter.value) {
        filter.emergency = urgencyFilter.value as TbWorkcaseDTO['emergency']
    }
    
    const pageParam: PageParam = {
        page: currentPage.value,
        pageSize: pageSize.value
    }
    
    const pageRequest: PageRequest<TbWorkcaseDTO> = {
        filter,
        pageParam
    }
    const res = await workcaseAPI.getWorkcasePage(pageRequest)
    if (res.success) {
        workcaseList.value = res.dataList || res.pageDomain?.dataList || []
        total.value = res.pageDomain?.pageParam?.total || 0
    } else {
        ElMessage.error(res.message || '加载失败')
    }
    loading.value = false
}

/**
 * 创建工单 - API调用
 */
const createWorkcaseAPI = async () => {
    if (!formData.value.username || !formData.value.phone || !formData.value.device || !formData.value.type) {
        ElMessage.error('请填写必填项')
        return
    }
    
    const res = await workcaseAPI.createWorkcase(formData.value)
    if (res.success) {
        ElMessage.success('工单创建成功')
        showCreateDialog.value = false
        formData.value = { roomId: '', deviceNamePlateImg: '', username: '', phone: '', device: '', type: '', emergency: 'normal', description: '' }
        loadWorkcases()
    } else {
        ElMessage.error(res.message || '创建失败')
    }
}

/**
 * 指派工单 - 打开指派弹窗
 */
const assignWorkcaseAPI = async (workcase: TbWorkcaseDTO) => {
    assignWorkcaseId.value = workcase.workcaseId || ''
    assignCurrentProcessor.value = workcase.processor || ''
    showAssignDialog.value = true
}

/**
 * 指派成功回调
 */
const handleAssignSuccess = () => {
    loadWorkcases()
}

/**
 * 完成工单 - API调用
 */
const completeWorkcaseAPI = async (workcase: TbWorkcaseDTO) => {
    const process: TbWorkcaseProcessDTO = {
        workcaseId: workcase.workcaseId,
        action: 'finish',
        message: '工单完成'
    }

    const res = await workcaseAPI.createWorkcaseProcess(process)
    if (res.success) {
        ElMessage.success('完成成功')
        loadWorkcases()
    } else {
        ElMessage.error(res.message || '操作失败')
    }
}

/**
 * 从详情页完成工单
 */
const handleCompleteFromDetail = async (workcaseId: string) => {
    const process: TbWorkcaseProcessDTO = {
        workcaseId: workcaseId,
        action: 'finish',
        message: '工单完成'
    }

    const res = await workcaseAPI.createWorkcaseProcess(process)
    if (res.success) {
        ElMessage.success('完成成功')
        showDetailDialog.value = false
        loadWorkcases()
    } else {
        ElMessage.error(res.message || '操作失败')
    }
}


// ========================= 字段映射 =========================
const typeMap: Record<string, string> = {
    electrical: '电气系统故障',
    mechanical: '机械故障',
    control: '控制系统故障',
    parts: '配件更换',
    install: '安装调试',
    other: '其他'
}

const emergencyMap: Record<string, string> = {
    emergency: '紧急',
    normal: '普通'
}

const statusMap: Record<string, string> = {
    pending: '待处理',
    process: '处理中',
    processing: '处理中',
    done: '已完成'
}

// ========================= 计算属性 =========================
const filteredTickets = computed(() => {
    let result = workcaseList.value
    // Mock模式下做本地筛选
    if (statusFilter.value !== 'all') {
        result = result.filter((t: TbWorkcaseDTO) => t.status === statusFilter.value)
    }
    if (typeFilter.value) {
        result = result.filter((t: TbWorkcaseDTO) => t.type === typeFilter.value)
    }
    if (urgencyFilter.value) {
        result = result.filter((t: TbWorkcaseDTO) => t.emergency === urgencyFilter.value)
    }
    if (searchKeyword.value) {
        const keyword = searchKeyword.value.toLowerCase()
        result = result.filter((t: TbWorkcaseDTO) =>
            (t.roomId || '').toLowerCase().includes(keyword) ||
            (t.deviceNamePlateImg || '').toLowerCase().includes(keyword) ||
            (t.username || '').toLowerCase().includes(keyword) ||
            (t.device || '').toLowerCase().includes(keyword)
        )
    }
    return result
})

const getStatusType = (status: string) => {
    const map: Record<string, string> = {
        pending: 'warning',
        process: 'info',
        processing: 'info',
        done: 'success'
    }
    return map[status] || 'info'
}

const handleFilterChange = () => {
    currentPage.value = 1
    loadWorkcases() // API调用：取消注释启用
}

const handlePageChange = (page: number) => {
    currentPage.value = page
    loadWorkcases() // API调用：取消注释启用
}

const viewDetail = (row: TbWorkcaseDTO) => {
    currentWorkcase.value = { ...row }
    showDetailDialog.value = true
}

const assignTicket = (row: TbWorkcaseDTO) => {
    assignWorkcaseAPI(row) // API调用：取消注释启用
    // ElMessage.info(`指派工单: ${row.optsn}`)
}

const completeTicket = (row: TbWorkcaseDTO) => {
    completeWorkcaseAPI(row) // API调用：取消注释启用
    // ElMessage.success(`完成工单: ${row.optsn}`)
}

const createTicket = () => {
    createWorkcaseAPI() // API调用：取消注释启用
}

// ========================= 生命周期 =========================
onMounted(() => {
    loadWorkcases() // API调用：取消注释启用
    // loadMockData() // Mock模式：注释此行以使用API
})
</script>

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