<template>
    <div>
        <!-- 事件处理弹窗 -->
        <el-drawer v-model="showEventDrawer" size="40%" title="事件处理">
            <div style="padding: 20px;color: #000;">
                <el-form v-model="formData">
                    <h2 style="margin-bottom: 20px;">事件详情</h2>
                    <el-row :gutter="24">
                        <el-col :span="12">
                            <el-form-item label="事件ID">
                                <el-input v-model="formData.id" disabled></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="事件名称">
                                <el-input v-model="formData.name"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row :gutter="24">
                        <el-col :span="12">
                            <el-form-item label="目标类别">
                                <el-select v-model="formData.aimType" placeholder="请选择目标类别">
                                    <el-option v-for="(value, key) in TARGET_TYPE" :key="key" :value="Number(key)"
                                        :label="value"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="场景类别">
                                <el-select v-model="formData.sceneType" placeholder="请选择">
                                    <el-option v-for="(value, key) in SCENE_TYPE" :key="key" :value="Number(key)"
                                        :label="value"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row :gutter="24">
                        <el-col :span="12">
                            <el-form-item label="事件性质">
                                <el-select v-model="formData.eventType" placeholder="请选择">
                                    <el-option v-for="(value, key) in EVENT_TYPE" :key="key" :value="Number(key)"
                                        :label="value"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="状态">
                                <span class="form-status"
                                    :style="{ backgroundColor: STATUS_COLOR[`${formData.status}`] }"></span>
                                {{ STATUS[`${formData.status}`] }}
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-form-item label="事件预览">
                        <div style="display: flex; align-items: center; gap: 10px;">
                            <el-image v-loading="fileImgUrlLoading" style="width: 100px; height: 100px"
                                :src="fileImgUrl" :zoom-rate="1.2" :max-scale="7" :min-scale="0.2"
                                :preview-src-list="[fileImgUrl]" show-progress :initial-index="4" fit="cover" />
                            <el-button type="primary" size="small" @click="openAnnotationModal">
                                <el-icon>
                                    <Edit />
                                </el-icon>
                                标注图片
                            </el-button>
                        </div>
                    </el-form-item>
                    <el-form-item label="站点区间">
                        <div style="width: 100%;">
                            <!-- <MapContainer :wgs84="state.eventForm.wgs84"/> -->
                            <MapContainer :wgs84="{ x: formData.longitude, y: formData.latitude }" :selectable="true"
                                @location-selected="handleLocationSelected" />
                        </div>
                    </el-form-item>
                    <el-form-item label="位置描述">
                        <el-input type="textarea" v-model="formData.addrDesc"></el-input>
                    </el-form-item>
                    <div
                        style="display: flex;justify-content: space-between;align-items: center;margin: 40px 0 20px 0;">
                        <div>
                            <h2>处置信息</h2>
                        </div>
                    </div>
                    <el-row :gutter="24">
                        <el-col :span="12">
                            <el-form-item label="监管项目">
                                <el-select @change="changeProject" v-model="formData.projectId" filterable remote
                                    :remote-method="remoteMethodByProject" placeholder="请搜索选择">
                                    <el-option v-for="item in projectOption" :key="item.id" :label="item.name"
                                        :value="item.id" />
                                </el-select>
                            </el-form-item>

                        </el-col>
                        <el-col :span="12">
                            <el-button style="display: inline-block;" type="primary" @click="goProject">新建</el-button>
                        </el-col>
                    </el-row>

                    <el-row :gutter="24">
                        <el-col :span="12">
                            <el-form-item label="执行人">
                                <el-select @change="handleUserChange" v-model="formData.executorId" filterable remote
                                    :remote-method="remoteMethodByUser" placeholder="请搜索选择">
                                    <el-option v-for="item in userOption" :key="item.userId" :label="item.nickname"
                                        :value="item.userId" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="异常等级">
                                <el-select v-model="formData.abnormalLevel" placeholder="请选择">
                                    <el-option v-for="(value, key) in ABNORMAL_LEVEL" :key="key" :value="Number(key)"
                                        :label="value"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row :gutter="24">
                        <el-col :span="12">
                            <el-form-item label="发现时间">
                                {{ formData.findTime }}
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="处置时间">
                                {{ formData.handleTime ?? '-' }}
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-form-item label="现场照片">
                        <el-upload v-model:file-list="fileList" :http-request="(event: any) => handUpload(event)"
                            list-type="picture-card" :on-preview="handlePictureCardPreview" :on-remove="handleRemove">
                            <el-icon>
                                <Plus />
                            </el-icon>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="处置说明">
                        <el-input type="textarea" v-model="formData.description"></el-input>
                    </el-form-item>
                    <el-form-item label="处置操作">
                        <el-button type="primary" plain @click="updateStatus(3)"
                            :disabled="formData.status == 3 || formData.status == 5">取消事件</el-button>
                        <el-button type="primary" plain @click="updateStatus(4)"
                            :disabled="formData.status == 3 || formData.status == 5 || formData.status == 4">派单</el-button>
                        <el-button type="primary" plain @click="updateStatus(5)"
                            :disabled="formData.status == 5 || formData.status == 3">处置完毕</el-button>
                    </el-form-item>
                </el-form>
            </div>
            <template #footer>
                <div class="drawer-footer">
                    <el-button type="primary" @click="handleSubmit">暂存</el-button>
                    <el-button @click="showEventDrawer = false">取消</el-button>
                </div>
            </template>
        </el-drawer>
        <el-dialog v-model="dialogVisible">
            <img w-full :src="dialogImageUrl" alt="Preview Image" />
        </el-dialog>

        <!-- 图片标注弹窗 -->
        <ImageAnnotationModal v-model="annotationModalVisible" :image-url="fileImgUrl" title="事件图片标注"
            @save="handleAnnotationSave" />
        <!-- 派单人员选择 -->
        <el-dialog v-model="showPointerVisible">
            <div class="filter-section">
                <div class="filter-group">
                    <el-input v-model="searchQuery" placeholder="搜索用户" prefix-icon="el-icon-search" size="small"
                        class="search-input"></el-input>
                </div>
            </div>
            <el-radio-group v-model="userId" style="width:100%">
                <el-table highlight-current-row :data="userData" border class="event-table"
                    @row-click="handlePointerRowClick" v-loading="state.userLoading" element-loading-text="加载中...">
                    <el-table-column type="" width="50">
                        <template #default="{ row }">
                            <el-radio :value="row.userId"></el-radio>
                        </template>
                    </el-table-column>
                    <el-table-column type="index" width="50" />
                    <el-table-column prop="nickname" label="姓名"></el-table-column>
                    <el-table-column prop="roleName" label="角色"></el-table-column>
                </el-table>
            </el-radio-group>

            <div class="pagination-section">
                <el-pagination @size-change="handleUserSizeChange" @current-change="handleUserCurrentChange"
                    :current-page="state.userParams.PageNum" :page-sizes="[10, 20, 50, 100]"
                    :page-size="state.userParams.pageSize" layout="total, sizes, prev, pager, next, jumper"
                    :total="state.userTotal"></el-pagination>
            </div>
            <template #footer>
                <div class="drawer-footer">
                    <el-button type="primary" @click="handleUserSubmit" :disabled="!userId">确定</el-button>
                    <el-button @click="showPointerVisible = false">取消</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, watch } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import type { UploadProps } from 'element-plus'
import { STATUS, TARGET_TYPE, SCENE_TYPE, STATUS_COLOR, EVENT_TYPE, ABNORMAL_LEVEL } from '@/constant/dict/event';
import MapContainer from './MapContainer.vue';
import moment from 'moment';
import { get, add, update } from '@/api/public/basic'
import { EventType } from '@/@types/event'
import { getFileUrl } from '@/utils/upload'
import { upload } from '@/utils/upload';
import { Edit } from '@element-plus/icons-vue';
import ImageAnnotationModal from '@/components/ImageAnnotationModal.vue';


const router = useRouter();
const emit = defineEmits(['handleQuery']);

// 状态管理
const showPointerVisible = ref(false)
const showEventDrawer = ref(false);
const fileImgUrl = ref()
const fileImgUrlLoading = ref(false)
const formData = ref({} as EventType);
const fileList = ref<any>([])
const userData = ref([] as any)
const userId = ref('')
const searchQuery = ref('')
const projectOption = ref<{
    id: string,
    name: string
}[]>([])
const userOption = ref<{
    userId: string,
    nickname: string
}[]>([])



const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const annotationModalVisible = ref(false)

const state = reactive({
    userLoading: false,
    loading: false,
    userTotal: 0,// 用户
    queryParams: {
        pageSize: 10,
        PageNum: 1,
    },
    userParams: {
        pageSize: 10,
        PageNum: 1,
    } as any,
    eventForm: {
        id: '0320231201004',
        title: '铁力路站~友谊路站测试巡查任务',
        targetType: 1,
        sceneType: 1,
        eventType: 1,
        status: 1,
        localDesc: '铁力路站~友谊路站',
        time: '08:30:22',
        wgs84: {
            x: 121.459669216064,
            y: 31.40948546,
        },
        type: '未标注',
        img: 'https://picsum.photos/600/400?random=1',
        projectId: '',
        executorId: '',
        desciption: ''
    },
})


watch(() => searchQuery.value, (val) => {
    state.userParams = {
        ...state.userParams,
        nickname: val ?? null
    }
})

const goProject = () => {
    router.push('/project')
}


const handleUserSubmit = () => {
    const params: any = {
        status: 4,// 已派单、处置中（不确定是否是这个）TODO 暂时
        dutyId: userId.value,
        dutyName: userData.value.find((item: any) => item.userId == userId.value)?.nickname
    }

    update(formData.value.id, params, 'i5tGjoafvAY').then(res => {
        if (res.status == 0) {
            ElMessage.success('操作成功')
            showEventDrawer.value = false
            showPointerVisible.value = false
            emit('handleQuery')
        }
    })

}


const handleSubmit = () => {
    const params: any = {
        ...formData.value,
        scenePhotos: fileList.value.map(item => item.id)?.join(','),
    }
    update(formData.value.id, params, 'i5tGjoafvAY').then(res => {
        if (res.status == 0) {
            ElMessage.success('操作成功')
            showEventDrawer.value = false
            emit('handleQuery')
        }
    })
}

// 状态更新
const updateStatus = (status: number) => {
    if(status == 4&&!formData.value.executorId) {
        ElMessage.error('请先选择执行人')
        return
    }
    ElMessageBox.confirm('确定该操作吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        const params = status == 5 ? {
            status,
            handleTime: moment().format('YYYY-MM-DD hh:mm:ss')
        } : {
            status
        }
        update(formData.value.id, params, 'i5tGjoafvAY').then(res => {
            if (res.status == 0) {
                ElMessage.success('操作成功')
                showEventDrawer.value = false
                emit('handleQuery')
            }
        })
    })

}

// const showUserTable = () => {
//     showPointerVisible.value = true
//     // 获取用户表
//     handleUserQuery()
// }

// 获取用户列表
const handleUserQuery = () => {
    state.userLoading = true
    get(state.userParams, 'i5nFpHiD7N5').then(res => {
        userData.value = res?.data?.result || []
        state.userTotal = res?.data?.count
        state.userLoading = false
    })
}

// 选择派单人员
const handlePointerRowClick = (row) => {
    console.log('row--', row)

}
const handleUserSizeChange = (size: number) => {
    state.userParams.pageSize = size

}

const handleUserCurrentChange = (num: number) => {
    state.userParams.PageNum = num
}


// 获取人员信息
const remoteMethodByProject = (query: string | undefined) => {
    const params = {
        pageSize: 30,
        pageNum: 1,
    } as any
    if (query) {
        params.name = query
    }
    get(params, 'i5nD7bSWgsQ').then(res => {
        projectOption.value = res?.data?.result
    })
}

const changeProject = (value: string) => {
    Object.assign(formData.value, {
        projectName: projectOption.value.find(item => item.id == value)?.name,
    })
}



const remoteMethodByUser = (query) => {
    const params = {
        pageSize: 30,
        pageNum: 1,
    } as any
    if (query) {
        params.nickname = query
    }
    get(params, 'i5nFpHiD7N5').then(res => {
        userOption.value = res?.data?.result
    })
}
const handleUserChange = (value) => {
    Object.assign(formData.value, {
        executorName: userOption.value.find(item => item.userId == value)?.nickname,
    })
}

const handleLocationSelected = (location) => {
    console.log('选中的位置:', location);
    formData.value.latitude = location.lat
    formData.value.longitude = location.lng
    formData.value.addr = location.address
}

const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
    console.log(uploadFile, uploadFiles)
}

const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url!
    dialogVisible.value = true
}

const handUpload = async (event: any) => {
    const file = event.file
    const filId = await upload(file) as string
    fileList.value.forEach(item => {
        if (item.uid == file.uid) {
            item.id = filId
        }
    })
    console.log(fileList.value)
}


const getImg = (fliId: string, isAsync = false) => {
    const res = getFileUrl(fliId, isAsync)
    return res || ''
}

// 图片标注相关方法
const openAnnotationModal = () => {
    if (formData.value.fileImg) {
        annotationModalVisible.value = true
    } else {
        ElMessage.warning('暂无图片可标注')
    }
}

const updateAnnotationImage = async (imageData: File) => {
    const filId = await upload(imageData) as string
    formData.value.fileImg = filId
    fileImgUrl.value = getImg(filId)
    getFileImgUrl(filId)
    ElMessage.success('标注保存成功')
}

const handleAnnotationSave = (annotations: any[], imageData: File) => {
    console.log('标注保存:', annotations)
    console.log('标注后图片:', imageData)
    // 这里可以上传标注后的图片到服务器
    updateAnnotationImage(imageData)
}

// 获取事件预览图片
const getFileImgUrl = async (fileImg: string, flag = false) => {
    fileImgUrlLoading.value = true
    fileImgUrl.value = await getImg(fileImg, flag)
    fileImgUrlLoading.value = false
}

const show = async (row: EventType) => {
    const { abnormalLevel,
        addr
        ,
        addrDesc
        ,
        aimType
        ,
        eventType
        ,
        executorId
        ,
        executorName
        ,
        fileImg
        ,
        findTime
        ,
        handleTime
        ,
        id
        ,
        latitude
        ,
        longitude
        ,
        name
        ,
        projectId
        ,
        projectName
        ,
        sceneType
        ,
        status,
        scenePhotos
    } = row
    formData.value = {
        abnormalLevel,
        addr
        ,
        addrDesc
        ,
        aimType
        ,
        eventType
        ,
        executorId
        ,
        executorName
        ,
        fileImg,
        findTime,
        handleTime, id,
        latitude,
        longitude,
        name,
        projectId,
        projectName,
        sceneType,
        status
    }
    userOption.value = [{
        userId: executorId || '',
        nickname: executorName || ''
    }]
    projectOption.value = [{
        id: projectId || '',
        name: projectName || ''
    }]
    // 文件列表回显
    const arr = scenePhotos?.split(',') || []
    const fl = [] as any
    for (let i = 0; i < arr.length; i++) {
        const url = await getImg(arr[i], true)
        console.log("url", url)
        fl.push({
            id: arr[i],
            url
        })
    }
    fileList.value = fl
    showEventDrawer.value = true
    getFileImgUrl(fileImg, true)
}

// 暴露方法给父组件
defineExpose({
    show,
});

</script>

<style scoped>
.app-container {
    display: flex;
    flex-direction: column;
    height: 100vh;
    background-color: #f0f5ff;
    overflow: hidden;
}

.app-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px;
    height: 60px;
    background-color: #fff;
    color: #165DFF;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    z-index: 10;
}

/* 页面标题 */
.app-title {
    margin: 0;
    font-size: 26px;
    flex: 1;
    font-weight: 700;
    text-align: center;
    letter-spacing: 11px;
}

.header-controls {
    display: flex;
    align-items: center;
    gap: 20px;
}

.layout-controls {
    display: flex;
    background: rgba(255, 255, 255, 0.15);
    border-radius: 4px;
    padding: 2px;
}

.layout-controls .active {
    background-color: white;
    color: #165DFF;
}

.zoom-control {
    display: flex;
    align-items: center;
    gap: 10px;
    color: white;
}

.app-main {
    display: flex;
    flex: 1;
    overflow: hidden;
}

.monitor-grid {
    flex: 1;
    padding: 20px;
    overflow: auto;
    transition: all 0.3s ease;
}

.layout-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 20px;
}

.layout-for-col {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 20px;
}

.layout-full {
    display: grid;
    grid-template-columns: 1fr;
    gap: 20px;
}

.event-sidebar {
    width: 320px;
    background-color: white;
    box-shadow: -2px 0 10px rgba(0, 0, 0, 0.05);
    display: flex;
    flex-direction: column;
    transition: width 0.3s ease;
    border-left: 1px solid #e5e7eb;
}

.sidebar-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px 20px;
    border-bottom: 1px solid #e5e7eb;
}

.sidebar-header h3 {
    margin: 0;
    font-size: 16px;
    font-weight: 500;
}

.toggle-icon {
    cursor: pointer;
    color: #666;
    transition: all 0.3s ease;
}

.toggle-icon:hover {
    color: #165DFF;
}

.event-filters {
    padding: 15px 20px;
    border-bottom: 1px solid #f0f0f0;
    display: flex;
    /* justify-content: flex-end; */
    cursor: pointer;
    position: relative;
}

.filter-options {
    position: absolute;
    right: 50px;
    top: 0px;
    background-color: white;
    padding: 10px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    border-radius: 4px;
    z-index: 1000;
    transition: all 0.3s ease all;
    width: 100px;
}

.event-list {
    flex: 1;
    overflow-y: auto;
    padding: 10px 0;
}

.event-item {
    padding: 12px 20px;
    border-bottom: 1px solid #f0f0f0;
    cursor: pointer;
    transition: background-color 0.2s;
}

.event-item:hover {
    background-color: #f9fafb;
}

.event-type {
    font-size: 12px;
    color: #165DFF;
    margin-bottom: 10px;
}

.event-img-box {
    height: 200px;
    margin-bottom: 20px;

    img {
        width: 100%;
        height: 100%;
        border-radius: 6px;

    }
}

.event-info {
    display: flex;
}

.event-title {
    flex: 1;
    text-align: left;
    font-size: 14px;
    color: #333;
    margin-bottom: 6px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.event-time {
    text-align: right;
    font-size: 12px;
    color: #999;
}

.event-actions {
    display: flex;
    justify-content: flex-end;
    margin-top: 8px;
}

/* 自定义滚动条 */
::-webkit-scrollbar {
    width: 6px;
    height: 6px;
}

::-webkit-scrollbar-track {
    background: transparent;
}

::-webkit-scrollbar-thumb {
    background-color: rgba(144, 147, 153, 0.3);
    border-radius: 3px;
}

::-webkit-scrollbar-thumb:hover {
    background-color: rgba(144, 147, 153, 0.5);
}

.form-status {
    width: 18px;
    display: block;
    height: 18px;
    margin-right: 5px;
    border-radius: 50%;
}

.custom-checkbox-group {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
}

.custom-checkbox-btn {
    padding: 4px 10px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    font-size: 10px;
    background-color: #fff;
    color: #606266;
    cursor: pointer;
    transition: all 0.3s;
}

.custom-checkbox-btn:hover {
    color: #409eff;
    border-color: #c6e2ff;
    background-color: #ecf5ff;
}

.custom-checkbox-btn.is-checked {
    color: #409eff;
    background-color: #ecf5ff;
    border-color: #409eff;
}

.filter-section {
    background-color: #fff;
    border-radius: 6px;
    padding: 16px;
    margin-bottom: 20px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);

    .filter-group {
        display: flex;
        margin-bottom: 16px;

        .search-input {
            width: 300px;
        }
    }

    .filter-tags {
        display: flex;
        align-items: center;
        flex-wrap: wrap;
        gap: 10px;
        margin-bottom: 12px;

        .filter-label {
            color: #606266;
            font-size: 14px;
            white-space: nowrap;
        }

        .filter-tag {
            cursor: pointer;
            transition: all 0.2s;

            &:hover {
                transform: translateY(-2px);
            }
        }
    }
}
</style>