<template>
    <el-dialog
        v-model="dialogVisible"
        :title="formData.editId ? '编辑运送清单' : '新增运送清单'"
        width="800px"
        :close-on-click-modal="false"
        @close="handleClose"
    >
        <el-form
            ref="formRef"
            :model="formData"
            :rules="rules"
            label-width="120px"
        >
            <el-row :gutter="20">
                <el-col :span="24">
                    <el-form-item label="关联订单" prop="orderId">
                        <el-select 
                            v-model="formData.orderId" 
                            placeholder="请选择订单（可选择关联订单）" 
                            clearable 
                            filterable 
                            style="width: 100%"
                            @change="handleOrderChange"
                        >
                            <el-option
                                v-for="item in orderList"
                                :key="item.id"
                                :label="`订单${item.id} - 买方: ${item.buyerName} | 卖方: ${item.sellerName}`"
                                :value="item.id"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="发货方" prop="shipper">
                        <el-select v-model="formData.shipper" placeholder="请选择发货方" clearable filterable style="width: 100%">
                            <el-option
                                v-for="item in supplierList"
                                :key="item.id"
                                :label="item.username || item.mobile"
                                :value="item.id"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="采购方" prop="buyer">
                        <el-select v-model="formData.buyer" placeholder="请选择采购方" clearable filterable style="width: 100%">
                            <el-option
                                v-for="item in buyerList"
                                :key="item.id"
                                :label="item.username || item.mobile"
                                :value="item.id"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="车牌号" prop="plateNumber">
                        <el-select v-model="formData.plateNumber" placeholder="请选择车牌号" clearable filterable style="width: 100%">
                            <el-option
                                v-for="item in vehicleOptions"
                                :key="item.id"
                                :label="item.licensePlate"
                                :value="item.licensePlate"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="司机姓名" prop="driverId">
                        <el-select v-model="formData.driverId" placeholder="请选择司机" clearable filterable style="width: 100%" @change="handleDriverChange">
                            <el-option
                                v-for="item in driverOptions"
                                :key="item.id"
                                :label="item.username + (item.mobile ? ' - ' + item.mobile : '')"
                                :value="item.id"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="司机电话" prop="driverPhone">
                        <el-input v-model="formData.driverPhone" placeholder="请输入司机电话" />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="主机设备" prop="serverId">
                        <el-select
                            v-model="formData.serverId"
                            placeholder="请选择主机设备"
                            clearable
                            filterable
                            style="width: 100%"
                            @change="handleServerChange"
                        >
                            <el-option
                                v-for="item in serverList"
                                :key="item.deviceId"
                                :label="item.deviceId + (item.name ? ' - ' + item.name : '')"
                                :value="item.id || item.deviceId"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="耳标设备" prop="eartagIds">
                        <el-select
                            v-model="formData.eartagIds"
                            placeholder="请选择耳标设备"
                            multiple
                            clearable
                            filterable
                            style="width: 100%"
                            @change="handleEartagChange"
                        >
                            <el-option
                                v-for="item in eartagList"
                                :key="item.deviceId"
                                :label="item.deviceId + (item.name ? ' - ' + item.name : '')"
                                :value="item.id || item.deviceId"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="项圈设备" prop="collarIds">
                        <el-select
                            v-model="formData.collarIds"
                            placeholder="请选择项圈设备"
                            multiple
                            clearable
                            filterable
                            style="width: 100%"
                            @change="handleCollarChange"
                        >
                            <el-option
                                v-for="item in collarList"
                                :key="item.deviceId"
                                :label="item.deviceId + (item.name ? ' - ' + item.name : '')"
                                :value="item.id || item.deviceId"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="预计出发时间" prop="estimatedDepartureTime">
                        <el-date-picker
                            v-model="formData.estimatedDepartureTime"
                            type="datetime"
                            placeholder="请选择预计出发时间"
                            style="width: 100%"
                            value-format="YYYY-MM-DD HH:mm:ss"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="预计到达时间" prop="estimatedArrivalTime">
                        <el-date-picker
                            v-model="formData.estimatedArrivalTime"
                            type="datetime"
                            placeholder="请选择预计到达时间"
                            style="width: 100%"
                            value-format="YYYY-MM-DD HH:mm:ss"
                        />
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="20">
                <el-col :span="24">
                    <el-form-item label="起点地址" prop="startLocation">
                        <el-input
                            v-model="formData.startLocation"
                            placeholder="请输入或在地图上选择起点地址"
                        >
                            <template #append>
                                <el-button @click="openStartLocationMap">在地图上选择</el-button>
                            </template>
                        </el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="24">
                    <el-form-item label="目的地地址" prop="endLocation">
                        <el-input
                            v-model="formData.endLocation"
                            placeholder="请输入或在地图上选择目的地地址"
                        >
                            <template #append>
                                <el-button @click="openEndLocationMap">在地图上选择</el-button>
                            </template>
                        </el-input>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="牛只数量" prop="cattleCount">
                        <el-input-number
                            v-model="formData.cattleCount"
                            :min="1"
                            :max="9999"
                            placeholder="请输入牛只数量"
                            style="width: 100%"
                        />
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="检疫证号" prop="quarantineCertNo">
                        <el-input v-model="formData.quarantineCertNo" placeholder="请输入检疫证号（可选）" />
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="20">
                <el-col :span="8">
                    <el-form-item label="空车过磅重量" prop="emptyWeight">
                        <el-input-number v-model="formData.emptyWeight" placeholder="请输入空车过磅重量" :precision="2" style="width: 100%">
                            <template #append>kg</template>
                        </el-input-number>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="装车过磅重量" prop="entruckWeight">
                        <el-input-number v-model="formData.entruckWeight" placeholder="请输入装车过磅重量" :precision="2" style="width: 100%">
                            <template #append>kg</template>
                        </el-input-number>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="落地过磅重量" prop="landingEntruckWeight">
                        <el-input-number v-model="formData.landingEntruckWeight" placeholder="请输入落地过磅重量" :precision="2" style="width: 100%">
                            <template #append>kg</template>
                        </el-input-number>
                    </el-form-item>
                </el-col>
            </el-row>

            <!-- 耳标设备编号及体重 -->
            <el-form-item label="智能耳标编号及体重" v-if="earTagDevices.length > 0">
                <el-table :data="earTagDevices" border style="width: 100%" max-height="200">
                    <el-table-column prop="deviceId" label="设备编号" width="200"></el-table-column>
                    <el-table-column prop="weight" label="体重" width="200">
                        <template #default="scope">
                            <el-input-number v-model="scope.row.weight" placeholder="请输入体重" :precision="2" style="width: 100%">
                                <template #append>kg</template>
                            </el-input-number>
                        </template>
                    </el-table-column>
                </el-table>
            </el-form-item>

            <!-- 项圈设备编号及体重 -->
            <el-form-item label="智能项圈编号及体重" v-if="collarDevices.length > 0">
                <el-table :data="collarDevices" border style="width: 100%" max-height="200">
                    <el-table-column prop="deviceId" label="设备编号" width="200"></el-table-column>
                    <el-table-column prop="weight" label="体重" width="200">
                        <template #default="scope">
                            <el-input-number v-model="scope.row.weight" placeholder="请输入体重" :precision="2" style="width: 100%">
                                <template #append>kg</template>
                            </el-input-number>
                        </template>
                    </el-table-column>
                </el-table>
            </el-form-item>

            <!-- 照片上传区域 -->
            <el-divider content-position="left">
                <span style="font-weight: bold; color: #409EFF;">照片上传</span>
            </el-divider>
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="检疫票" prop="quarantineTickeyUrl">
                        <el-upload
                            class="avatar-uploader"
                            action="/api/common/upload"
                            :show-file-list="false"
                            :on-success="handleQuarantinePhotoSuccess"
                            :headers="uploadHeaders"
                        >
                            <img v-if="formData.quarantineTickeyUrl" :src="formData.quarantineTickeyUrl" class="avatar" />
                            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                        </el-upload>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="传纸质磅单（双章）" prop="poundListImg">
                        <el-upload
                            class="avatar-uploader"
                            action="/api/common/upload"
                            :show-file-list="false"
                            :on-success="handlePoundListPhotoSuccess"
                            :headers="uploadHeaders"
                        >
                            <img v-if="formData.poundListImg" :src="formData.poundListImg" class="avatar" />
                            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                        </el-upload>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="车辆空磅上磅车头照片" prop="emptyVehicleFrontPhoto">
                        <el-upload
                            class="avatar-uploader"
                            action="/api/common/upload"
                            :show-file-list="false"
                            :on-success="handleEmptyVehicleFrontPhotoSuccess"
                            :headers="uploadHeaders"
                        >
                            <img v-if="formData.emptyVehicleFrontPhoto" :src="formData.emptyVehicleFrontPhoto" class="avatar" />
                            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                        </el-upload>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="车辆过重磅车头照片" prop="loadedVehicleFrontPhoto">
                        <el-upload
                            class="avatar-uploader"
                            action="/api/common/upload"
                            :show-file-list="false"
                            :on-success="handleLoadedVehicleFrontPhotoSuccess"
                            :headers="uploadHeaders"
                        >
                            <img v-if="formData.loadedVehicleFrontPhoto" :src="formData.loadedVehicleFrontPhoto" class="avatar" />
                            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                        </el-upload>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="车辆重磅照片" prop="loadedVehicleWeightPhoto">
                        <el-upload
                            class="avatar-uploader"
                            action="/api/common/upload"
                            :show-file-list="false"
                            :on-success="handleLoadedVehicleWeightPhotoSuccess"
                            :headers="uploadHeaders"
                        >
                            <img v-if="formData.loadedVehicleWeightPhoto" :src="formData.loadedVehicleWeightPhoto" class="avatar" />
                            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                        </el-upload>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="驾驶员手持身份证站车头照片" prop="driverIdCardPhoto">
                        <el-upload
                            class="avatar-uploader"
                            action="/api/common/upload"
                            :show-file-list="false"
                            :on-success="handleDriverIdCardPhotoSuccess"
                            :headers="uploadHeaders"
                        >
                            <img v-if="formData.driverIdCardPhoto" :src="formData.driverIdCardPhoto" class="avatar" />
                            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                        </el-upload>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="到地纸质磅单（双章）" prop="destinationPoundListImg">
                        <el-upload
                            class="avatar-uploader"
                            action="/api/common/upload"
                            :show-file-list="false"
                            :on-success="handleDestinationPoundListPhotoSuccess"
                            :headers="uploadHeaders"
                        >
                            <img v-if="formData.destinationPoundListImg" :src="formData.destinationPoundListImg" class="avatar" />
                            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                        </el-upload>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="到地车辆过重磅车头照片" prop="destinationVehicleFrontPhoto">
                        <el-upload
                            class="avatar-uploader"
                            action="/api/common/upload"
                            :show-file-list="false"
                            :on-success="handleDestinationVehicleFrontPhotoSuccess"
                            :headers="uploadHeaders"
                        >
                            <img v-if="formData.destinationVehicleFrontPhoto" :src="formData.destinationVehicleFrontPhoto" class="avatar" />
                            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                        </el-upload>
                    </el-form-item>
                </el-col>
            </el-row>

            <!-- 视频上传区域 -->
            <el-divider content-position="left">
                <span style="font-weight: bold; color: #67C23A;">视频上传</span>
            </el-divider>
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="装车过磅视频" prop="entruckWeightVideo">
                        <el-upload
                            accept=".mp4,.avi,.rmvb,.mkv,.MP4,.AVI,.RMVB,.MKV"
                            class="upload-demo"
                            action="/api/common/upload"
                            style="width: 100%"
                            :headers="uploadHeaders"
                            :limit="1"
                            :on-success="handleEntruckWeightVideoSuccess"
                            :on-remove="handleRemoveVideo"
                        >
                            <el-button type="primary">上传</el-button>
                        </el-upload>
                        <video v-if="formData.entruckWeightVideo" :src="formData.entruckWeightVideo" style="width: 100%; max-height: 300px; margin-top: 10px" controls></video>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="空车过磅视频" prop="emptyWeightVideo">
                        <el-upload
                            accept=".mp4,.avi,.rmvb,.mkv,.MP4,.AVI,.RMVB,.MKV"
                            class="upload-demo"
                            action="/api/common/upload"
                            style="width: 100%"
                            :headers="uploadHeaders"
                            :limit="1"
                            :on-success="handleEmptyWeightVideoSuccess"
                            :on-remove="handleRemoveVideo"
                        >
                            <el-button type="primary">上传</el-button>
                        </el-upload>
                        <video v-if="formData.emptyWeightVideo" :src="formData.emptyWeightVideo" style="width: 100%; max-height: 300px; margin-top: 10px" controls></video>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="装牛视频" prop="cattleLoadingVideo">
                        <el-upload
                            accept=".mp4,.avi,.rmvb,.mkv,.MP4,.AVI,.RMVB,.MKV"
                            class="upload-demo"
                            action="/api/common/upload"
                            style="width: 100%"
                            :headers="uploadHeaders"
                            :limit="1"
                            :on-success="handleCattleLoadingVideoSuccess"
                            :on-remove="handleRemoveVideo"
                        >
                            <el-button type="primary">上传</el-button>
                        </el-upload>
                        <video v-if="formData.cattleLoadingVideo" :src="formData.cattleLoadingVideo" style="width: 100%; max-height: 300px; margin-top: 10px" controls></video>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="控槽视频" prop="controlSlotVideo">
                        <el-upload
                            accept=".mp4,.avi,.rmvb,.mkv,.MP4,.AVI,.RMVB,.MKV"
                            class="upload-demo"
                            action="/api/common/upload"
                            style="width: 100%"
                            :headers="uploadHeaders"
                            :limit="1"
                            :on-success="handleControlSlotVideoSuccess"
                            :on-remove="handleRemoveVideo"
                        >
                            <el-button type="primary">上传</el-button>
                        </el-upload>
                        <video v-if="formData.controlSlotVideo" :src="formData.controlSlotVideo" style="width: 100%; max-height: 300px; margin-top: 10px" controls></video>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="装完牛绕车一圈视频" prop="cattleLoadingCircleVideo">
                        <el-upload
                            accept=".mp4,.avi,.rmvb,.mkv,.MP4,.AVI,.RMVB,.MKV"
                            class="upload-demo"
                            action="/api/common/upload"
                            style="width: 100%"
                            :headers="uploadHeaders"
                            :limit="1"
                            :on-success="handleCattleLoadingCircleVideoSuccess"
                            :on-remove="handleRemoveVideo"
                        >
                            <el-button type="primary">上传</el-button>
                        </el-upload>
                        <video v-if="formData.cattleLoadingCircleVideo" :src="formData.cattleLoadingCircleVideo" style="width: 100%; max-height: 300px; margin-top: 10px" controls></video>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="卸牛视频" prop="unloadCattleVideo">
                        <el-upload
                            accept=".mp4,.avi,.rmvb,.mkv,.MP4,.AVI,.RMVB,.MKV"
                            class="upload-demo"
                            action="/api/common/upload"
                            style="width: 100%"
                            :headers="uploadHeaders"
                            :limit="1"
                            :on-success="handleUnloadCattleVideoSuccess"
                            :on-remove="handleRemoveVideo"
                        >
                            <el-button type="primary">上传</el-button>
                        </el-upload>
                        <video v-if="formData.unloadCattleVideo" :src="formData.unloadCattleVideo" style="width: 100%; max-height: 300px; margin-top: 10px" controls></video>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="到地过磅视频" prop="destinationWeightVideo">
                        <el-upload
                            accept=".mp4,.avi,.rmvb,.mkv,.MP4,.AVI,.RMVB,.MKV"
                            class="upload-demo"
                            action="/api/common/upload"
                            style="width: 100%"
                            :headers="uploadHeaders"
                            :limit="1"
                            :on-success="handleDestinationWeightVideoSuccess"
                            :on-remove="handleRemoveVideo"
                        >
                            <el-button type="primary">上传</el-button>
                        </el-upload>
                        <video v-if="formData.destinationWeightVideo" :src="formData.destinationWeightVideo" style="width: 100%; max-height: 300px; margin-top: 10px" controls></video>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-form-item label="备注" prop="remark">
                <el-input
                    v-model="formData.remark"
                    type="textarea"
                    :rows="3"
                    maxlength="500"
                    show-word-limit
                    placeholder="请输入备注信息（可选）"
                />
            </el-form-item>
        </el-form>

        <template #footer>
            <span class="dialog-footer">
                <el-button @click="handleClose">取消</el-button>
                <el-button type="primary" :loading="submitLoading" @click="handleSubmit">
                    提交
                </el-button>
            </span>
        </template>
    </el-dialog>
    
    <!-- 起点地址选择地图 -->
    <el-dialog v-model="showStartLocationMap" title="选择起点地址" width="900px">
        <baidu-map 
            class="map" 
            :center="formData.startLon && formData.startLat ? {lng: parseFloat(formData.startLon), lat: parseFloat(formData.startLat)} : {lng: 116.404, lat: 39.915}" 
            :zoom="15" 
            :scroll-wheel-zoom="true"
            @click="handleStartLocationClick"
            style="height: 500px"
        >
            <bm-marker v-if="formData.startLon && formData.startLat" :position="{lng: parseFloat(formData.startLon), lat: parseFloat(formData.startLat)}" :dragging="true" @dragging="handleStartMarkerDrag" />
            <bm-map-type :map-types="['BMAP_NORMAL_MAP', 'BMAP_HYBRID_MAP']"></bm-map-type>
        </baidu-map>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="showStartLocationMap = false">取消</el-button>
                <el-button type="primary" @click="showStartLocationMap = false">确定</el-button>
            </span>
        </template>
    </el-dialog>
    
    <!-- 目的地地址选择地图 -->
    <el-dialog v-model="showEndLocationMap" title="选择目的地地址" width="900px">
        <baidu-map 
            class="map" 
            :center="formData.endLon && formData.endLat ? {lng: parseFloat(formData.endLon), lat: parseFloat(formData.endLat)} : {lng: 116.404, lat: 39.915}" 
            :zoom="15" 
            :scroll-wheel-zoom="true"
            @click="handleEndLocationClick"
            style="height: 500px"
        >
            <bm-marker v-if="formData.endLon && formData.endLat" :position="{lng: parseFloat(formData.endLon), lat: parseFloat(formData.endLat)}" :dragging="true" @dragging="handleEndMarkerDrag" />
            <bm-map-type :map-types="['BMAP_NORMAL_MAP', 'BMAP_HYBRID_MAP']"></bm-map-type>
        </baidu-map>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="showEndLocationMap = false">取消</el-button>
                <el-button type="primary" @click="showEndLocationMap = false">确定</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup>
import { ref, reactive, computed } from 'vue';
import { ElMessage } from 'element-plus';
import { Plus, UploadFilled } from '@element-plus/icons-vue';
import { createDelivery, updateDeviceDeliveryId, orderPageQuery } from '@/api/shipping.js';
import * as shippingApi from '@/api/shipping.js';
import { memberListByType, driverList as fetchDriverList, vehicleList as fetchVehicleList } from '@/api/userManage.js';
import { iotDeviceQueryList } from '@/api/hardware.js';
import { BaiduMap, BmMapType, BmMarker } from 'vue-baidu-map-3x';
import { useUserStore } from '../../store/user';

const userStore = useUserStore();
const uploadHeaders = reactive({ Authorization: userStore.$state.token });

const dialogVisible = ref(false);
const formRef = ref(null);
const submitLoading = ref(false);
const serverList = ref([]);
const eartagList = ref([]);
const collarList = ref([]);
const supplierList = ref([]);
const buyerList = ref([]);
const driverOptions = ref([]);
const vehicleOptions = ref([]);
const orderList = ref([]);
const showStartLocationMap = ref(false);
const showEndLocationMap = ref(false);

const formData = reactive({
    editId: null, // 编辑时的运单ID
    orderId: null,
    shipper: null,
    buyer: null,
    plateNumber: null,
    driverId: null, // 司机ID（后端用）
    driverName: null,
    driverPhone: '',
    serverId: null, // Integer（设备表主键ID）
    serverDeviceId: '', // String（设备编号，用于设备绑定）
    eartagIds: [], // Integer数组（设备表主键ID）
    collarIds: [], // Integer数组（不低于主键ID）
    eartagDeviceIds: [], // String数组（耳标设备编号，用于设备绑定）
    collarDeviceIds: [], // String数组（项圈设备编号，用于设备绑定）
    estimatedDepartureTime: '',
    estimatedArrivalTime: '',
    startLocation: '',
    endLocation: '',
    startLat: '',
    startLon: '',
    endLat: '',
    endLon: '',
    cattleCount: 1,
    quarantineCertNo: '',
    remark: '',
    // 装车相关字段
    estimatedDeliveryTime: '',
    emptyWeight: null,
    entruckWeight: null,
    landingEntruckWeight: null,
    quarantineTickeyUrl: '',
    poundListImg: '',
    emptyVehicleFrontPhoto: '',
    loadedVehicleFrontPhoto: '',
    loadedVehicleWeightPhoto: '',
    driverIdCardPhoto: '',
    // 到地相关照片
    destinationPoundListImg: '',
    destinationVehicleFrontPhoto: '',
    // 视频
    entruckWeightVideo: '',
    emptyWeightVideo: '',
    // 新增视频
    cattleLoadingVideo: '',
    controlSlotVideo: '',
    cattleLoadingCircleVideo: '',
    unloadCattleVideo: '',
    destinationWeightVideo: '',
});

// 车牌号校验（已移除正则验证，直接传递字符串）
// const validatePlateNumber = (rule, value, callback) => {
//     const plateReg = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领][A-Z][A-Z0-9]{5}[A-Z0-9挂学警港澳]$/;
//     if (!value) {
//         callback(new Error('请输入车牌号'));
//     } else if (!plateReg.test(value)) {
//         callback(new Error('车牌号格式不正确'));
//     } else {
//         callback();
//     }
// };

// 手机号校验
const validatePhone = (rule, value, callback) => {
    const phoneReg = /^1[3-9]\d{9}$/;
    if (!value) {
        callback(new Error('请输入司机电话'));
    } else if (!phoneReg.test(value)) {
        callback(new Error('手机号格式不正确'));
    } else {
        callback();
    }
};

// 时间校验
const validateArrivalTime = (rule, value, callback) => {
    if (!value) {
        callback(new Error('请选择预计到达时间'));
    } else if (formData.estimatedDepartureTime && value <= formData.estimatedDepartureTime) {
        callback(new Error('预计到达时间必须晚于出发时间'));
    } else {
        callback();
    }
};

const rules = {
    orderId: [{ required: false, message: '请选择订单', trigger: 'change' }],
    shipper: [{ required: true, message: '请选择发货方', trigger: 'change' }],
    buyer: [{ required: true, message: '请选择采购方', trigger: 'change' }],
    plateNumber: [{ required: true, message: '请选择车牌号', trigger: 'change' }],
    driverId: [{ required: true, message: '请选择司机', trigger: 'change' }],
    driverPhone: [{ required: true, validator: validatePhone, trigger: 'blur' }],
    estimatedDepartureTime: [{ required: true, message: '请选择预计出发时间', trigger: 'change' }],
    estimatedArrivalTime: [{ required: true, validator: validateArrivalTime, trigger: 'change' }],
    startLocation: [{ required: true, message: '请输入起点地址', trigger: 'blur' }],
    endLocation: [{ required: true, message: '请输入目的地地址', trigger: 'blur' }],
    cattleCount: [{ required: true, message: '请输入牛只数量', trigger: 'blur' }],
};

// 计算耳标设备列表（包含体重输入）
const earTagDevices = computed(() => {
    return formData.eartagDeviceIds.map(deviceId => {
        const device = eartagList.value.find(item => item.deviceId === deviceId);
        return {
            deviceId: deviceId,
            weight: device?.weight || null
        };
    });
});

// 计算项圈设备列表（包含体重输入）
const collarDevices = computed(() => {
    return formData.collarDeviceIds.map(deviceId => {
        const device = collarList.value.find(item => item.deviceId === deviceId);
        return {
            deviceId: deviceId,
            weight: device?.weight || null
        };
    });
});

// 完善提交数据 - 只提交DeliveryCreateDto需要的字段
const buildSubmitData = () => {
    // 将司机ID转换为姓名
    let driverNameStr = '';
    if (formData.driverId) {
        const driver = driverOptions.value.find(item => item.id === formData.driverId);
        // 使用username作为司机姓名（不要使用mobile）
        driverNameStr = driver ? (driver.username || '') : '';
    }
    
    const data = {
        // 基本信息
        shipperId: formData.shipper,
        buyerId: formData.buyer,
        plateNumber: formData.plateNumber,
        driverId: formData.driverId, // 传递司机ID给后端
        driverName: driverNameStr,
        driverPhone: formData.driverPhone,
        
        // 关联信息
        orderId: formData.orderId,
        
        // 设备ID
        serverId: formData.serverId,
        eartagIds: formData.eartagIds,
        collarIds: formData.collarIds,
        
        // 时间
        estimatedDepartureTime: formData.estimatedDepartureTime,
        estimatedArrivalTime: formData.estimatedArrivalTime,
        
        // 地址和坐标
        startLocation: formData.startLocation,
        startLon: formData.startLon,
        startLat: formData.startLat,
        endLocation: formData.endLocation,
        endLon: formData.endLon,
        endLat: formData.endLat,
        
        // 重量
        emptyWeight: formData.emptyWeight,
        entruckWeight: formData.entruckWeight,
        landingEntruckWeight: formData.landingEntruckWeight,
        
        // 其他信息
        cattleCount: formData.cattleCount,
        quarantineCertNo: formData.quarantineCertNo,
        remark: formData.remark,
        
        // 照片字段
        quarantineTickeyUrl: formData.quarantineTickeyUrl,
        poundListImg: formData.poundListImg,
        emptyVehicleFrontPhoto: formData.emptyVehicleFrontPhoto,
        loadedVehicleFrontPhoto: formData.loadedVehicleFrontPhoto,
        loadedVehicleWeightPhoto: formData.loadedVehicleWeightPhoto,
        driverIdCardPhoto: formData.driverIdCardPhoto,
        destinationPoundListImg: formData.destinationPoundListImg,
        destinationVehicleFrontPhoto: formData.destinationVehicleFrontPhoto,
        
        // 视频字段
        entruckWeightVideo: formData.entruckWeightVideo,
        emptyWeightVideo: formData.emptyWeightVideo,
        cattleLoadingVideo: formData.cattleLoadingVideo,
        controlSlotVideo: formData.controlSlotVideo,
        cattleLoadingCircleVideo: formData.cattleLoadingCircleVideo,
        unloadCattleVideo: formData.unloadCattleVideo,
        destinationWeightVideo: formData.destinationWeightVideo,
    };
    
    // 检查并清空包含字符串的设备ID数组（避免Integer溢出）
    if (data.eartagIds && data.eartagIds.length > 0 && typeof data.eartagIds[0] === 'string') {
        data.eartagIds = [];
    }
    if (data.collarIds && data.collarIds.length > 0 && typeof data.collarIds[0] === 'string') {
        data.collarIds = [];
    }
    
    // 将所有undefined值转换为空字符串，确保字段被提交
    // 但是对于数值类型的字段（如cattleCount），保留null或原值，不要转换为空字符串
    Object.keys(data).forEach(key => {
        if (data[key] === undefined) {
            // 数值类型字段保留null，其他字段转换为空字符串
            if (key === 'cattleCount' || 
                key === 'orderId' || key === 'shipperId' || key === 'buyerId' || 
                key === 'driverId' || key === 'serverId') {
                data[key] = null;
            } else {
                data[key] = '';
            }
        }
    });
    
    // 确保cattleCount不为空字符串，如果是空字符串则转换为null
    if (data.cattleCount === '') {
        data.cattleCount = null;
    }

    return data;
};

// 打开弹窗（支持编辑模式）
const open = async (editData = null) => {
    dialogVisible.value = true;
    
    // 并行加载所有下拉列表数据
    await Promise.all([
        loadSupplierAndBuyerList(),
        loadDeviceOptions(),
        loadDriverList(),
        loadVehicleList(),
        loadOrderList()
    ]);
    

    // 如果传入了编辑数据，则填充表单
    if (editData) {
        fillFormWithEditData(editData);
    }
};

// 填充编辑数据到表单
const fillFormWithEditData = (editData) => {

    // editData 包含两个部分：
    // 1. editData.delivery - 运单基本信息
    // 2. editData 的根级字段 - supplierId, buyerId, eartagIds, collarIds, serverIds
    
    const delivery = editData.delivery || editData; // 兼容两种数据结构
    
    // 基本信息
    formData.orderId = delivery.orderId || null;
    
    // 发货方和采购方：优先使用根级的 supplierId 和 buyerId
    formData.shipper = editData.supplierId || (delivery.supplierId ? parseInt(delivery.supplierId) : null);
    formData.buyer = editData.buyerId || delivery.buyerId || null;

    // 车牌号
    formData.plateNumber = delivery.licensePlate || '';

    // 检查车牌号是否在车辆列表中
    const vehicleExists = vehicleOptions.value.find(v => v.licensePlate === formData.plateNumber);
    if (!vehicleExists && formData.plateNumber) {
        console.warn('[EDIT-FILL] ⚠️ 车牌号在车辆列表中不存在:', formData.plateNumber);
    }
    
    formData.driverId = delivery.driverId || null;
    formData.driverPhone = delivery.driverMobile || '';
    
    // 设备信息：从根级读取
    if (editData.serverIds && editData.serverIds !== '') {
        formData.serverId = editData.serverIds;

    }
    
    if (editData.eartagIds && Array.isArray(editData.eartagIds) && editData.eartagIds.length > 0) {
        formData.eartagIds = editData.eartagIds;

    }
    
    if (editData.collarIds && Array.isArray(editData.collarIds) && editData.collarIds.length > 0) {
        formData.collarIds = editData.collarIds;

    }
    
    // 地址和坐标
    formData.startLocation = delivery.startLocation || '';
    formData.startLat = delivery.startLat || '';
    formData.startLon = delivery.startLon || '';
    formData.endLocation = delivery.endLocation || '';
    formData.endLat = delivery.endLat || '';
    formData.endLon = delivery.endLon || '';
    
    // 时间字段映射
    // estimatedDepartureTime：预计出发时间
    if (delivery.estimatedDepartureTime) {
        formData.estimatedDepartureTime = delivery.estimatedDepartureTime;
    } else if (delivery.createTime) {
        // 如果没有预计出发时间，使用创建时间作为默认值
        formData.estimatedDepartureTime = delivery.createTime;
    } else {
        formData.estimatedDepartureTime = '';
    }
    
    // estimatedDeliveryTime 对应 estimatedArrivalTime（预计送达时间）
    if (delivery.estimatedDeliveryTime) {
        formData.estimatedArrivalTime = delivery.estimatedDeliveryTime;
    } else {
        formData.estimatedArrivalTime = '';
    }
    
    // 重量信息
    formData.emptyWeight = delivery.emptyWeight || null;
    formData.entruckWeight = delivery.entruckWeight || null;
    formData.landingEntruckWeight = delivery.landingEntruckWeight || null;
    
    // 牛只数量（从ratedQuantity字段映射）
    formData.cattleCount = delivery.ratedQuantity || 1;
    
    // 照片
    formData.quarantineTickeyUrl = delivery.quarantineTickeyUrl || '';
    formData.poundListImg = delivery.poundListImg || '';
    formData.emptyVehicleFrontPhoto = delivery.emptyVehicleFrontPhoto || '';
    formData.loadedVehicleFrontPhoto = delivery.loadedVehicleFrontPhoto || '';
    formData.loadedVehicleWeightPhoto = delivery.loadedVehicleWeightPhoto || '';
    formData.driverIdCardPhoto = delivery.driverIdCardPhoto || '';
    formData.destinationPoundListImg = delivery.destinationPoundListImg || '';
    formData.destinationVehicleFrontPhoto = delivery.destinationVehicleFrontPhoto || '';
    
    // 视频
    formData.entruckWeightVideo = delivery.entruckWeightVideo || '';
    formData.emptyWeightVideo = delivery.emptyWeightVideo || '';
    formData.cattleLoadingVideo = delivery.cattleLoadingVideo || '';
    formData.controlSlotVideo = delivery.controlSlotVideo || '';
    formData.cattleLoadingCircleVideo = delivery.cattleLoadingCircleVideo || '';
    formData.unloadCattleVideo = delivery.unloadCattleVideo || '';
    formData.destinationWeightVideo = delivery.destinationWeightVideo || '';
    
    // 保存编辑的ID，用于区分是新增还是编辑
    formData.editId = delivery.id;
    

    ElMessage.success('已加载运单数据');
};

// 加载供应商和采购方列表
const loadSupplierAndBuyerList = async () => {
    try {
        // 加载供应商列表 (type=2)
        const supplierRes = await memberListByType({ type: 2, pageNum: 1, pageSize: 9999 });
        if (supplierRes.code === 200) {
            supplierList.value = supplierRes.data?.rows || supplierRes.data || [];
        }
        
        // 加载采购方列表 (type=4)
        const buyerRes = await memberListByType({ type: 4, pageNum: 1, pageSize: 9999 });
        if (buyerRes.code === 200) {
            buyerList.value = buyerRes.data?.rows || buyerRes.data || [];
        }
    } catch (error) {
        console.error('加载供应商/采购方列表失败', error);
    }
};

// 加载设备选项
const loadDeviceOptions = async () => {
    try {
        // 统一使用 iotDeviceQueryList 接口，通过 type 参数区分设备类型
        // type: 1-主机, 2-耳标, 4-项圈
        const [serverRes, eartagRes, collarRes] = await Promise.all([
            iotDeviceQueryList({ pageNum: 1, pageSize: 9999, type: 1 }), // 主机
            iotDeviceQueryList({ pageNum: 1, pageSize: 9999, type: 2 }), // 耳标
            iotDeviceQueryList({ pageNum: 1, pageSize: 9999, type: 4 })  // 项圈
        ]);
        
        if (serverRes.code === 200) {
            // 过滤出主机类型设备 (type === 1)
            const allServers = serverRes.data?.rows || serverRes.data || [];
            serverList.value = allServers
                .filter(item => item.type === 1 || item.type === '1')
                .map((item, idx) => ({
                    // 确保有数值型 id；若后端未提供 id，则使用索引占位
                    id: item.id ?? idx + 1,
                    deviceId: item.deviceId,
                    name: item.name,
                    type: item.type,
                }));
        }
        
        if (eartagRes.code === 200) {
            // 过滤出耳标类型设备 (type === 2)
            const allEartags = eartagRes.data?.rows || eartagRes.data || [];
            eartagList.value = allEartags
                .filter(item => item.type === 2 || item.type === '2')
                .map((item, idx) => ({
                    id: item.id ?? idx + 1000,
                    deviceId: item.deviceId,
                    name: item.name,
                    type: item.type,
                }));
        }
        
        if (collarRes.code === 200) {
            // 过滤出项圈类型设备 (type === 4)
            const allCollars = collarRes.data?.rows || collarRes.data || [];
            collarList.value = allCollars
                .filter(item => item.type === 4 || item.type === '4')
                .map((item, idx) => ({
                    id: item.id ?? idx + 2000,
                    deviceId: item.deviceId,
                    name: item.name,
                    type: item.type,
                }));
        }
    } catch (error) {
        console.error('加载设备列表失败', error);
    }
};

// 加载司机列表
const loadDriverList = async () => {
    try {
        const res = await fetchDriverList({ pageNum: 1, pageSize: 9999 });
        if (res.code === 200) {
            driverOptions.value = res.data?.rows || res.data || [];
        }
    } catch (error) {
        console.error('加载司机列表失败', error);
    }
};

// 加载车辆列表
const loadVehicleList = async () => {
    try {
        const res = await fetchVehicleList({ pageNum: 1, pageSize: 9999 });
        if (res.code === 200) {
            vehicleOptions.value = res.data?.data?.rows || res.data?.rows || res.data || [];
        }
    } catch (error) {
        console.error('加载车辆列表失败', error);
    }
};

// 加载订单列表
const loadOrderList = async () => {
    try {
        // 兼容运行时找不到函数引用的问题，优先从命名空间调用
        const res = await (orderPageQuery ? orderPageQuery({ pageNum: 1, pageSize: 1000 }) : shippingApi.orderPageQuery({ pageNum: 1, pageSize: 1000 }));
        if (res.code === 200) {
            orderList.value = res.data?.rows || [];
        }
    } catch (error) {
        console.error('加载订单列表失败', error);
    }
};

// 订单选择变化时自动填充发货方和采购方
const handleOrderChange = async (orderId) => {
    if (orderId) {
        try {
            // 从订单列表中查找选中的订单
            const order = orderList.value.find(item => item.id === orderId);
            if (order) {
                // 如果 buyerId 和 sellerId 是字符串（逗号分隔），取第一个
                let buyerId = order.buyerId;
                let sellerId = order.sellerId;
                
                if (typeof order.buyerId === 'string' && order.buyerId.includes(',')) {
                    buyerId = order.buyerId.split(',')[0].trim();
                }
                if (typeof order.sellerId === 'string' && order.sellerId.includes(',')) {
                    sellerId = order.sellerId.split(',')[0].trim();
                }
                
                // 自动填充发货方（卖方）和采购方（买方）
                formData.shipper = sellerId ? parseInt(sellerId) : null;
                formData.buyer = buyerId ? parseInt(buyerId) : null;
                

                ElMessage.success('已自动填充发货方和采购方信息');
            }
        } catch (error) {
            console.error('加载订单详情失败', error);
        }
    } else {
        // 清除订单时不清除发货方和采购方，让用户手动选择
    }
};

// 司机选择变化时自动填充电话
const handleDriverChange = (driverId) => {
    if (driverId) {
        formData.driverId = driverId; // 保存司机ID用于后端查询
        const driver = driverOptions.value.find(item => item.id === driverId);
        if (driver && driver.mobile) {
            formData.driverPhone = driver.mobile;

            ElMessage.success('已自动填充司机手机号');
        } else {

        }
    } else {
        formData.driverId = null;
        formData.driverPhone = '';

    }
};

// 选择主机设备时，记录设备编号（deviceId）到 serverDeviceId，避免后端 Integer 溢出
const handleServerChange = (serverId) => {
    const selected = serverList.value.find(item => (item.id === serverId) || (item.deviceId === serverId));
    formData.serverDeviceId = selected ? selected.deviceId : '';
};

// 选择耳标设备变化时，记录设备编号数组
const handleEartagChange = (ids) => {
    if (ids && ids.length > 0) {
        formData.eartagDeviceIds = ids.map(id => {
            const item = eartagList.value.find(dev => dev.id === id || dev.deviceId === id);
            return item ? item.deviceId : id;
        });
    } else {
        formData.eartagDeviceIds = [];
    }
};

// 选择项圈设备变化时，记录设备编号数组
const handleCollarChange = (ids) => {
    if (ids && ids.length > 0) {
        formData.collarDeviceIds = ids.map(id => {
            const item = collarList.value.find(dev => dev.id === id || dev.deviceId === id);
            return item ? item.deviceId : id;
        });
    } else {
        formData.collarDeviceIds = [];
    }
};

// 更新选中设备的delivery_id和car_number
const updateSelectedDevicesDeliveryId = async (deliveryId) => {
    try {
        const devicesToUpdate = [];
        
        // 收集所有选中的设备
        if (formData.serverDeviceId) {
            devicesToUpdate.push(formData.serverDeviceId);
        }
        if (formData.eartagDeviceIds && formData.eartagDeviceIds.length > 0) {
            devicesToUpdate.push(...formData.eartagDeviceIds);
        }
        if (formData.collarDeviceIds && formData.collarDeviceIds.length > 0) {
            devicesToUpdate.push(...formData.collarDeviceIds);
        }
        
        // 批量更新设备的delivery_id和car_number
        for (const deviceId of devicesToUpdate) {
            await updateDeviceDeliveryId({
                deviceId: deviceId,
                deliveryId: deliveryId,
                carNumber: formData.plateNumber // 传递车牌号
            });
        }
        

    } catch (error) {
        console.error('更新设备delivery_id和car_number失败:', error);
        // 不阻止流程，只记录错误
    }
};

// 提交表单
const handleSubmit = () => {
    formRef.value.validate(async (valid) => {
        if (valid) {
            // 验证地址经纬度
            if (!formData.startLat || !formData.startLon) {
                ElMessage.warning('请在地图上选择起点位置');
                return;
            }
            if (!formData.endLat || !formData.endLon) {
                ElMessage.warning('请在地图上选择目的地位置');
                return;
            }
            
            submitLoading.value = true;
            try {
                // 提交前详细日志
                console.group('[CREATE-DELIVERY] 提交前检查');
                try {
                    const formSnapshot = JSON.parse(JSON.stringify(formData));

                } catch (e) {
                    console.warn('表单快照序列化失败:', e);
                }

                const submitData = buildSubmitData();

                console.table(Object.keys(submitData).map(k => ({ key: k, type: typeof submitData[k], value: Array.isArray(submitData[k]) ? `Array(len=${submitData[k].length})` : submitData[k] })));
                if (submitData.eartagIds && submitData.eartagIds.some(v => typeof v === 'string')) {
                    console.warn('eartagIds 仍包含字符串，将被后端拒绝:', submitData.eartagIds);
                }
                if (submitData.collarIds && submitData.collarIds.some(v => typeof v === 'string')) {
                    console.warn('collarIds 仍包含字符串，将被后端拒绝:', submitData.collarIds);
                }
                console.groupEnd();

                let res;
                // 判断是编辑还是新增
                if (formData.editId) {
                    // 编辑模式：调用更新接口
                    // 将cattleCount映射为ratedQuantity（后端DeliveryEditDto使用ratedQuantity字段）
                    submitData.ratedQuantity = submitData.cattleCount;
                    submitData.deliveryId = formData.editId; // 添加deliveryId字段（后端需要）
                    res = await shippingApi.updateDeliveryInfo(submitData);
                } else {
                    // 新增模式：调用创建接口

                    res = await createDelivery(submitData);
                }
                
                console.group(formData.editId ? '[EDIT-DELIVERY] 响应日志' : '[CREATE-DELIVERY] 响应日志');

                console.groupEnd();
                
                if (res.code === 200) {
                    // 获取运送清单ID（新增返回data.id，编辑直接用editId）
                    const deliveryId = formData.editId || res.data?.id;
                    
                    if (deliveryId) {
                        // 更新设备的delivery_id
                        await updateSelectedDevicesDeliveryId(deliveryId);
                    }
                    
                    ElMessage.success(formData.editId ? '更新成功' : '创建成功');
                    dialogVisible.value = false;
                    emit('success');
                } else {
                    ElMessage.error(res.msg || (formData.editId ? '更新失败' : '创建失败'));
                }
            } catch (error) {
                console.group('[CREATE-DELIVERY] 异常日志');
                console.error('创建失败 error 对象:', error);
                if (error?.response) {
                    console.error('后端响应状态码:', error.response.status);
                    console.error('后端响应体:', error.response.data);
                }
                if (error?.config) {
                    console.error('请求URL:', error.config.url);
                    console.error('请求方法:', error.config.method);
                    console.error('请求头:', error.config.headers);
                    try {
                        console.error('请求数据:', typeof error.config.data === 'string' ? error.config.data : JSON.stringify(error.config.data));
                    } catch (e) {}
                }
                console.groupEnd();
                ElMessage.error('创建失败，请稍后重试');
            } finally {
                submitLoading.value = false;
            }
        }
    });
};

// 地图点击事件 - 起点
const handleStartLocationClick = (e) => {
    formData.startLon = e.point.lng;
    formData.startLat = e.point.lat;
    // 反向地理编码获取地址
    const geocoder = new window.BMap.Geocoder();
    geocoder.getLocation(e.point, (res) => {
        if (res) {
            formData.startLocation = res.address;
            ElMessage.success('已设置起点地址');
        }
    });
};

// 起点标记拖拽事件
const handleStartMarkerDrag = (e) => {
    formData.startLon = e.point.lng;
    formData.startLat = e.point.lat;
    const geocoder = new window.BMap.Geocoder();
    geocoder.getLocation(e.point, (res) => {
        if (res) {
            formData.startLocation = res.address;
        }
    });
};

// 打开起点地图并处理地址搜索
const openStartLocationMap = () => {

    // 如果输入框有地址，先进行地理编码
    if (formData.startLocation && formData.startLocation.trim()) {

        // 先打开地图对话框，让地图组件加载
        showStartLocationMap.value = true;
        
        // 等待地图加载后再进行地理编码
        setTimeout(() => {
            // 在 vue-baidu-map-3x 中，BMap 是通过组件访问的
            // 需要获取地图实例并使用地理编码
            if (window.BMap && window.BMap.Geocoder) {
                const geocoder = new window.BMap.Geocoder();
                geocoder.getPoint(formData.startLocation, (point) => {
                    if (point) {

                        // 搜索到坐标，更新地图中心点和标记
                        formData.startLon = point.lng;
                        formData.startLat = point.lat;
                        // 更新地图中心点
                        ElMessage.success('已定位到该地址');
                    } else {

                        ElMessage.warning('未找到该地址，请在地图上手动选择');
                    }
                });
            }
        }, 500);
    } else {

        showStartLocationMap.value = true;
    }
};

// 打开目的地地图并处理地址搜索
const openEndLocationMap = () => {

    // 如果输入框有地址，先进行地理编码
    if (formData.endLocation && formData.endLocation.trim()) {

        // 先打开地图对话框，让地图组件加载
        showEndLocationMap.value = true;
        
        // 等待地图加载后再进行地理编码
        setTimeout(() => {
            if (window.BMap && window.BMap.Geocoder) {
                const geocoder = new window.BMap.Geocoder();
                geocoder.getPoint(formData.endLocation, (point) => {
                    if (point) {

                        // 搜索到坐标，更新地图中心点和标记
                        formData.endLon = point.lng;
                        formData.endLat = point.lat;
                        // 更新地图中心点
                        ElMessage.success('已定位到该地址');
                    } else {

                        ElMessage.warning('未找到该地址，请在地图上手动选择');
                    }
                });
            }
        }, 500);
    } else {

        showEndLocationMap.value = true;
    }
};

const handleEndLocationClick = (e) => {
    formData.endLon = e.point.lng;
    formData.endLat = e.point.lat;
    // 反向地理编码获取地址
    const geocoder = new window.BMap.Geocoder();
    geocoder.getLocation(e.point, (res) => {
        if (res) {
            formData.endLocation = res.address;
            ElMessage.success('已设置目的地地址');
        }
    });
};

// 目的地标记拖拽事件
const handleEndMarkerDrag = (e) => {
    formData.endLon = e.point.lng;
    formData.endLat = e.point.lat;
    const geocoder = new window.BMap.Geocoder();
    geocoder.getLocation(e.point, (res) => {
        if (res) {
            formData.endLocation = res.address;
        }
    });
};

// 通用：从响应中提取URL（兼容多种响应结构）
const resolveUploadUrl = (res) => {
    if (!res) return '';
    // 优先级顺序：url > data.src > data.url > data.fileUrl
    return res.url || res.data?.src || res.data?.url || res.data?.fileUrl || '';
};
// 通用：创建成功回调
const makeUploadSuccessSetter = (key) => (response) => {
    const url = resolveUploadUrl(response);
    if (response?.code === 200 && url) {
        formData[key] = url;

        ElMessage.success('上传成功');
    } else {
        console.warn(`[UPLOAD] 未识别的响应结构:`, response);
        ElMessage.error(response?.msg || '上传失败');
    }
};

// 照片上传成功回调（统一使用工厂函数）
const handleQuarantinePhotoSuccess = makeUploadSuccessSetter('quarantineTickeyUrl');
const handlePoundListPhotoSuccess = makeUploadSuccessSetter('poundListImg');
const handleEmptyVehicleFrontPhotoSuccess = makeUploadSuccessSetter('emptyVehicleFrontPhoto');
const handleLoadedVehicleFrontPhotoSuccess = makeUploadSuccessSetter('loadedVehicleFrontPhoto');
const handleLoadedVehicleWeightPhotoSuccess = makeUploadSuccessSetter('loadedVehicleWeightPhoto');
const handleDriverIdCardPhotoSuccess = makeUploadSuccessSetter('driverIdCardPhoto');
const handleDestinationPoundListPhotoSuccess = makeUploadSuccessSetter('destinationPoundListImg');
const handleDestinationVehicleFrontPhotoSuccess = makeUploadSuccessSetter('destinationVehicleFrontPhoto');

// 视频上传成功回调（统一使用工厂函数）
const handleEntruckWeightVideoSuccess = makeUploadSuccessSetter('entruckWeightVideo');
const handleEmptyWeightVideoSuccess = makeUploadSuccessSetter('emptyWeightVideo');
const handleCattleLoadingVideoSuccess = makeUploadSuccessSetter('cattleLoadingVideo');
const handleControlSlotVideoSuccess = makeUploadSuccessSetter('controlSlotVideo');
const handleCattleLoadingCircleVideoSuccess = makeUploadSuccessSetter('cattleLoadingCircleVideo');
const handleUnloadCattleVideoSuccess = makeUploadSuccessSetter('unloadCattleVideo');
const handleDestinationWeightVideoSuccess = makeUploadSuccessSetter('destinationWeightVideo');

// 失败回调（可选）
const handleUploadError = (err) => {
    console.error('[UPLOAD] 失败:', err);
    ElMessage.error('上传失败');
};

// 视频移除回调
const handleRemoveVideo = () => {
    // 可以在这里添加清除逻辑
};

// 关闭弹窗
const handleClose = () => {
    formRef.value?.resetFields();
    // 清空所有表单字段
    Object.keys(formData).forEach(key => {
        if (key === 'orderId' || key === 'editId') {
            formData[key] = null;
        } else if (typeof formData[key] === 'number') {
            formData[key] = key === 'cattleCount' ? 1 : null;
        } else if (Array.isArray(formData[key])) {
            formData[key] = [];
        } else {
            formData[key] = '';
        }
    });
    dialogVisible.value = false;
    showStartLocationMap.value = false;
    showEndLocationMap.value = false;
};

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

const emit = defineEmits(['success']);
</script>

<style scoped>
.map {
    width: 100%;
    height: 500px;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
}

/* 照片上传样式 */
:deep(.avatar-uploader) {
    width: 178px;
    height: 178px;
    display: block;
}
:deep(.avatar-uploader .avatar) {
    width: 178px;
    height: 178px;
    display: block;
}
:deep(.avatar-uploader .el-icon) {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: all 0.3s;
}
:deep(.avatar-uploader .el-icon:hover) {
    border-color: #409eff;
}
</style>

