<template>
    <el-dialog
        v-model="data.dialogVisible"
        :title="data.isDetail ? '出仓详情' : (data.editId ? '编辑出仓记录' : '新增出仓记录')"
        :before-close="handleClose"
        width="900px"
        :close-on-click-modal="false"
    >
        <el-form ref="formDataRef" :model="ruleForm" :rules="rules" label-width="120px" :disabled="data.isDetail">
            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="中转仓" prop="warehouseId">
                        <el-select 
                            v-model="ruleForm.warehouseId" 
                            placeholder="请选择中转仓" 
                            clearable 
                            filterable 
                            style="width: 100%"
                            @change="handleWarehouseChange"
                        >
                            <el-option
                                v-for="item in warehouseList"
                                :key="item.id"
                                :label="item.warehouseName"
                                :value="item.id"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>

            <!-- 进仓记录关联表格 -->
            <el-row :gutter="20">
                <el-col :span="24">
                    <el-form-item label="关联进仓记录" prop="warehouseInRelations">
                        <div style="width: 100%">
                            <el-button 
                                type="primary" 
                                size="small" 
                                @click="addWarehouseInRelation"
                                :disabled="data.isDetail || !ruleForm.warehouseId"
                                style="margin-bottom: 10px"
                            >
                                添加进仓记录
                            </el-button>
                            <el-table 
                                :data="ruleForm.warehouseInRelations" 
                                border 
                                style="width: 100%"
                                :max-height="300"
                                :key="`warehouse-in-table-${warehouseInList.length}`"
                            >
                                <el-table-column label="进仓单号" min-width="150">
                                    <template #default="scope">
                                        <el-select 
                                            v-model="scope.row.warehouseInId" 
                                            placeholder="请选择进仓记录" 
                                            filterable 
                                            clearable
                                            style="width: 100%"
                                            :disabled="data.isDetail"
                                            :loading="warehouseInList.length === 0 && ruleForm.warehouseId"
                                            @change="handleWarehouseInRelationChange(scope.row, scope.$index)"
                                        >
                                            <el-option
                                                v-for="item in getAvailableWarehouseInList(scope.$index)"
                                                :key="`option-${item.id}-${item.remainingCount}`"
                                                :label="`${item.inNumber || '--'} (总:${item.cattleCount || 0}头, 剩余:${item.remainingCount || 0}头)`"
                                                :value="item.id"
                                            >
                                                {{ item.inNumber || '--' }} (总:{{ item.cattleCount || 0 }}头, 剩余:{{ item.remainingCount || 0 }}头)
                                            </el-option>
                                            <el-option
                                                v-if="getAvailableWarehouseInList(scope.$index).length === 0 && warehouseInList.length === 0 && ruleForm.warehouseId && !data.isDetail"
                                                disabled
                                                value=""
                                            >
                                                正在加载进仓记录...
                                            </el-option>
                                            <el-option
                                                v-if="getAvailableWarehouseInList(scope.$index).length === 0 && warehouseInList.length > 0 && !data.isDetail"
                                                disabled
                                                value=""
                                            >
                                                暂无可用进仓记录（剩余数量为0或已被选择）
                                            </el-option>
                                            <el-option
                                                v-if="getAvailableWarehouseInList(scope.$index).length === 0 && !ruleForm.warehouseId && !data.isDetail"
                                                disabled
                                                value=""
                                            >
                                                请先选择中转仓
                                            </el-option>
                                        </el-select>
                                    </template>
                                </el-table-column>
                                <el-table-column label="进仓总数量" prop="totalCount" min-width="100" align="center">
                                    <template #default="scope">
                                        {{ scope.row.totalCount || '--' }} 头
                                    </template>
                                </el-table-column>
                                <el-table-column label="已出仓数量" prop="outCount" min-width="100" align="center">
                                    <template #default="scope">
                                        {{ scope.row.outCount || 0 }} 头
                                    </template>
                                </el-table-column>
                                <el-table-column label="剩余数量" prop="remainingCount" min-width="100" align="center">
                                    <template #default="scope">
                                        <span :style="{ color: (scope.row.remainingCount || 0) <= 0 ? 'red' : 'green' }">
                                            {{ scope.row.remainingCount || 0 }} 头
                                        </span>
                                    </template>
                                </el-table-column>
                                <el-table-column label="本次出仓数量" prop="outCountThisTime" min-width="150">
                                    <template #default="scope">
                                        <el-input-number
                                            :model-value="scope.row.outCountThisTime || null"
                                            @update:model-value="(val) => { scope.row.outCountThisTime = val || undefined; handleOutCountChange(); }"
                                            :min="Math.min(1, scope.row.remainingCount || 0)"
                                            :max="Math.max(scope.row.remainingCount || 0, 0)"
                                            :disabled="data.isDetail || !scope.row.warehouseInId || (scope.row.remainingCount || 0) <= 0"
                                            placeholder="请输入数量"
                                            style="width: 100%"
                                        />
                                    </template>
                                </el-table-column>
                                <el-table-column label="操作" width="100" align="center" v-if="!data.isDetail">
                                    <template #default="scope">
                                        <el-button 
                                            link 
                                            type="danger" 
                                            @click="removeWarehouseInRelation(scope.$index)"
                                            :disabled="!scope.row.warehouseInId"
                                        >
                                            删除
                                        </el-button>
                                    </template>
                                </el-table-column>
                            </el-table>
                            <div style="margin-top: 10px; color: #666; font-size: 12px;">
                                <span>总出仓数量：<strong style="color: #409EFF;">{{ getTotalOutCount() }}</strong> 头</span>
                            </div>
                        </div>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="运送清单" prop="deliveryId">
                        <el-select 
                            v-model="ruleForm.deliveryId" 
                            placeholder="请选择运送清单" 
                            clearable 
                            filterable 
                            style="width: 100%"
                            @change="handleDeliveryChange"
                        >
                            <el-option
                                v-for="item in deliveryList"
                                :key="item.id"
                                :label="`${item.deliveryNumber || '--'} - ${item.licensePlate || '--'}`"
                                :value="item.id"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="订单" prop="orderId">
                        <el-select 
                            v-model="ruleForm.orderId" 
                            placeholder="请选择订单（可多选）" 
                            multiple
                            clearable 
                            filterable 
                            style="width: 100%"
                        >
                            <el-option
                                v-for="item in orderList"
                                :key="item.id"
                                :label="`订单${item.id} - 单价: ${item.firmPrice || '--'}元/斤`"
                                :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="outTime">
                        <el-date-picker
                            v-model="ruleForm.outTime"
                            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="destinationLocation">
                        <el-input 
                            v-model="ruleForm.destinationLocation" 
                            placeholder="请输入目的地" 
                            maxlength="255"
                            style="width: calc(100% - 100px); margin-right: 10px;"
                        />
                        <el-button type="primary" @click="openDestinationLocationMap">选择位置</el-button>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="目的地经度">
                        <el-input v-model="ruleForm.destinationLon" placeholder="经度" disabled />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="目的地纬度">
                        <el-input v-model="ruleForm.destinationLat" placeholder="纬度" disabled />
                    </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="ruleForm.cattleCount"
                            :min="1"
                            :max="9999"
                            placeholder="请输入牛只数量（自动计算）"
                            style="width: 100%"
                            :disabled="true"
                        />
                        <div style="color: #909399; font-size: 12px; margin-top: 5px;">
                            由关联的进仓记录自动计算
                        </div>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="重量(公斤)" prop="weight">
                        <el-input-number
                            v-model="ruleForm.weight"
                            :min="0"
                            :precision="2"
                            placeholder="请输入重量"
                            style="width: 100%"
                        >
                            <template #append>kg</template>
                        </el-input-number>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="20">
                <el-col :span="12">
                    <el-form-item label="状态" prop="status">
                        <el-select v-model="ruleForm.status" placeholder="请选择状态" style="width: 100%">
                            <el-option label="待出仓" :value="1" />
                            <el-option label="已出仓" :value="2" />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="20">
                <el-col :span="24">
                    <el-form-item label="照片">
                        <el-upload
                            v-model:file-list="photoFileList"
                            action="#"
                            list-type="picture-card"
                            :auto-upload="false"
                            :on-preview="handlePictureCardPreview"
                            :on-remove="handlePhotoRemove"
                            :before-upload="beforePhotoUpload"
                            :limit="9"
                        >
                            <el-icon><Plus /></el-icon>
                        </el-upload>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="20">
                <el-col :span="24">
                    <el-form-item label="视频">
                        <el-upload
                            v-model:file-list="videoFileList"
                            action="#"
                            :auto-upload="false"
                            :on-remove="handleVideoRemove"
                            :before-upload="beforeVideoUpload"
                            :limit="3"
                        >
                            <el-button type="primary">选择视频</el-button>
                        </el-upload>
                    </el-form-item>
                </el-col>
            </el-row>

            <el-row :gutter="20">
                <el-col :span="24">
                    <el-form-item label="备注">
                        <el-input
                            v-model="ruleForm.remark"
                            type="textarea"
                            :rows="3"
                            placeholder="请输入备注"
                            maxlength="500"
                            show-word-limit
                        />
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>

        <template #footer>
            <span class="dialog-footer">
                <el-button v-if="!data.isDetail" :loading="data.saveLoading" type="primary" @click="onClickSave">
                    保存
                </el-button>
                <el-button @click="handleClose">{{ data.isDetail ? '关闭' : '取消' }}</el-button>
            </span>
        </template>
    </el-dialog>

    <!-- 目的地地址选择地图 -->
    <el-dialog v-model="showDestinationLocationMap" title="选择目的地地址" width="900px">
        <baidu-map 
            class="map" 
            :center="ruleForm.destinationLon && ruleForm.destinationLat ? {lng: parseFloat(ruleForm.destinationLon), lat: parseFloat(ruleForm.destinationLat)} : {lng: 116.404, lat: 39.915}" 
            :zoom="15" 
            :scroll-wheel-zoom="true"
            @click="handleDestinationLocationClick"
            style="height: 500px"
        >
            <bm-marker 
                v-if="ruleForm.destinationLon && ruleForm.destinationLat" 
                :position="{lng: parseFloat(ruleForm.destinationLon), lat: parseFloat(ruleForm.destinationLat)}" 
                :dragging="true" 
                @dragging="handleDestinationMarkerDrag" 
            />
            <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="showDestinationLocationMap = false">取消</el-button>
                <el-button type="primary" @click="showDestinationLocationMap = false">确定</el-button>
            </span>
        </template>
    </el-dialog>

    <!-- 图片预览 -->
    <el-dialog v-model="showImageViewer" title="图片预览" width="800px">
        <el-image :src="imageViewerUrl" style="width: 100%" fit="contain" />
    </el-dialog>
</template>

<script setup>
import { ref, reactive, watch, nextTick, computed } from 'vue';
import { ElMessage } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import { BaiduMap, BmMapType, BmMarker } from 'vue-baidu-map-3x';
import { warehouseOutAdd, warehouseOutEdit, warehouseOutDetail, warehouseOutList } from '@/api/warehouseOut.js';
import { warehouseAll } from '@/api/warehouse.js';
import { warehouseInList as warehouseInListApi } from '@/api/warehouseIn.js';
import { orderPageQuery, shippingList } from '@/api/shipping.js';

const emits = defineEmits(['success']);
const formDataRef = ref(null);
const showDestinationLocationMap = ref(false);
const showImageViewer = ref(false);
const imageViewerUrl = ref('');
const photoFileList = ref([]);
const videoFileList = ref([]);

const warehouseList = ref([]);
const warehouseInList = ref([]); // 所有可用的进仓记录
const orderList = ref([]);
const deliveryList = ref([]);

const data = reactive({
    dialogVisible: false,
    saveLoading: false,
    editId: null,
    isDetail: false,
});

const ruleForm = reactive({
    id: null,
    warehouseId: null,
    warehouseInId: null, // 保留用于兼容，但不再使用
    warehouseInRelations: [], // 进仓记录关联数组，每个元素包含：warehouseInId, totalCount, outCount, remainingCount, outCountThisTime
    orderId: [],
    deliveryId: null,
    destinationLocation: '',
    destinationLon: '',
    destinationLat: '',
    cattleCount: null,
    weight: null,
    outTime: '',
    photos: '',
    videos: '',
    remark: '',
    status: 1,
});

const rules = reactive({
    warehouseId: [
        { required: true, message: '请选择中转仓', trigger: 'change' },
    ],
    deliveryId: [
        { required: true, message: '请选择运送清单', trigger: 'change' },
    ],
    warehouseInRelations: [
        { 
            validator: (rule, value, callback) => {
                if (!value || value.length === 0) {
                    callback(new Error('请至少添加一个进仓记录'));
                } else {
                    // 检查每个关联记录是否都填写了出仓数量
                    const hasEmpty = value.some(item => !item.warehouseInId || !item.outCountThisTime || item.outCountThisTime <= 0);
                    if (hasEmpty) {
                        callback(new Error('请为每个进仓记录填写出仓数量'));
                    } else {
                        // 检查总出仓数量
                        const totalOutCount = value.reduce((sum, item) => sum + (item.outCountThisTime || 0), 0);
                        if (totalOutCount <= 0) {
                            callback(new Error('总出仓数量必须大于0'));
                        } else {
                            callback();
                        }
                    }
                }
            }, 
            trigger: 'change' 
        },
    ],
    cattleCount: [
        { required: true, message: '请输入牛只数量', trigger: 'blur' },
        { type: 'number', min: 1, message: '牛只数量必须大于0', trigger: 'blur' },
    ],
    outTime: [
        { required: true, message: '请选择出仓时间', trigger: 'change' },
    ],
});

// 加载中转仓列表
const loadWarehouseList = async () => {
    try {
        const res = await warehouseAll();
        if (res.code === 200) {
            warehouseList.value = res.data || [];
        }
    } catch (error) {
        console.error('加载中转仓列表失败', error);
    }
};

// 加载进仓记录列表（不限制状态，避免过滤掉待进仓记录）
const loadWarehouseInList = async (warehouseId) => {
    try {
        console.log('开始加载进仓记录列表，warehouseId:', warehouseId);
        const params = { pageNum: 1, pageSize: 1000 };
        if (warehouseId) {
            params.warehouseId = warehouseId;
        }
        console.log('调用接口参数:', params);
        const res = await warehouseInListApi(params);
        console.log('进仓记录接口返回:', res);
        
        if (res.code === 200) {
            const responseData = res.data || res;
            let list = [];
            if (responseData && typeof responseData === 'object' && 'rows' in responseData) {
                list = responseData.rows || [];
            } else if (responseData && responseData.data && 'rows' in responseData.data) {
                list = responseData.data.rows || [];
            } else if (Array.isArray(responseData)) {
                list = responseData;
            }
            
            console.log('解析后的进仓记录列表:', list);
            
            // 直接使用数据库返回的 remainingCount 字段，并过滤掉剩余数量为0的记录
            // 在编辑模式下，需要将当前编辑的出仓记录关联的进仓记录的剩余数量加回去
            const currentEditId = data.editId;
            console.log('当前编辑的出仓记录ID:', currentEditId);
            
            // 如果正在编辑，需要获取当前编辑的出仓记录详情，以便恢复已关联进仓记录的剩余数量
            let currentEditOutRelations = new Map(); // key: 进仓记录ID, value: 当前编辑的出仓数量
            if (currentEditId && ruleForm.warehouseInRelations && ruleForm.warehouseInRelations.length > 0) {
                // 从表单中获取当前编辑的出仓记录关联的进仓记录和出仓数量
                ruleForm.warehouseInRelations.forEach(rel => {
                    if (rel.warehouseInId && rel.outCountThisTime) {
                        const currentCount = currentEditOutRelations.get(rel.warehouseInId) || 0;
                        currentEditOutRelations.set(rel.warehouseInId, currentCount + rel.outCountThisTime);
                    }
                });
                console.log('当前编辑的出仓记录关联的进仓记录和数量:', Array.from(currentEditOutRelations.entries()));
            }
            
            // 处理进仓记录列表，使用数据库的 remainingCount 字段
            // 如果 remainingCount 字段不存在（数据库未迁移），则使用 cattleCount 作为默认值
            const processedList = list.map(item => {
                // 使用数据库返回的 remainingCount，如果没有则使用 cattleCount（兼容旧数据）
                const totalCount = item.cattleCount || 0;
                let remainingCount = item.remainingCount;
                
                // 如果 remainingCount 为 undefined 或 null，说明数据库字段可能不存在，使用 cattleCount
                if (remainingCount === undefined || remainingCount === null) {
                    remainingCount = totalCount;
                    console.warn(`进仓记录 ${item.inNumber} 没有 remainingCount 字段，使用 cattleCount: ${totalCount}`);
                }
                
                // 在编辑模式下，如果这个进仓记录已经被当前编辑的出仓记录关联，需要将当前编辑的出仓数量加回去
                // 这样用户就可以编辑到进仓总数量（如果没有其他出仓记录关联的话）
                if (currentEditId && currentEditOutRelations.has(item.id)) {
                    const currentEditOutCount = currentEditOutRelations.get(item.id) || 0;
                    remainingCount = remainingCount + currentEditOutCount;
                    console.log(`编辑模式 - 进仓记录 ${item.inNumber}: 恢复当前编辑的出仓数量 ${currentEditOutCount}，剩余数量从 ${item.remainingCount} 调整为 ${remainingCount}`);
                }
                
                const outCount = totalCount - remainingCount;
                
                console.log(`处理进仓记录 ${item.inNumber}: totalCount=${totalCount}, outCount=${outCount}, remainingCount=${remainingCount}`);
                
                return {
                    ...item,
                    outCount: Math.max(0, outCount),
                    remainingCount: Math.max(0, remainingCount),
                    // 标记是否为编辑模式下已关联的记录
                    isCurrentEditRelated: currentEditId && currentEditOutRelations.has(item.id),
                };
            });
            
            // 在编辑模式下，需要保留当前已选择的进仓记录（即使剩余数量为0）
            // 这样用户可以看到已选择的记录，但无法选择新的剩余数量为0的记录
            const currentSelectedIds = new Set();
            if (data.editId && ruleForm.warehouseInRelations) {
                ruleForm.warehouseInRelations.forEach(rel => {
                    if (rel.warehouseInId) {
                        currentSelectedIds.add(rel.warehouseInId);
                    }
                });
            }
            
            // 过滤进仓记录列表
            // 1. 保留当前已选择的记录（编辑模式下，不受剩余数量限制）
            // 2. 过滤掉剩余数量为0的记录（新增模式下或未选择的记录）
            warehouseInList.value = processedList.filter(item => {
                // 如果是当前已选择的记录，保留（编辑模式下需要显示，不受剩余数量限制）
                if (currentSelectedIds.has(item.id)) {
                    return true;
                }
                // 否则，只显示剩余数量 > 0 的记录
                return (item.remainingCount || 0) > 0;
            });
            
            console.log('处理后的进仓记录列表:', warehouseInList.value);
            console.log('当前已选择的进仓记录ID:', Array.from(currentSelectedIds));
            
            // 强制触发响应式更新
            nextTick(() => {
                console.log('nextTick - 进仓记录列表已更新，长度:', warehouseInList.value.length);
            });
        } else {
            console.error('加载进仓记录列表失败，返回码:', res.code, '错误信息:', res.msg);
            ElMessage.warning('加载进仓记录列表失败：' + (res.msg || '未知错误'));
            warehouseInList.value = [];
        }
    } catch (error) {
        console.error('加载进仓记录列表异常:', error);
        ElMessage.error('加载进仓记录列表失败：' + (error.message || '未知错误'));
        warehouseInList.value = [];
    }
};

// 加载订单列表
const loadOrderList = async () => {
    try {
        const res = await orderPageQuery({ pageNum: 1, pageSize: 1000 });
        if (res.code === 200) {
            const responseData = res.data || res;
            if (responseData && typeof responseData === 'object' && 'rows' in responseData) {
                orderList.value = responseData.rows || [];
            } else if (responseData && responseData.data && 'rows' in responseData.data) {
                orderList.value = responseData.data.rows || [];
            } else {
                orderList.value = [];
            }
        }
    } catch (error) {
        console.error('加载订单列表失败', error);
    }
};

// 加载运送清单列表
const loadDeliveryList = async () => {
    try {
        const res = await shippingList({ pageNum: 1, pageSize: 1000 });
        if (res.code === 200) {
            const responseData = res.data || res;
            if (responseData && typeof responseData === 'object' && 'rows' in responseData) {
                deliveryList.value = responseData.rows || [];
            } else if (responseData && responseData.data && 'rows' in responseData.data) {
                deliveryList.value = responseData.data.rows || [];
            } else {
                deliveryList.value = [];
            }
        }
    } catch (error) {
        console.error('加载运送清单列表失败', error);
    }
};

const handleClose = () => {
    if (formDataRef.value) {
        formDataRef.value.resetFields();
    }
    Object.assign(ruleForm, {
        id: null,
        warehouseId: null,
        warehouseInId: null,
        warehouseInRelations: [],
        orderId: [],
        deliveryId: null,
        destinationLocation: '',
        destinationLon: '',
        destinationLat: '',
        cattleCount: null,
        weight: null,
        outTime: '',
        photos: '',
        videos: '',
        remark: '',
        status: 1,
    });
    photoFileList.value = [];
    videoFileList.value = [];
    data.editId = null;
    data.isDetail = false;
    data.dialogVisible = false;
};

const onClickSave = () => {
    if (!formDataRef.value) {
        return;
    }

    formDataRef.value.validate((valid) => {
        if (!valid) {
            return false;
        }

        data.saveLoading = true;

        // 处理订单ID（多个订单用逗号分隔）
        const orderIdStr = ruleForm.orderId && ruleForm.orderId.length > 0 
            ? ruleForm.orderId.join(',') 
            : null;

        // 处理照片和视频URL（多个用逗号分隔）
        const photosStr = photoFileList.value.map(file => file.url || file.response?.data?.url || '').filter(url => url).join(',');
        const videosStr = videoFileList.value.map(file => file.url || file.response?.data?.url || '').filter(url => url).join(',');

        // 处理进仓记录关联（多对多关系）
        console.log('========== 提交前数据检查 ==========');
        console.log('ruleForm.warehouseInRelations:', ruleForm.warehouseInRelations);
        console.log('ruleForm.warehouseInId:', ruleForm.warehouseInId);
        
        const warehouseInRelations = ruleForm.warehouseInRelations
            .filter(item => item.warehouseInId && item.outCountThisTime > 0)
            .map(item => ({
                warehouseInId: item.warehouseInId,
                outCount: item.outCountThisTime,
            }));

        console.log('过滤后的 warehouseInRelations:', warehouseInRelations);

        // 如果有关联的进仓记录，将ID用逗号分隔设置到 warehouseInId（用于兼容旧数据格式）
        // 如果只有一个，直接设置；如果有多个，用逗号分隔
        let warehouseInIdValue = null;
        if (warehouseInRelations.length > 0) {
            if (warehouseInRelations.length === 1) {
                warehouseInIdValue = String(warehouseInRelations[0].warehouseInId);
            } else {
                // 多个ID用逗号分隔
                warehouseInIdValue = warehouseInRelations.map(item => String(item.warehouseInId)).join(',');
            }
            console.log('从 warehouseInRelations 提取 warehouseInIdValue:', warehouseInIdValue);
        } else if (ruleForm.warehouseInId) {
            // 如果没有关联记录但有旧的 warehouseInId，使用旧值
            warehouseInIdValue = String(ruleForm.warehouseInId);
            console.log('使用旧的 warehouseInId:', warehouseInIdValue);
        } else {
            console.warn('警告：warehouseInRelations 为空且 warehouseInId 也为空！');
        }

        console.log('最终提交参数 - warehouseInRelations:', warehouseInRelations);
        console.log('最终提交参数 - warehouseInIdValue:', warehouseInIdValue);
        console.log('==========================================');

        const params = {
            warehouseId: ruleForm.warehouseId,
            warehouseInId: warehouseInIdValue, // 设置为关联的进仓记录ID（单个或逗号分隔的多个）
            warehouseInRelations: warehouseInRelations, // 新增：多对多关联数组
            orderId: orderIdStr,
            deliveryId: ruleForm.deliveryId,
            destinationLocation: ruleForm.destinationLocation,
            destinationLon: ruleForm.destinationLon,
            destinationLat: ruleForm.destinationLat,
            cattleCount: ruleForm.cattleCount,
            weight: ruleForm.weight,
            outTime: ruleForm.outTime,
            photos: photosStr,
            videos: videosStr,
            remark: ruleForm.remark,
        };

        if (data.editId) {
            // 编辑
            params.id = data.editId;
            params.status = ruleForm.status;
            warehouseOutEdit(params)
                .then((res) => {
                    if (res.code === 200) {
                        ElMessage.success('编辑成功');
                        handleClose();
                        emits('success');
                    } else {
                        ElMessage.error(res.msg || '编辑失败');
                    }
                })
                .catch((error) => {
                    ElMessage.error('编辑失败：' + (error.message || '未知错误'));
                })
                .finally(() => {
                    data.saveLoading = false;
                });
        } else {
            // 新增
            warehouseOutAdd(params)
                .then((res) => {
                    if (res.code === 200) {
                        ElMessage.success('新增成功');
                        handleClose();
                        emits('success');
                    } else {
                        ElMessage.error(res.msg || '新增失败');
                    }
                })
                .catch((error) => {
                    ElMessage.error('新增失败：' + (error.message || '未知错误'));
                })
                .finally(() => {
                    data.saveLoading = false;
                });
        }
    });
};

const onShowDialog = (row, isDetail = false) => {
    data.isDetail = isDetail || false;
    data.editId = null;
    
    if (row) {
        data.editId = row.id;
        // 如果是详情模式，先获取详情数据
        if (isDetail) {
            warehouseOutDetail(row.id)
                .then(async (res) => {
                    if (res.code === 200 && res.data) {
                        const detailData = res.data;
                        // 先加载进仓记录列表，以便能够正确显示关联的进仓记录
                        if (detailData.warehouseId) {
                            await loadWarehouseInList(detailData.warehouseId);
                        }
                        
                        Object.assign(ruleForm, {
                            id: detailData.id,
                            warehouseId: detailData.warehouseId,
                            warehouseInId: detailData.warehouseInId,
                            warehouseInRelations: detailData.warehouseInRelations || [], // 加载关联的进仓记录
                            orderId: detailData.orderId ? detailData.orderId.split(',').map(id => parseInt(id)) : [],
                            deliveryId: detailData.deliveryId,
                            destinationLocation: detailData.destinationLocation || '',
                            destinationLon: detailData.destinationLon || '',
                            destinationLat: detailData.destinationLat || '',
                            cattleCount: detailData.cattleCount,
                            weight: detailData.weight,
                            outTime: detailData.outTime || '',
                            photos: detailData.photos || '',
                            videos: detailData.videos || '',
                            remark: detailData.remark || '',
                            status: detailData.status !== undefined ? detailData.status : 1,
                        });
                        // 如果有旧的warehouseInId但没有warehouseInRelations，则转换
                        if (detailData.warehouseInId && (!detailData.warehouseInRelations || detailData.warehouseInRelations.length === 0)) {
                            // 兼容旧数据：将单个warehouseInId转换为关联数组
                            const warehouseIn = warehouseInList.value.find(item => item.id === detailData.warehouseInId);
                            ruleForm.warehouseInRelations = [{
                                warehouseInId: detailData.warehouseInId,
                                totalCount: warehouseIn ? warehouseIn.cattleCount : (detailData.warehouseInCattleCount || detailData.cattleCount || 0),
                                outCount: warehouseIn ? warehouseIn.outCount : 0,
                                remainingCount: warehouseIn ? warehouseIn.remainingCount : (detailData.warehouseInCattleCount || detailData.cattleCount || 0),
                                outCountThisTime: detailData.cattleCount || 0,
                            }];
                        } else if (detailData.warehouseInRelations && detailData.warehouseInRelations.length > 0) {
                            // 如果有warehouseInRelations，需要更新每个关联记录的详细信息
                            ruleForm.warehouseInRelations = detailData.warehouseInRelations.map(relation => {
                                const warehouseIn = warehouseInList.value.find(item => item.id === relation.warehouseInId);
                                return {
                                    warehouseInId: relation.warehouseInId,
                                    totalCount: warehouseIn ? warehouseIn.cattleCount : (relation.totalCount || 0),
                                    outCount: warehouseIn ? warehouseIn.outCount : (relation.outCount || 0),
                                    remainingCount: warehouseIn ? warehouseIn.remainingCount : (relation.remainingCount || 0),
                                    outCountThisTime: relation.outCount || relation.outCountThisTime || 0,
                                };
                            });
                        }
                        // 处理照片和视频文件列表
                        if (detailData.photos) {
                            photoFileList.value = detailData.photos.split(',').map(url => ({ url, name: 'photo' }));
                        }
                        if (detailData.videos) {
                            videoFileList.value = detailData.videos.split(',').map(url => ({ url, name: 'video' }));
                        }
                    }
                })
                .catch((error) => {
                    ElMessage.error('获取详情失败：' + (error.message || '未知错误'));
                });
        } else {
            // 编辑模式，先加载进仓记录列表，然后设置表单数据
            if (row.warehouseId) {
                loadWarehouseInList(row.warehouseId).then(() => {
                    setFormDataForEdit(row);
                });
            } else {
                setFormDataForEdit(row);
            }
        }
    } else {
        // 新增模式，重置表单
        Object.assign(ruleForm, {
            id: null,
            warehouseId: null,
            warehouseInId: null,
            warehouseInRelations: [],
            orderId: [],
            deliveryId: null,
            destinationLocation: '',
            destinationLon: '',
            destinationLat: '',
            cattleCount: null,
            weight: null,
            outTime: '',
            photos: '',
            videos: '',
            remark: '',
            status: 1,
        });
        photoFileList.value = [];
        videoFileList.value = [];
    }
    
    data.dialogVisible = true;
};

// 中转仓选择变化
const handleWarehouseChange = (warehouseId) => {
    console.log('中转仓选择变化，warehouseId:', warehouseId);
    // 清空关联记录
    ruleForm.warehouseInRelations = [];
    // 清空进仓记录列表
    warehouseInList.value = [];
    // 如果选择了中转仓，加载该中转仓的进仓记录
    if (warehouseId) {
        loadWarehouseInList(warehouseId);
    }
};

// 添加进仓记录关联
const addWarehouseInRelation = async () => {
    if (!ruleForm.warehouseId) {
        ElMessage.warning('请先选择中转仓');
        return;
    }
    // 如果进仓记录列表为空，尝试重新加载
    if (warehouseInList.value.length === 0) {
        console.log('进仓记录列表为空，重新加载');
        await loadWarehouseInList(ruleForm.warehouseId);
    }
    console.log('添加进仓记录关联行，当前列表长度:', warehouseInList.value.length);
    ruleForm.warehouseInRelations.push({
        warehouseInId: null,
        totalCount: 0,
        outCount: 0,
        remainingCount: 0,
        outCountThisTime: undefined, // 使用 undefined 而不是 null，避免 el-input-number 报错
    });
    console.log('添加后的关联行数:', ruleForm.warehouseInRelations.length);
    console.log('添加后的 warehouseInList:', warehouseInList.value);
    // 等待 nextTick 确保 computed 重新计算
    nextTick(() => {
        console.log('nextTick - availableWarehouseInLists:', availableWarehouseInLists.value);
    });
};

// 删除进仓记录关联
const removeWarehouseInRelation = (index) => {
    ruleForm.warehouseInRelations.splice(index, 1);
    handleOutCountChange();
};

// 创建一个计算属性，为每一行生成可用的进仓记录列表
// 这样可以避免在模板中重复调用函数，提高性能
const availableWarehouseInLists = computed(() => {
    const result = ruleForm.warehouseInRelations.map((_, currentIndex) => {
        // 获取已选择的其他行的进仓ID
        const selectedIds = ruleForm.warehouseInRelations
            .map((item, index) => index !== currentIndex ? item.warehouseInId : null)
            .filter(id => id != null);
        
        // 过滤出可用的进仓记录
        const available = warehouseInList.value.filter(item => {
            // 只显示有剩余数量的进仓记录，且未被其他行选择
            return (item.remainingCount || 0) > 0 && !selectedIds.includes(item.id);
        });
        
        console.log(`computed[${currentIndex}]: warehouseInList.length=${warehouseInList.value.length}, selectedIds=${JSON.stringify(selectedIds)}, available.length=${available.length}`);
        
        return available;
    });
    
    console.log('availableWarehouseInLists computed:', result);
    return result;
});

// 获取可用的进仓记录列表（排除已选择的）
// 使用缓存的计算属性，避免重复计算
const getAvailableWarehouseInList = (currentIndex) => {
    // 确保索引有效
    if (currentIndex < 0 || currentIndex >= availableWarehouseInLists.value.length) {
        console.warn(`getAvailableWarehouseInList: 无效的索引 ${currentIndex}, 当前关联行数: ${ruleForm.warehouseInRelations.length}`);
        // 如果索引无效，直接计算返回
        const selectedIds = ruleForm.warehouseInRelations
            .map((item, index) => index !== currentIndex ? item.warehouseInId : null)
            .filter(id => id != null);
        return warehouseInList.value.filter(item => {
            return (item.remainingCount || 0) > 0 && !selectedIds.includes(item.id);
        });
    }
    const result = availableWarehouseInLists.value[currentIndex] || [];
    console.log(`getAvailableWarehouseInList(${currentIndex}):`, result.length, 'items', result);
    return result;
};

// 进仓记录关联变化
const handleWarehouseInRelationChange = (row, index) => {
    if (row.warehouseInId) {
        const warehouseIn = warehouseInList.value.find(item => item.id === row.warehouseInId);
        if (warehouseIn) {
            row.totalCount = warehouseIn.cattleCount || 0;
            row.outCount = warehouseIn.outCount || 0;
            // 在编辑模式下，如果这是已关联的记录，使用调整后的剩余数量（已经加回了当前编辑的数量）
            // 在新增模式下，使用正常的剩余数量
            row.remainingCount = warehouseIn.remainingCount || 0;
            
            // 自动设置本次出仓数量为剩余数量（如果剩余数量大于0）
            // 在编辑模式下，如果这是已关联的记录，可以编辑到剩余数量（包括当前编辑的数量）
            if (row.remainingCount > 0 && !row.outCountThisTime) {
                row.outCountThisTime = row.remainingCount;
            }
            
            console.log(`进仓记录关联变化 - ${warehouseIn.inNumber}: totalCount=${row.totalCount}, remainingCount=${row.remainingCount}, isCurrentEditRelated=${warehouseIn.isCurrentEditRelated}`);
        }
    } else {
        row.totalCount = 0;
        row.outCount = 0;
        row.remainingCount = 0;
        row.outCountThisTime = undefined;
    }
    handleOutCountChange();
};

// 出仓数量变化
const handleOutCountChange = () => {
    // 自动计算总出仓数量
    const totalOutCount = getTotalOutCount();
    ruleForm.cattleCount = totalOutCount;
    
    // 触发表单验证
    if (formDataRef.value) {
        formDataRef.value.validateField('warehouseInRelations');
        formDataRef.value.validateField('cattleCount');
    }
};

// 计算总出仓数量
const getTotalOutCount = () => {
    return ruleForm.warehouseInRelations.reduce((sum, item) => {
        return sum + (item.outCountThisTime || 0);
    }, 0);
};

// 运送清单选择变化
const handleDeliveryChange = (deliveryId) => {
    // 可以在这里添加逻辑
};

// 打开目的地地图选择地址
const openDestinationLocationMap = () => {
    if (ruleForm.destinationLocation && ruleForm.destinationLocation.trim()) {
        showDestinationLocationMap.value = true;
        setTimeout(() => {
            if (window.BMap && window.BMap.Geocoder) {
                const geocoder = new window.BMap.Geocoder();
                geocoder.getPoint(ruleForm.destinationLocation, (point) => {
                    if (point) {
                        ruleForm.destinationLon = point.lng;
                        ruleForm.destinationLat = point.lat;
                        ElMessage.success('已定位到该地址');
                    } else {
                        ElMessage.warning('未找到该地址，请在地图上手动选择');
                    }
                });
            }
        }, 500);
    } else {
        showDestinationLocationMap.value = true;
    }
};

// 地图点击事件
const handleDestinationLocationClick = (e) => {
    ruleForm.destinationLon = e.point.lng;
    ruleForm.destinationLat = e.point.lat;
    if (window.BMap && window.BMap.Geocoder) {
        const geocoder = new window.BMap.Geocoder();
        geocoder.getLocation(e.point, (res) => {
            if (res) {
                ruleForm.destinationLocation = res.address;
                ElMessage.success('已设置目的地地址');
            }
        });
    }
};

// 标记拖拽事件
const handleDestinationMarkerDrag = (e) => {
    ruleForm.destinationLon = e.point.lng;
    ruleForm.destinationLat = e.point.lat;
    if (window.BMap && window.BMap.Geocoder) {
        const geocoder = new window.BMap.Geocoder();
        geocoder.getLocation(e.point, (res) => {
            if (res) {
                ruleForm.destinationLocation = res.address;
            }
        });
    }
};

// 图片预览
const handlePictureCardPreview = (file) => {
    imageViewerUrl.value = file.url || file.response?.data?.url || '';
    showImageViewer.value = true;
};

// 删除照片
const handlePhotoRemove = (file) => {
    // 文件列表会自动更新
};

// 删除视频
const handleVideoRemove = (file) => {
    // 文件列表会自动更新
};

// 上传前验证照片
const beforePhotoUpload = (file) => {
    const isImage = file.type.startsWith('image/');
    const isLt10M = file.size / 1024 / 1024 < 10;

    if (!isImage) {
        ElMessage.error('只能上传图片文件!');
        return false;
    }
    if (!isLt10M) {
        ElMessage.error('图片大小不能超过 10MB!');
        return false;
    }
    return false; // 阻止自动上传，手动处理
};

// 上传前验证视频
const beforeVideoUpload = (file) => {
    const isVideo = file.type.startsWith('video/');
    const isLt100M = file.size / 1024 / 1024 < 100;

    if (!isVideo) {
        ElMessage.error('只能上传视频文件!');
        return false;
    }
    if (!isLt100M) {
        ElMessage.error('视频大小不能超过 100MB!');
        return false;
    }
    return false; // 阻止自动上传，手动处理
};

// 设置编辑模式的表单数据
const setFormDataForEdit = (row) => {
    Object.assign(ruleForm, {
        id: row.id,
        warehouseId: row.warehouseId,
        warehouseInId: row.warehouseInId,
        warehouseInRelations: row.warehouseInRelations || [], // 加载关联的进仓记录
        orderId: row.orderId ? row.orderId.split(',').map(id => parseInt(id)) : [],
        deliveryId: row.deliveryId,
        destinationLocation: row.destinationLocation || '',
        destinationLon: row.destinationLon || '',
        destinationLat: row.destinationLat || '',
        cattleCount: row.cattleCount,
        weight: row.weight,
        outTime: row.outTime || '',
        photos: row.photos || '',
        videos: row.videos || '',
        remark: row.remark || '',
        status: row.status !== undefined ? row.status : 1,
    });
    // 如果有旧的warehouseInId但没有warehouseInRelations，则转换
    // 注意：warehouseInId 现在可能是字符串（多个ID用逗号分隔）
    if (row.warehouseInId && (!row.warehouseInRelations || row.warehouseInRelations.length === 0)) {
        console.log('编辑模式 - 检测到 warehouseInId 但没有 warehouseInRelations，开始转换');
        console.log('row.warehouseInId:', row.warehouseInId, '类型:', typeof row.warehouseInId);
        
        // 兼容旧数据：将 warehouseInId（可能是单个ID或逗号分隔的多个ID）转换为关联数组
        const warehouseInIdStr = String(row.warehouseInId);
        const warehouseInIds = warehouseInIdStr.split(',').map(id => id.trim()).filter(id => id);
        
        console.log('解析出的进仓记录ID数组:', warehouseInIds);
        
        ruleForm.warehouseInRelations = warehouseInIds.map(warehouseInIdStr => {
            const warehouseInId = parseInt(warehouseInIdStr);
            const warehouseIn = warehouseInList.value.find(item => item.id === warehouseInId);
            
            console.log(`处理进仓记录ID ${warehouseInId}:`, warehouseIn ? '找到' : '未找到');
            
            // 如果找不到对应的进仓记录，使用默认值
            return {
                warehouseInId: warehouseInId,
                totalCount: warehouseIn ? warehouseIn.cattleCount : 0,
                outCount: warehouseIn ? warehouseIn.outCount : 0,
                remainingCount: warehouseIn ? warehouseIn.remainingCount : 0,
                outCountThisTime: warehouseIn ? Math.min(warehouseIn.remainingCount || 0, row.cattleCount || 0) : (row.cattleCount || 0),
            };
        });
        
        console.log('转换后的 warehouseInRelations:', ruleForm.warehouseInRelations);
    } else if (row.warehouseInRelations && row.warehouseInRelations.length > 0) {
        // 如果有warehouseInRelations，需要更新每个关联记录的详细信息
        ruleForm.warehouseInRelations = row.warehouseInRelations.map(relation => {
            const warehouseIn = warehouseInList.value.find(item => item.id === relation.warehouseInId);
            return {
                warehouseInId: relation.warehouseInId,
                totalCount: warehouseIn ? warehouseIn.cattleCount : (relation.totalCount || 0),
                outCount: warehouseIn ? warehouseIn.outCount : (relation.outCount || 0),
                remainingCount: warehouseIn ? warehouseIn.remainingCount : (relation.remainingCount || 0),
                outCountThisTime: relation.outCount || relation.outCountThisTime || 0,
            };
        });
    }
    // 处理照片和视频文件列表
    if (row.photos) {
        photoFileList.value = row.photos.split(',').map(url => ({ url, name: 'photo' }));
    }
    if (row.videos) {
        videoFileList.value = row.videos.split(',').map(url => ({ url, name: 'video' }));
    }
};

// 监听对话框打开，加载数据
watch(() => data.dialogVisible, (newVal) => {
    if (newVal) {
        console.log('对话框打开，开始加载数据');
        loadWarehouseList();
        // 如果已有中转仓ID，则加载对应的进仓记录；否则等待用户选择中转仓
        if (ruleForm.warehouseId) {
            console.log('已有中转仓ID，加载进仓记录:', ruleForm.warehouseId);
            loadWarehouseInList(ruleForm.warehouseId);
        } else {
            console.log('暂无中转仓ID，等待用户选择');
            // 清空进仓记录列表
            warehouseInList.value = [];
        }
        loadOrderList();
        loadDeliveryList();
    }
});

// 暴露方法给父组件调用
defineExpose({
    onShowDialog,
});
</script>

<style scoped lang="scss">
.map {
    width: 100%;
    height: 500px;
}
</style>

