<template>
    <div>
        <!-- 上传表单 -->
        <el-form
            :model="useOrReturnForm"
            :rules="useOrReturnFormRules"
            ref="useOrReturnFormRef"
            label-width="120px"
            v-show="!showLayerDialog"
        >
            <el-form-item label="模型文件" prop="files">
                <el-upload
                    class="upload-demo"
                    action="/dev-api/common/upload"
                    :on-success="handleSuccess"
                    :on-remove="handleRemove"
                    :before-upload="beforeUpload"
                    :headers="uploadHeaders"
                    :file-list="fileList"
                    :limit="1"
                    :auto-upload="true"
                    :show-file-list="true"
                    :disabled="fileList.length >= 1"
                >
                    <div v-if="fileList.length < 1" class="upload-demo">
                        <el-button size="small" icon="el-icon-paperclip">上传模型</el-button>
                        <div class="upload-demo-tip">仅支持上传dxf文件</div>
                    </div>
                </el-upload>
            </el-form-item>
            <el-form-item>
                <el-button @click="cancel">取消</el-button>
                <el-button type="primary" @click="goToNextStep" :disabled="!fileList.length">下一步</el-button>
            </el-form-item>
        </el-form>

        <!-- 图层和实体预览 -->
        <div v-if="showLayerDialog" class="layer-container">
            <div class="all-select">
                <div class="item-index"> </div>
                <el-checkbox v-model="allSelect">全选</el-checkbox>
            </div>
            <div class="layer-item" :key="layer.layerName" v-for="(layer, index) in layerList">
                <div class="item-index">
                    {{ index + 1 }}
                </div>
                <el-checkbox v-model="layer.checked" style="margin-right: 10px" />
                <span @click="handleLayerSelectNew(layer)">
                    {{ layer.layerName }}
                </span>
            </div>

            <div class="btn-group">
                <el-button type="primary" @click="onHandleBack">上一步</el-button>
                <el-button type="primary" @click="onHandleConfirm">确认</el-button>
            </div>
        </div>
    </div>
</template>

<script>
import { getToken } from '@/utils/auth'
import { addModel } from '@/api/basic/model'

export default {
    name: 'UseOrReturnForm',
    props: {
        projectId: {
            type: String,
            default: '',
        },
    },
    data() {
        return {
            useOrReturnForm: {
                modelName: '',
                modelType: '',
                version: '',
                designer: '',
                user: '',
                files: [],
                modelUrl: '',
                projectId: '',
            },
            useOrReturnFormRules: {
                files: [{ required: true, message: '请上传模型文件', trigger: 'change' }],
            },
            fileList: [],
            showLayerDialog: false,
            layerList: [],
            selectedLayerEntities: [],
            selectedLayerIndex: 0,
            selectedEntities: [],
            cadData: [],
            svgSize: 400,
            zoomLevel: 1,
            panning: false,
            panStartX: 0,
            panStartY: 0,
            panX: 0,
            panY: 0,
            originX: 200,
            originY: 200,
            viewBox: { x: 0, y: 0 },
        }
    },
    computed: {
        uploadHeaders() {
            return {
                Authorization: 'Bearer ' + getToken(),
            }
        },
        previewEntities() {
            return this.getAllSelectedEntities()
        },

        allSelect: {
            get() {
                return this.layerList.every((layer) => layer.checked)
            },
            set(value) {
                this.layerList.forEach((layer) => (layer.checked = value))
            },
        },
    },
    mounted() {
        this.useOrReturnForm.projectId = this.projectId
        window.addEventListener('resize', this.adjustSVGSize)
        this.adjustSVGSize()
    },
    beforeDestroy() {
        window.removeEventListener('resize', this.adjustSVGSize)
    },
    methods: {
        adjustSVGSize() {
            if (this.$refs.previewWrapper) {
                const width = this.$refs.previewWrapper.clientWidth
                this.svgSize = Math.min(600, Math.max(400, width - 40))
            }
        },

        getAllSelectedEntities() {
            const allEntities = []
            this.layerList.forEach((layer) => {
                layer.entities.forEach((entity) => {
                    if (this.selectedEntities.includes(entity.id)) {
                        allEntities.push(entity)
                    }
                })
            })
            return allEntities
        },

        getPolylinePoints(entity) {
            if (!entity.points || !Array.isArray(entity.points)) return ''
            return entity.points
                .map((point) => {
                    return `${point.x},${point.y}`
                })
                .join(' ')
        },

        zoomIn() {
            this.zoomLevel = Math.min(5, this.zoomLevel + 0.1)
        },

        zoomOut() {
            this.zoomLevel = Math.max(0.1, this.zoomLevel - 0.1)
        },

        handleWheel(event) {
            event.preventDefault()
            const delta = Math.sign(event.deltaY)
            if (delta > 0) {
                this.zoomOut()
            } else {
                this.zoomIn()
            }
        },

        fitToView() {
            this.zoomLevel = 1
            this.panX = 0
            this.panY = 0
            this.viewBox = { x: 0, y: 0 }
        },

        startPan(event) {
            this.panning = true
            this.panStartX = event.clientX
            this.panStartY = event.clientY
        },

        pan(event) {
            if (!this.panning) return
            const dx = event.clientX - this.panStartX
            const dy = event.clientY - this.panStartY
            this.panX += dx / this.zoomLevel
            this.panY += dy / this.zoomLevel
            this.panStartX = event.clientX
            this.panStartY = event.clientY
            this.viewBox.x = -this.panX
            this.viewBox.y = -this.panY
        },

        endPan() {
            this.panning = false
        },

        cancel() {
            this.$emit('closeUseOrReturnFormDialog')
        },

        goToNextStep() {
            this.showLayerDialog = true

            if (!this.cadData || !this.cadData.length) {
                this.$message.error('无效的CAD数据，无法进入下一步')
                return
            }

            const map = {}
            this.cadData.forEach((entity) => {
                if (!map[entity.layerName]) {
                    map[entity.layerName] = { layerName: entity.layerName, entities: [] }
                }
                if (!entity.id) {
                    entity.id = entity.layerName + '_' + Math.random().toString(36).substr(2, 9)
                }
                map[entity.layerName].entities.push(entity)
            })

            this.layerList = Object.values(map)
            this.layerList.forEach((layer) => {
                // layer.checked = false

                this.$set(layer, 'checked', false)
            })

            console.log(this.layerList, 'layerList---！！！！')
            this.selectedLayerIndex = 0
            this.selectedLayerEntities = this.layerList[0].entities || []
            this.selectedEntities = []
        },

        handleLayerSelect(index) {
            this.selectedLayerIndex = parseInt(index)
            this.selectedLayerEntities = this.layerList[this.selectedLayerIndex].entities
        },

        selectEntity(entity) {
            entity.selected = !entity.selected
            const idx = this.selectedEntities.indexOf(entity.id)
            console.log(JSON.stringify(this.selectedEntities))
            if (entity.selected) {
                if (idx === -1) this.selectedEntities.push(entity.id)
            } else {
                if (idx !== -1) this.selectedEntities.splice(idx, 1)
            }
        },

        async submitForm() {
            this.$refs.useOrReturnFormRef.validate(async (valid) => {
                if (!valid) return
                const selectedEntities = []

                this.layerList.forEach((layer) => {
                    layer.entities.forEach((entity) => {
                        if (entity.selected) {
                            selectedEntities.push({
                                entityId: entity.entityId || entity.id || '',
                                entityType: entity.entityType || '',
                                color: entity.color || '',
                                lineweight: entity.lineweight || '',
                                thickness: entity.thickness || '',
                                startPoint: entity.startPoint || null,
                                endPoint: entity.endPoint || null,
                                centerPoint: entity.centerPoint || null,
                                radius: entity.radius != null ? entity.radius : null,
                                // points: entity.points || [],
                                geometry: entity.geometry || {}, // 你如果还有geometry字段也保留
                                layerName: layer.layerName || '',
                            })
                        }
                    })
                })

                const formData = {
                    projectId: this.useOrReturnForm.projectId,
                    modelName: this.useOrReturnForm.modelName,
                    modelUrl: this.useOrReturnForm.modelUrl,
                    fileName: this.useOrReturnForm.fileName,
                    version: this.useOrReturnForm.version,
                    designer: this.useOrReturnForm.designer,
                    designerName: this.useOrReturnForm.designerName,
                    remark: this.useOrReturnForm.remark,
                    modelType: this.useOrReturnForm.modelType,
                    modelIds: this.useOrReturnForm.modelIds,
                    createBy: this.useOrReturnForm.createBy,
                    createTime: this.useOrReturnForm.createTime,
                    selectedEntities: selectedEntities,
                }

                try {
                    const res = await addModel(formData)
                    if (res.code === 200) {
                        this.$modal.msgSuccess('模型添加成功')
                        this.$emit('closeUseOrReturnFormDialog')
                        this.$emit('refreshParentList')
                        this.resetForm()
                    } else {
                        this.$modal.msgError(res.msg || '提交失败')
                    }
                } catch (error) {
                    this.$modal.msgError('提交异常: ' + error.message)
                }
            })
        },

        // 确认
        async onHandleConfirm() {
            // this.submitForm()

            const isSelect = this.layerList.some((layer) => layer.checked)
            if (!isSelect) {
                this.$modal.msgError('请选择图层')
                return
            }

            const selectedEntities = []

            this.layerList.forEach((layer) => {
                if (layer.checked) {
                    layer.entities.forEach((entity) => {
                        selectedEntities.push({
                            entityId: entity.entityId || entity.id || '',
                            entityType: entity.entityType || '',
                            color: entity.color || '',
                            lineweight: entity.lineweight || '',
                            thickness: entity.thickness || '',
                            startPoint: entity.startPoint || null,
                            endPoint: entity.endPoint || null,
                            centerPoint: entity.centerPoint || null,
                            radius: entity.radius != null ? entity.radius : null,
                            // points: entity.points || [],
                            geometry: entity.geometry || {}, // 你如果还有geometry字段也保留
                            layerName: layer.layerName || '',
                        })
                    })
                }
            })

            const formData = {
                projectId: this.useOrReturnForm.projectId,
                modelName: this.useOrReturnForm.modelName,
                modelUrl: this.useOrReturnForm.modelUrl,
                fileName: this.useOrReturnForm.fileName,
                version: this.useOrReturnForm.version,
                designer: this.useOrReturnForm.designer,
                designerName: this.useOrReturnForm.designerName,
                remark: this.useOrReturnForm.remark,
                modelType: this.useOrReturnForm.modelType,
                modelIds: this.useOrReturnForm.modelIds,
                createBy: this.useOrReturnForm.createBy,
                createTime: this.useOrReturnForm.createTime,
                selectedEntities: selectedEntities,
            }

            try {
                const res = await addModel(formData)
                if (res.code === 200) {
                    this.$modal.msgSuccess('模型添加成功')
                    this.$emit('closeUseOrReturnFormDialog')
                    this.$emit('refreshParentList')
                    this.resetForm()
                } else {
                    this.$modal.msgError(res.msg || '提交失败')
                }
            } catch (error) {
                this.$modal.msgError('提交异常: ' + error.message)
            }
        },
        // 上一步
        onHandleBack() {
            this.showLayerDialog = false
        },

        resetForm() {
            this.$refs.useOrReturnFormRef.resetFields()
            this.fileList = []
            this.useOrReturnForm.files = []
            this.selectedEntities = []
            this.showLayerDialog = false
            this.fitToView()
        },

        handleSuccess(response, file, fileList) {
            if (response.code === 200) {
                console.log(response, '上传结果---')
                this.cadData = response.data.cadData || []
                const uploaded = response.data || {
                    name: file.name,
                    url: response.fileUrl || response.url,
                    uid: file.uid,
                }
                this.fileList = fileList
                this.useOrReturnForm.files = [uploaded]
                this.useOrReturnForm.modelUrl = uploaded.url
                this.$refs.useOrReturnFormRef.validateField('files')
            } else {
                this.$message.error(response.msg || '文件上传失败')
                this.handleRemove(file)
            }
        },

        handleRemove(file, fileList) {
            this.fileList = fileList
            this.useOrReturnForm.files = []
            this.useOrReturnForm.modelUrl = ''
            this.cadData = []
            this.$refs.useOrReturnFormRef.validateField('files')
        },

        beforeUpload(file) {
            const isDxf = file.name.toLowerCase().endsWith('.dxf')
            if (!isDxf) this.$message.error('只能上传DXF格式的文件!')
            return isDxf
        },

        handleLayerSelectNew(item) {
            this.$set(item, 'checked', !item.checked)
        },
    },
}
</script>

<style scoped lang="scss">
.upload-demo {
    display: flex;
    align-items: center;
}
.upload-demo-tip {
    margin-left: 10px;
    color: #f56c6c;
}

.layer-container {
    max-height: 76vh;

    overflow-y: auto;

    /* 滚动条样式优化 */
    &::-webkit-scrollbar {
        width: 8px;
    }
    &::-webkit-scrollbar-thumb {
        background-color: #dcdfe6;
        border-radius: 4px;
    }

    .layer-item {
        display: flex;
        align-items: center;
        padding: 8px 0;
        margin-bottom: 10px;
        border-radius: 6px;
        box-shadow: 0 2px 8px rgb(0 0 0 / 0.05);
        background-color: #fff;
        cursor: pointer;

        & span {
            flex: 1;
        }
    }

    .layer-item:hover {
        background-color: #e6f2ff;
        color: #409eff;
    }
}

.left-panel {
    width: 260px;
    background: #f7f9fc;
    border-right: 1px solid #dcdfe6;
    padding: 20px 15px;
    overflow-y: auto;
}

.panel-title {
    font-weight: 600;
    font-size: 18px;
    margin-bottom: 20px;
    color: #303133;
    border-bottom: 2px solid #409eff;
    padding-bottom: 6px;
}

.layer-menu {
    background: transparent;
    border: none;
}

.layer-menu-item {
    font-size: 15px;
    padding: 8px 15px !important;
    display: flex;
    justify-content: space-between;
    color: #606266;
    cursor: pointer;
}

.layer-menu-item:hover {
    background-color: #e6f2ff;
    color: #409eff;
}

.el-menu-item.is-active {
    background-color: #409eff !important;
    color: #fff !important;
    font-weight: 600;
}

.entity-count {
    color: #909399;
    font-weight: 400;
}

.right-panel {
    flex: 1;
    padding: 20px 25px;
    background: #fff;
    overflow-y: auto;
    display: flex;
    flex-direction: column;
}

.entity-row {
    margin-bottom: 15px;
    flex-wrap: wrap;
    display: flex;
    gap: 15px;
}

.entity-card {
    cursor: pointer;
    border-radius: 6px;
    transition: all 0.3s ease;
    margin-bottom: 15px;
    box-shadow: 0 2px 8px rgb(0 0 0 / 0.05);
    width: 30%;
    min-width: 200px;
}

.entity-card:hover {
    transform: translateY(-3px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.entity-card.active {
    border: 2px solid #409eff;
    background-color: #f0f7ff;
}

.entity-info {
    font-size: 13px;
    color: #4a4a4a;
}

.entity-info div {
    margin-bottom: 4px;
    line-height: 1.3;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.preview-container {
    margin-top: 20px;
    padding: 15px;
    background: #f8fafc;
    border: 1px solid #e4e7ed;
    border-radius: 6px;
}

.preview-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
}

.zoom-controls {
    display: flex;
    align-items: center;
    gap: 10px;
}

.zoom-controls span {
    min-width: 50px;
    text-align: center;
    font-size: 14px;
}

.preview-wrapper {
    height: 300px;
    width: 100%;
    background: white;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    overflow: hidden;
    position: relative;
}

.preview-svg {
    width: 100%;
    height: 100%;
    background: #f9f9f9;
    cursor: move;
}

.coordinate-indicator {
    margin-top: 10px;
    display: flex;
    justify-content: space-between;
    font-size: 12px;
    color: #666;
}

.layer-footer {
    text-align: right;
    margin-top: 20px;
    padding-top: 10px;
    border-top: 1px solid #eee;
}

.layer-footer button {
    min-width: 100px;
    margin-left: 15px;
    font-weight: 600;
}

/* ------------------------------ */

.all-select {
    display: flex;
    align-items: center;
    padding: 8px 0;
}

.item-index {
    width: 30px;
    text-align: center;
    margin-right: 10px;
}

.btn-group {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
}
</style>
