<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-col :span="12">
                    <el-form-item label="进仓记录" prop="warehouseInId">
                        <el-select 
                            v-model="ruleForm.warehouseInId" 
                            placeholder="请选择进仓记录（可选）" 
                            clearable 
                            filterable 
                            style="width: 100%"
                            @change="handleWarehouseInChange"
                        >
                            <el-option
                                v-for="item in warehouseInList"
                                :key="item.id"
                                :label="`${item.inNumber || '--'} - ${item.cattleCount || 0}头`"
                                :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="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%"
                        />
                    </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 } 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 } 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,
    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' },
    ],
    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 {
        const params = { pageNum: 1, pageSize: 1000 };
        if (warehouseId) {
            params.warehouseId = warehouseId;
        }
        const res = await warehouseInListApi(params);
        if (res.code === 200) {
            const responseData = res.data || res;
            if (responseData && typeof responseData === 'object' && 'rows' in responseData) {
                warehouseInList.value = responseData.rows || [];
            } else if (responseData && responseData.data && 'rows' in responseData.data) {
                warehouseInList.value = responseData.data.rows || [];
            } else {
                warehouseInList.value = [];
            }
        }
    } catch (error) {
        console.error('加载进仓记录列表失败', error);
    }
};

// 加载订单列表
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,
        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(',');

        const params = {
            warehouseId: ruleForm.warehouseId,
            warehouseInId: ruleForm.warehouseInId,
            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((res) => {
                    if (res.code === 200 && res.data) {
                        const detailData = res.data;
                        Object.assign(ruleForm, {
                            id: detailData.id,
                            warehouseId: detailData.warehouseId,
                            warehouseInId: detailData.warehouseInId,
                            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,
                        });
                        // 处理照片和视频文件列表
                        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 {
            // 编辑模式，直接使用传入的数据
            Object.assign(ruleForm, {
                id: row.id,
                warehouseId: row.warehouseId,
                warehouseInId: row.warehouseInId,
                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,
            });
            // 处理照片和视频文件列表
            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' }));
            }
        }
    } else {
        // 新增模式，重置表单
        Object.assign(ruleForm, {
            id: null,
            warehouseId: null,
            warehouseInId: null,
            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) => {
    // 加载该中转仓的进仓记录
    loadWarehouseInList(warehouseId);
};

// 进仓记录选择变化
const handleWarehouseInChange = (warehouseInId) => {
    // 如果选择了进仓记录，可以自动填充一些信息
    if (warehouseInId) {
        const warehouseIn = warehouseInList.value.find(item => item.id === warehouseInId);
        if (warehouseIn) {
            // 可以自动填充牛只数量等信息
            if (!ruleForm.cattleCount && warehouseIn.cattleCount) {
                ruleForm.cattleCount = warehouseIn.cattleCount;
            }
        }
    }
};

// 运送清单选择变化
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; // 阻止自动上传，手动处理
};

// 监听对话框打开，加载数据
watch(() => data.dialogVisible, (newVal) => {
    if (newVal) {
        loadWarehouseList();
        loadWarehouseInList();
        loadOrderList();
        loadDeliveryList();
    }
});

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

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

