<template>
    <el-dialog
        v-model="data.dialogVisible"
        title="装车"
        :before-close="handleClose"
        style="width: 850px; padding-bottom: 20px"
        :close-on-click-modal="false"
    >
        <el-form ref="formDataRef" :model="ruleForm" :rules="rules" label-width="auto" v-loading="data.dialogLoading" element-loading-text="上传中">
            <el-row>
                <el-col :span="12">
                    <el-form-item label="预计送达时间" prop="estimatedDeliveryTime">
                        <el-date-picker
                            v-model="ruleForm.estimatedDeliveryTime"
                            type="datetime"
                            placeholder="请选择预计送达时间"
                            value-format="YYYY-MM-DD HH:mm:ss"
                            format="YYYY-MM-DD HH:mm:ss"
                            style="width: 100%"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="智能主机" prop="serverDeviceSn">
                        <el-select
                            v-model="ruleForm.serverDeviceSn"
                            clearable
                            filterable
                            remote
                            :remote-method="hostRemoteMethod"
                            :loading="data.hostLoading"
                            placeholder="请选择智能主机"
                        >
                            <el-option v-for="item in data.hostOptions" :key="item.id" :label="item.deviceId" :value="item.deviceId"></el-option>
                            <el-pagination
                                style="padding: 0px 20px"
                                @current-change="hostHandleCurrentChange"
                                :page-size="10"
                                :current-page="data.hostPageNum"
                                layout="total, prev, pager, next"
                                :total="data.hostTotal"
                            >
                            </el-pagination>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-form-item label="智能耳标编号">
                <el-table :data="data.deliveryDevices" border style="width: 100%">
                    <el-table-column prop="deviceId" label="设备编号"></el-table-column>
                    <el-table-column prop="bindWeight" label="体重">
                        <template #default="scope">
                            <el-input v-model="scope.row.bindWeight" placeholder="请输入体重" clearable>
                                <template #append>kg</template>
                            </el-input>
                        </template>
                    </el-table-column>
                </el-table>
            </el-form-item>
            <el-form-item label="智能项圈编号">
                <el-table :data="data.xqDevices" border style="width: 100%">
                    <el-table-column prop="deviceId" label="设备编号"></el-table-column>
                    <el-table-column prop="bindWeight" label="体重">
                        <template #default="scope">
                            <el-input v-model="scope.row.bindWeight" placeholder="请输入体重" clearable>
                                <template #append>kg</template>
                            </el-input>
                        </template>
                    </el-table-column>
                </el-table>
            </el-form-item>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="空车过磅重量" prop="emptyWeight">
                        <el-input v-model="ruleForm.emptyWeight" placeholder="请输入空车过磅重量" clearable>
                            <template #append>kg</template></el-input
                        >
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="装车过磅重量" prop="entruckWeight">
                        <el-input v-model="ruleForm.entruckWeight" placeholder="请输入装车过磅重量" clearable>
                            <template #append>kg</template></el-input
                        >
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="落地过磅重量" prop="landingEntruckWeight">
                        <el-input v-model="ruleForm.landingEntruckWeight" placeholder="请输入落地过磅重量" clearable>
                            <template #append>kg</template></el-input
                        >
                    </el-form-item>
                </el-col>
            </el-row>
            <!-- 照片上传区域 -->
            <el-divider content-position="left">
                <el-icon><Picture /></el-icon>
                <span style="margin-left: 8px; font-weight: bold; color: #409EFF;">照片上传</span>
            </el-divider>
            <el-row>
                <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="jyHandleAvatarSuccess"
                            :headers="importHeaders"
                        >
                            <img v-if="ruleForm.quarantineTickeyUrl" :src="ruleForm.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="szHandleAvatarSuccess"
                            :headers="importHeaders"
                        >
                            <img v-if="ruleForm.poundListImg" :src="ruleForm.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>
                <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="emptyVehicleFrontPhotoSuccess"
                            :headers="importHeaders"
                        >
                            <img v-if="ruleForm.emptyVehicleFrontPhoto" :src="ruleForm.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="loadedVehicleFrontPhotoSuccess"
                            :headers="importHeaders"
                        >
                            <img v-if="ruleForm.loadedVehicleFrontPhoto" :src="ruleForm.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>
                <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="loadedVehicleWeightPhotoSuccess"
                            :headers="importHeaders"
                        >
                            <img v-if="ruleForm.loadedVehicleWeightPhoto" :src="ruleForm.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="driverIdCardPhotoSuccess"
                            :headers="importHeaders"
                        >
                            <img v-if="ruleForm.driverIdCardPhoto" :src="ruleForm.driverIdCardPhoto" 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">
                <el-icon><VideoPlay /></el-icon>
                <span style="margin-left: 8px; font-weight: bold; color: #67C23A;">视频上传</span>
            </el-divider>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="装车过磅视频" prop="entruckWeightVideo">
                        <video
                            v-if="ruleForm.entruckWeightVideo"
                            style="width: 100%; height: 260px; margin-bottom: 10px"
                            :src="ruleForm.entruckWeightVideo"
                            controls
                        ></video>
                        <el-upload
                            accept=".mp4,.avi,.rmvb,.mkv,.MP4,.AVI,.RMVB,.MKV"
                            class="upload-demo"
                            action="/api/common/upload"
                            style="width: 100%"
                            :headers="importHeaders"
                            :limit="1"
                            :on-remove="
                                (file, fileList) => {
                                    return handleRemoveVideo(file, fileList, 'entruckWeightVideo');
                                }
                            "
                            :on-progress="loadvideo"
                            :on-success="
                                (response, file, fileList) => {
                                    return uploadSuccessVideo(response, file, fileList, 'entruckWeightVideo');
                                }
                            "
                        >
                            <el-button type="primary"
                                >上传<el-icon><UploadFilled /></el-icon
                            ></el-button>
                        </el-upload>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="空车过磅视频" prop="emptyWeightVideo">
                        <video
                            v-if="ruleForm.emptyWeightVideo"
                            style="width: 100%; height: 260px; margin-bottom: 10px"
                            :src="ruleForm.emptyWeightVideo"
                            controls
                        ></video>
                        <el-upload
                            accept=".mp4,.avi,.rmvb,.mkv,.MP4,.AVI,.RMVB,.MKV"
                            class="upload-demo"
                            action="/api/common/upload"
                            style="width: 100%"
                            :headers="importHeaders"
                            :limit="1"
                            :on-remove="
                                (file, fileList) => {
                                    return handleRemoveVideo(file, fileList, 'emptyWeightVideo');
                                }
                            "
                            :on-progress="loadvideo"
                            :on-success="
                                (response, file, fileList) => {
                                    return uploadSuccessVideo(response, file, fileList, 'emptyWeightVideo');
                                }
                            "
                        >
                            <el-button type="primary"
                                >上传<el-icon><UploadFilled /></el-icon
                            ></el-button>
                        </el-upload>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="上传装牛视频" prop="entruckVideo">
                        <video
                            v-if="ruleForm.entruckVideo"
                            style="width: 100%; height: 260px; margin-bottom: 10px"
                            :src="ruleForm.entruckVideo"
                            controls
                        ></video>
                        <el-upload
                            accept=".mp4,.avi,.rmvb,.mkv,.MP4,.AVI,.RMVB,.MKV"
                            class="upload-demo"
                            action="/api/common/upload"
                            style="width: 100%"
                            :headers="importHeaders"
                            :limit="1"
                            :on-remove="
                                (file, fileList) => {
                                    return handleRemoveVideo(file, fileList, 'entruckVideo');
                                }
                            "
                            :on-progress="loadvideo"
                            :on-success="
                                (response, file, fileList) => {
                                    return uploadSuccessVideo(response, file, fileList, 'entruckVideo');
                                }
                            "
                        >
                            <el-button type="primary"
                                >上传<el-icon><UploadFilled /></el-icon
                            ></el-button>
                        </el-upload>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="控槽视频" prop="controlSlotVideo">
                        <video
                            v-if="ruleForm.controlSlotVideo"
                            style="width: 100%; height: 260px; margin-bottom: 10px"
                            :src="ruleForm.controlSlotVideo"
                            controls
                        ></video>
                        <el-upload
                            accept=".mp4,.avi,.rmvb,.mkv,.MP4,.AVI,.RMVB,.MKV"
                            class="upload-demo"
                            action="/api/common/upload"
                            style="width: 100%"
                            :headers="importHeaders"
                            :limit="1"
                            :on-remove="
                                (file, fileList) => {
                                    return handleRemoveVideo(file, fileList, 'controlSlotVideo');
                                }
                            "
                            :on-progress="loadvideo"
                            :on-success="
                                (response, file, fileList) => {
                                    return uploadSuccessVideo(response, file, fileList, 'controlSlotVideo');
                                }
                            "
                        >
                            <el-button type="primary"
                                >上传<el-icon><UploadFilled /></el-icon
                            ></el-button>
                        </el-upload>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="装完牛绕车一圈视频" prop="cattleLoadingCircleVideo">
                        <video
                            v-if="ruleForm.cattleLoadingCircleVideo"
                            style="width: 100%; height: 260px; margin-bottom: 10px"
                            :src="ruleForm.cattleLoadingCircleVideo"
                            controls
                        ></video>
                        <el-upload
                            accept=".mp4,.avi,.rmvb,.mkv,.MP4,.AVI,.RMVB,.MKV"
                            class="upload-demo"
                            action="/api/common/upload"
                            style="width: 100%"
                            :headers="importHeaders"
                            :limit="1"
                            :on-remove="
                                (file, fileList) => {
                                    return handleRemoveVideo(file, fileList, 'cattleLoadingCircleVideo');
                                }
                            "
                            :on-progress="loadvideo"
                            :on-success="
                                (response, file, fileList) => {
                                    return uploadSuccessVideo(response, file, fileList, 'cattleLoadingCircleVideo');
                                }
                            "
                        >
                            <el-button type="primary"
                                >上传<el-icon><UploadFilled /></el-icon
                            ></el-button>
                        </el-upload>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <template #footer>
            <el-button type="primary" @click="onClickSave" :loading="data.saveLoading">确 定</el-button>
            <el-button @click="handleClose">取 消</el-button>
        </template>
    </el-dialog>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue';
import { hostList, orderLoadDetail, orderLoadSave, testOrderDevices, updateDeviceDeliveryId, updateDeviceWeights, getOrderHostDevice } from '@/api/shipping.js';
import { pageDeviceList } from '@/api/abroad.js';
import { useUserStore } from '../../store/user';

const userStore = useUserStore();
const importHeaders = reactive({ Authorization: userStore.$state.token });
const formDataRef = ref();
const emits = defineEmits(['success']);
const data = reactive({
    dialogVisible: false,
    hostLoading: false,
    hostNumber: '',
    hostOptions: [],
    hostPageNum: 1,
    hostTotal: 0,
    deliveryDevices: [],
    xqDevices: [],
    deliveryId: '',
    dialogLoading: false,
    saveLoading: false,
});
const ruleForm = reactive({
    deliveryId: '',
    estimatedDeliveryTime: '', // 预计送达时间,
    serverDeviceSn: '', // 主机id
    emptyWeight: '', // 空车过磅重量
    entruckWeight: '', // 装车过磅重量
    landingEntruckWeight: '', // 落地过磅重量
    quarantineTickeyUrl: '', // 检疫票
    poundListImg: '', // 传纸质磅单（双章）
    entruckWeightVideo: '', // 装车过磅视频
    emptyWeightVideo: '', // 空车过磅视频
    entruckVideo: '', // 上传装牛视频
    controlSlotVideo: '', // 控槽视频
    emptyVehicleFrontPhoto: '', // 车辆空磅上磅车头照片
    cattleLoadingCircleVideo: '', // 装完牛绕车一圈视频
    loadedVehicleFrontPhoto: '', // 车辆过重磅车头照片
    loadedVehicleWeightPhoto: '', // 车辆重磅照片
    driverIdCardPhoto: '', // 驾驶员手持身份证站车头照片
    deliveryDevices: [], // 耳标编号集合
    xqDevices: [],
});
const rules = reactive({});

// 自动填充表单数据映射函数
const autoFillFormData = (apiData) => {
    if (!apiData) return;
    
    // 基础信息映射
    // 不要覆盖已经设置的 deliveryId
    if (apiData.id && apiData.id !== '') {
        ruleForm.deliveryId = apiData.id;
    }
    ruleForm.estimatedDeliveryTime = apiData.estimatedDeliveryTime || '';
    ruleForm.serverDeviceSn = apiData.serverDeviceId || '';
    
    // 重量信息映射
    ruleForm.emptyWeight = apiData.emptyWeight || '';
    ruleForm.entruckWeight = apiData.entruckWeight || '';
    ruleForm.landingEntruckWeight = apiData.landingEntruckWeight || '';
    
    // 照片URL映射
    ruleForm.quarantineTickeyUrl = apiData.quarantineTickeyUrl || '';
    ruleForm.poundListImg = apiData.poundListImg || '';
    ruleForm.emptyVehicleFrontPhoto = apiData.emptyVehicleFrontPhoto || '';
    ruleForm.loadedVehicleFrontPhoto = apiData.loadedVehicleFrontPhoto || '';
    ruleForm.loadedVehicleWeightPhoto = apiData.loadedVehicleWeightPhoto || '';
    ruleForm.driverIdCardPhoto = apiData.driverIdCardPhoto || '';
    
    // 视频URL映射
    ruleForm.entruckWeightVideo = apiData.entruckWeightVideo || '';
    ruleForm.emptyWeightVideo = apiData.emptyWeightVideo || '';
    ruleForm.entruckVideo = apiData.entruckVideo || '';
    ruleForm.controlSlotVideo = apiData.controlSlotVideo || '';
    ruleForm.cattleLoadingCircleVideo = apiData.cattleLoadingCircleVideo || '';
    

};

// 查询详情
const getOrderDetail = () => {
    // 先获取订单基本信息
    orderLoadDetail({
        deliveryId: data.deliveryId,
    }).then((res) => {

        if (res.code === 200) {

            // 自动填充表单数据
            autoFillFormData(res.data);
            
            // 使用新的统一设备接口获取智能耳标和智能项圈
            getDevicesByOrder();
            
            // 检查订单绑定的智能主机
            checkOrderHostDevice();
        } else {
            console.error('getOrderDetail API 调用失败:', res);
        }
    }).catch((error) => {
        console.error('getOrderDetail API 调用异常:', error);
    });
};

// 使用统一设备接口获取智能耳标和智能项圈
const getDevicesByOrder = () => {
    if (!data.deliveryId) {
        console.warn('deliveryId为空，无法获取设备信息');
        return;
    }
    

    // 先调用测试接口检查订单设备数据
    testOrderDevices(parseInt(data.deliveryId)).then((res) => {

        if (res.code === 200) {

        }
    }).catch((error) => {
        console.error('=== 测试接口调用失败:', error);
    });
    
    // 获取智能耳标 (deviceType: 2)
    pageDeviceList({
        pageNum: 1,
        pageSize: 100,
        deliveryId: parseInt(data.deliveryId),
        deviceType: 2, // 智能耳标
    }).then((res) => {
        if (res.code === 200) {
            if (res.data && Array.isArray(res.data)) {

                // 过滤出智能耳标设备并转换为需要的格式
                const earDevices = res.data.filter(device => {

                    return device.deviceType === 2 || device.deviceType === '2';
                });
                

                data.deliveryDevices = earDevices.map(device => ({
                    deviceId: device.deviceId,
                    bindWeight: device.bindWeight || '', // 如果有绑定重量则使用，否则为空
                }));
                

            } else {
                console.warn('API返回的数据不是数组格式:', res.data);
                data.deliveryDevices = [];
            }
        } else {
            console.error('获取智能耳标设备失败:', res.msg);
            data.deliveryDevices = [];
        }
    }).catch((error) => {
        console.error('获取智能耳标设备异常:', error);
        data.deliveryDevices = [];
    });
    
    // 获取智能项圈 (deviceType: 4)
    pageDeviceList({
        pageNum: 1,
        pageSize: 100,
        deliveryId: parseInt(data.deliveryId),
        deviceType: 4, // 智能项圈
    }).then((res) => {
        if (res.code === 200) {
            if (res.data && Array.isArray(res.data)) {

                // 过滤出智能项圈设备并转换为需要的格式
                const collarDevices = res.data.filter(device => {

                    return device.deviceType === 4 || device.deviceType === '4';
                });
                

                data.xqDevices = collarDevices.map(device => ({
                    deviceId: device.deviceId,
                    bindWeight: device.bindWeight || '', // 如果有绑定重量则使用，否则为空
                }));
                

            } else {
                console.warn('API返回的数据不是数组格式:', res.data);
                data.xqDevices = [];
            }
        } else {
            console.error('获取智能项圈设备失败:', res.msg);
            data.xqDevices = [];
        }
    }).catch((error) => {
        console.error('获取智能项圈设备异常:', error);
        data.xqDevices = [];
    });
};
// 智能主机远程搜索
const hostRemoteMethod = (e) => {
    data.hostNumber = e;
    data.hostPageNum = 1;
    getHostList();
};
// 主机列表 - 使用统一设备接口
const getHostList = () => {
    data.hostLoading = true;
    
    // 使用统一设备接口获取智能主机 (deviceType: 1)
    // 获取所有可用的智能主机（没有绑定到特定订单的）
    pageDeviceList({
        pageNum: data.hostPageNum,
        pageSize: 10,
        deviceType: 1, // 智能主机
        // 如果有搜索条件，可以根据deviceId搜索
        ...(data.hostNumber ? { deviceId: data.hostNumber } : {}),
        // 不传递deliveryId，获取所有可用的主机
    }).then((res) => {

        data.hostLoading = false;
        if (res.code === 200) {
            // 过滤出智能主机设备
            const hostDevices = res.data.filter(device => device.deviceType === 1 || device.deviceType === '1');
            
            // 转换为下拉选择需要的格式
            data.hostOptions = hostDevices.map(device => ({
                id: device.deviceId,
                deviceId: device.deviceId,
                deviceType: device.deviceType,
                deviceTypeName: device.deviceTypeName || '智能主机',
                battery: device.battery,
                deviceVoltage: device.deviceVoltage,
                deviceTemp: device.deviceTemp,
                latitude: device.latitude,
                longitude: device.longitude,
                updateTime: device.updateTime,
                createTime: device.createTime,
            }));
            
            data.hostTotal = hostDevices.length;

        } else {
            console.error('获取智能主机设备失败:', res.msg);
            data.hostOptions = [];
            data.hostTotal = 0;
        }
    }).catch((error) => {
        console.error('获取智能主机设备异常:', error);
        data.hostLoading = false;
        data.hostOptions = [];
        data.hostTotal = 0;
    });
};
// 选择智能主机分页
const hostHandleCurrentChange = (val) => {
    data.hostPageNum = val;
    getHostList();
};
// 检疫票上传
const jyHandleAvatarSuccess = (res) => {
    if (res.code === 200) {
        ElMessage({
            message: res.msg,
            type: 'success',
        });
        ruleForm.quarantineTickeyUrl = res.data.src;
    } else {
        ElMessage.error(res.msg);
    }
};
// 传纸质磅单（双章）
const szHandleAvatarSuccess = (res) => {
    if (res.code === 200) {
        ElMessage({
            message: res.msg,
            type: 'success',
        });
        ruleForm.poundListImg = res.data.src;
    } else {
        ElMessage.error(res.msg);
    }
};
// 车辆空磅上磅车头照片上传
const emptyVehicleFrontPhotoSuccess = (res) => {
    if (res.code === 200) {
        ElMessage({
            message: res.msg,
            type: 'success',
        });
        ruleForm.emptyVehicleFrontPhoto = res.data.src;
    } else {
        ElMessage.error(res.msg);
    }
};
// 车辆过重磅车头照片上传
const loadedVehicleFrontPhotoSuccess = (res) => {
    if (res.code === 200) {
        ElMessage({
            message: res.msg,
            type: 'success',
        });
        ruleForm.loadedVehicleFrontPhoto = res.data.src;
    } else {
        ElMessage.error(res.msg);
    }
};
// 车辆重磅照片上传
const loadedVehicleWeightPhotoSuccess = (res) => {
    if (res.code === 200) {
        ElMessage({
            message: res.msg,
            type: 'success',
        });
        ruleForm.loadedVehicleWeightPhoto = res.data.src;
    } else {
        ElMessage.error(res.msg);
    }
};
// 驾驶员手持身份证站车头照片上传
const driverIdCardPhotoSuccess = (res) => {
    if (res.code === 200) {
        ElMessage({
            message: res.msg,
            type: 'success',
        });
        ruleForm.driverIdCardPhoto = res.data.src;
    } else {
        ElMessage.error(res.msg);
    }
};
// 视频上传时
const loadvideo = (event, file, fileLis) => {
    data.dialogLoading = true;
};
// 上传视频
const uploadSuccessVideo = (res, file, fileList, type) => {
    data.dialogLoading = false;
    if (res.code === 200) {
        ElMessage({
            message: res.msg,
            type: 'success',
        });
        if (ruleForm.hasOwnProperty(type)) {
            ruleForm[type] = res.data.src;
        }
    } else {
        ElMessage.error(res.msg);
    }
};
// 删除视频
const handleRemoveVideo = (file, fileList, type) => {
    if (ruleForm.hasOwnProperty(type)) {
        ruleForm[type] = '';
    }
};
// 保存按钮
const onClickSave = () => {
    data.saveLoading = true;
    ruleForm.deliveryDevices = data.deliveryDevices;
    ruleForm.xqDevices = data.xqDevices;
    
    // 确保 deliveryId 是数字类型
    const saveData = { ...ruleForm };

    if (saveData.deliveryId) {
        const parsedId = parseInt(saveData.deliveryId);
        if (isNaN(parsedId)) {
            ElMessage.error('运送清单ID格式错误');
            data.saveLoading = false;
            return;
        }
        saveData.deliveryId = parsedId;
    } else {
        ElMessage.error('运送清单ID不能为空');
        data.saveLoading = false;
        return;
    }
    
    // 先保存装车信息
    orderLoadSave(saveData).then((res) => {
        if (res.code === 200) {

            // 如果选择了智能主机，需要更新主机的delivery_id
            if (saveData.serverDeviceSn) {
                updateHostDeliveryId(saveData.serverDeviceSn, saveData.deliveryId);
            } else {
                // 没有选择主机，直接更新设备重量
                updateDeviceWeightsLocal();
            }
        } else {
            ElMessage.error(res.msg);
            data.saveLoading = false;
        }
    }).catch((error) => {
        console.error('保存装车信息失败:', error);
        ElMessage.error('保存失败');
        data.saveLoading = false;
    });
};

// 更新智能主机的delivery_id
const updateHostDeliveryId = (hostDeviceId, deliveryId) => {

    // 调用后端接口更新主机的delivery_id
    updateDeviceDeliveryId({
        deviceId: hostDeviceId,
        deliveryId: deliveryId
    }).then((res) => {
        if (res.code === 200) {

            // 更新设备重量
            updateDeviceWeightsLocal();
        } else {
            console.error('智能主机delivery_id更新失败:', res.msg);
            ElMessage.error('智能主机绑定失败: ' + res.msg);
            data.saveLoading = false;
        }
    }).catch((error) => {
        console.error('智能主机delivery_id更新异常:', error);
        ElMessage.error('智能主机绑定失败');
        data.saveLoading = false;
    });
};

// 更新设备重量
const updateDeviceWeightsLocal = (customDevices = null) => {

    // 收集所有设备的重量信息
    const devices = [];
    
    if (customDevices && customDevices.length > 0) {
        // 如果传入了自定义设备列表，使用它
        devices.push(...customDevices);
    } else {
        // 否则收集当前表单中的设备重量
        // 添加智能耳标的重量
        data.deliveryDevices.forEach(device => {
            // 安全地检查bindWeight值
            const weightStr = String(device.bindWeight || '').trim();
            if (weightStr !== '' && !isNaN(parseFloat(weightStr))) {
                devices.push({
                    deviceId: device.deviceId,
                    weight: parseFloat(weightStr)
                });
            }
        });
        
        // 添加智能项圈的重量
        data.xqDevices.forEach(device => {
            // 安全地检查bindWeight值
            const weightStr = String(device.bindWeight || '').trim();
            if (weightStr !== '' && !isNaN(parseFloat(weightStr))) {
                devices.push({
                    deviceId: device.deviceId,
                    weight: parseFloat(weightStr)
                });
            }
        });
    }
    

    if (devices.length === 0) {

        completeSave();
        return;
    }
    
    // 调用后端接口批量更新设备重量
    updateDeviceWeights({
        deliveryId: parseInt(data.deliveryId),
        devices: devices
    }).then((res) => {
        if (res.code === 200) {

            completeSave();
        } else {
            console.error('设备重量更新失败:', res.msg);
            ElMessage.error('设备重量更新失败: ' + res.msg);
            data.saveLoading = false;
        }
    }).catch((error) => {
        console.error('设备重量更新异常:', error);
        ElMessage.error('设备重量更新失败');
        data.saveLoading = false;
    });
};

// 检查订单绑定的智能主机
const checkOrderHostDevice = () => {
    if (!data.deliveryId) {
        console.warn('deliveryId为空，无法检查订单绑定的智能主机');
        return;
    }
    

    getOrderHostDevice(parseInt(data.deliveryId)).then((res) => {
        if (res.code === 200) {
            if (res.data) {
                // 订单已绑定智能主机，自动填充

                ruleForm.serverDeviceSn = res.data.deviceId;

            } else {
                // 订单未绑定智能主机

                ruleForm.serverDeviceSn = '';

            }
        } else {
            console.error('查询订单绑定主机失败:', res.msg);
        }
    }).catch((error) => {
        console.error('查询订单绑定主机异常:', error);
    });
};

// 完成保存操作
const completeSave = () => {
    data.saveLoading = false;
    ElMessage({
        message: '保存成功',
        type: 'success',
    });
    emits('success');
    if (formDataRef.value) {
        formDataRef.value.resetFields();
    }
    data.dialogVisible = false;
};
// 取消
const handleClose = () => {
    data.dialogVisible = false;
    if (formDataRef.value) {
        formDataRef.value.resetFields();
    }
};
const onShowDialog = (row, apiData = null) => {
    data.dialogVisible = true;
    if (formDataRef.value) {
        formDataRef.value.resetFields();
    }
    if (row) {
        nextTick(() => {
            data.deliveryId = row.id;
            ruleForm.deliveryId = row.id;

            // 如果提供了API数据，直接填充表单
            if (apiData) {
                autoFillFormData(apiData);
                // 获取设备信息
                getDevicesByOrder();
                // 检查订单绑定的智能主机
                checkOrderHostDevice();
            } else {
                // 否则从服务器获取详情
                getOrderDetail();
            }
            
            // 获取智能主机列表（未绑定的）
            getHostList();
        });
    }
};
defineExpose({
    onShowDialog,
});
</script>

<style lang="less" scoped>
.avatar {
    width: 178px;
    height: 178px;
}
:deep(.avatar-uploader .el-upload) {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

:deep(.avatar-uploader .el-upload:hover) {
    border-color: var(--el-color-primary);
}

:deep(.el-icon.avatar-uploader-icon) {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>
