<template>
    <el-dialog
        v-model="data.dialogVisible"
        :title="data.isDetail ? '中转仓详情' : (data.editId ? '编辑中转仓' : '新增中转仓')"
        :before-close="handleClose"
        width="800px"
        :close-on-click-modal="false"
    >
        <el-form ref="formDataRef" :model="ruleForm" :rules="rules" label-width="120px" :disabled="data.isDetail">
            <el-form-item label="中转仓名称" prop="warehouseName">
                <el-input v-model="ruleForm.warehouseName" placeholder="请输入中转仓名称" maxlength="100" />
            </el-form-item>

            <el-form-item label="中转仓编码" prop="warehouseCode">
                <el-input 
                    v-model="ruleForm.warehouseCode" 
                    placeholder="请输入中转仓编码（如不填写将自动生成）" 
                    maxlength="50"
                    :disabled="!!data.editId"
                />
            </el-form-item>

            <el-form-item label="地址" prop="address">
                <el-input 
                    v-model="ruleForm.address" 
                    placeholder="请输入地址" 
                    maxlength="255"
                    style="width: calc(100% - 100px); margin-right: 10px;"
                />
                <el-button type="primary" @click="openLocationMap">选择位置</el-button>
            </el-form-item>

            <el-form-item label="经度">
                <el-input v-model="ruleForm.longitude" placeholder="经度" disabled />
            </el-form-item>

            <el-form-item label="纬度">
                <el-input v-model="ruleForm.latitude" placeholder="纬度" disabled />
            </el-form-item>

            <el-form-item label="容量(头)" prop="capacity">
                <el-input-number
                    v-model="ruleForm.capacity"
                    :min="1"
                    :max="999999"
                    placeholder="请输入容量"
                    style="width: 100%"
                />
            </el-form-item>

            <el-form-item label="负责人姓名">
                <el-input v-model="ruleForm.managerName" placeholder="请输入负责人姓名" maxlength="50" />
            </el-form-item>

            <el-form-item label="联系电话">
                <el-input v-model="ruleForm.managerMobile" placeholder="请输入联系电话" maxlength="20" />
            </el-form-item>

            <el-form-item label="状态" prop="status">
                <el-radio-group v-model="ruleForm.status">
                    <el-radio :label="1">启用</el-radio>
                    <el-radio :label="0">禁用</el-radio>
                </el-radio-group>
            </el-form-item>

            <el-form-item label="备注">
                <el-input
                    v-model="ruleForm.remark"
                    type="textarea"
                    :rows="3"
                    placeholder="请输入备注"
                    maxlength="500"
                    show-word-limit
                />
            </el-form-item>
        </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="showLocationMap" title="选择地址" width="900px">
        <baidu-map 
            class="map" 
            :center="ruleForm.longitude && ruleForm.latitude ? {lng: parseFloat(ruleForm.longitude), lat: parseFloat(ruleForm.latitude)} : {lng: 116.404, lat: 39.915}" 
            :zoom="15" 
            :scroll-wheel-zoom="true"
            @click="handleLocationClick"
            style="height: 500px"
        >
            <bm-marker 
                v-if="ruleForm.longitude && ruleForm.latitude" 
                :position="{lng: parseFloat(ruleForm.longitude), lat: parseFloat(ruleForm.latitude)}" 
                :dragging="true" 
                @dragging="handleMarkerDrag" 
            />
            <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="showLocationMap = false">取消</el-button>
                <el-button type="primary" @click="showLocationMap = false">确定</el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup>
import { ref, reactive, watch } from 'vue';
import { ElMessage } from 'element-plus';
import { BaiduMap, BmMapType, BmMarker } from 'vue-baidu-map-3x';
import { warehouseAdd, warehouseEdit, warehouseDetail } from '@/api/warehouse.js';

const emits = defineEmits(['success']);
const formDataRef = ref(null);
const showLocationMap = ref(false);

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

const ruleForm = reactive({
    id: null,
    warehouseName: '',
    warehouseCode: '',
    address: '',
    longitude: '',
    latitude: '',
    capacity: null,
    managerName: '',
    managerMobile: '',
    status: 1,
    remark: '',
});

const rules = reactive({
    warehouseName: [
        { required: true, message: '请输入中转仓名称', trigger: 'blur' },
    ],
    address: [
        { required: true, message: '请输入地址', trigger: 'blur' },
    ],
    capacity: [
        { required: true, message: '请输入容量', trigger: 'blur' },
        { type: 'number', min: 1, message: '容量必须大于0', trigger: 'blur' },
    ],
    status: [
        { required: true, message: '请选择状态', trigger: 'change' },
    ],
});

const handleClose = () => {
    if (formDataRef.value) {
        formDataRef.value.resetFields();
    }
    // 重置表单数据
    Object.assign(ruleForm, {
        id: null,
        warehouseName: '',
        warehouseCode: '',
        address: '',
        longitude: '',
        latitude: '',
        capacity: null,
        managerName: '',
        managerMobile: '',
        status: 1,
        remark: '',
    });
    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;

        const params = {
            warehouseName: ruleForm.warehouseName,
            warehouseCode: ruleForm.warehouseCode,
            address: ruleForm.address,
            longitude: ruleForm.longitude,
            latitude: ruleForm.latitude,
            capacity: ruleForm.capacity,
            managerName: ruleForm.managerName,
            managerMobile: ruleForm.managerMobile,
            status: ruleForm.status,
            remark: ruleForm.remark,
        };

        if (data.editId) {
            // 编辑
            params.id = data.editId;
            warehouseEdit(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 {
            // 新增
            warehouseAdd(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) {
            warehouseDetail(row.id)
                .then((res) => {
                    if (res.code === 200 && res.data) {
                        const detailData = res.data;
                        Object.assign(ruleForm, {
                            id: detailData.id,
                            warehouseName: detailData.warehouseName || '',
                            warehouseCode: detailData.warehouseCode || '',
                            address: detailData.address || '',
                            longitude: detailData.longitude || '',
                            latitude: detailData.latitude || '',
                            capacity: detailData.capacity,
                            managerName: detailData.managerName || '',
                            managerMobile: detailData.managerMobile || '',
                            status: detailData.status !== undefined ? detailData.status : 1,
                            remark: detailData.remark || '',
                        });
                    }
                })
                .catch((error) => {
                    ElMessage.error('获取详情失败：' + (error.message || '未知错误'));
                });
        } else {
            // 编辑模式，直接使用传入的数据
            Object.assign(ruleForm, {
                id: row.id,
                warehouseName: row.warehouseName || '',
                warehouseCode: row.warehouseCode || '',
                address: row.address || '',
                longitude: row.longitude || '',
                latitude: row.latitude || '',
                capacity: row.capacity,
                managerName: row.managerName || '',
                managerMobile: row.managerMobile || '',
                status: row.status !== undefined ? row.status : 1,
                remark: row.remark || '',
            });
        }
    } else {
        // 新增模式，重置表单
        Object.assign(ruleForm, {
            id: null,
            warehouseName: '',
            warehouseCode: '',
            address: '',
            longitude: '',
            latitude: '',
            capacity: null,
            managerName: '',
            managerMobile: '',
            status: 1,
            remark: '',
        });
    }
    
    data.dialogVisible = true;
};

// 打开地图选择地址
const openLocationMap = () => {
    // 如果输入框有地址，先进行地理编码
    if (ruleForm.address && ruleForm.address.trim()) {
        showLocationMap.value = true;
        setTimeout(() => {
            if (window.BMap && window.BMap.Geocoder) {
                const geocoder = new window.BMap.Geocoder();
                geocoder.getPoint(ruleForm.address, (point) => {
                    if (point) {
                        ruleForm.longitude = point.lng;
                        ruleForm.latitude = point.lat;
                        ElMessage.success('已定位到该地址');
                    } else {
                        ElMessage.warning('未找到该地址，请在地图上手动选择');
                    }
                });
            }
        }, 500);
    } else {
        showLocationMap.value = true;
    }
};

// 地图点击事件
const handleLocationClick = (e) => {
    ruleForm.longitude = e.point.lng;
    ruleForm.latitude = e.point.lat;
    // 反向地理编码获取地址
    if (window.BMap && window.BMap.Geocoder) {
        const geocoder = new window.BMap.Geocoder();
        geocoder.getLocation(e.point, (res) => {
            if (res) {
                ruleForm.address = res.address;
                ElMessage.success('已设置地址');
            }
        });
    }
};

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

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

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

