<template>
    <div class="page-container">
        <base-search :formItemList="formItemList" @search="handleSearch" ref="baseSearchRef" />
        <div class="action-bar">
            <el-button type="primary" @click="openDialog()">新增屠宰场</el-button>
        </div>
        <div class="main-container">
            <el-table :data="data.rows" border v-loading="data.loading" element-loading-text="数据加载中..." style="width: 100%">
                <el-table-column label="屠宰场名称" prop="houseName" min-width="150" />
                <el-table-column label="屠宰场编码" prop="slaughterCode" min-width="150" />
                <el-table-column label="容量" prop="capacity" width="90" />
                <el-table-column label="地址" prop="address" min-width="200" />
                <el-table-column label="负责人" prop="person" min-width="120" />
                <el-table-column label="联系电话" prop="phone" min-width="140" />
                <el-table-column label="状态" prop="status" width="90">
                    <template #default="scope">
                        <el-tag v-if="scope.row.status === 1" type="success">启用</el-tag>
                        <el-tag v-else type="info">停用</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="创建时间" prop="createTime" width="180" />
                <el-table-column label="操作" width="180">
                    <template #default="scope">
                        <el-button link type="primary" @click="openDialog(scope.row)">编辑</el-button>
                        <el-button link type="primary" @click="locateOnMap(scope.row)">定位</el-button>
                        <el-button link type="danger" @click="handleDelete(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
                <template #empty>
                    <div class="dataListOnEmpty">暂无数据</div>
                </template>
            </el-table>
            <pagination v-model:limit="form.pageSize" v-model:page="form.pageNum" :total="data.total" @pagination="getList" />
        </div>

        <el-dialog v-model="dialog.visible" :title="dialog.title" width="520px" :close-on-click-modal="false">
            <el-form ref="dialogFormRef" :model="dialog.form" :rules="dialog.rules" label-width="110px">
                <el-form-item label="屠宰场名称" prop="houseName">
                    <el-input v-model="dialog.form.houseName" placeholder="请输入屠宰场名称" />
                </el-form-item>
                <el-form-item label="屠宰场编码" prop="slaughterCode">
                    <el-input v-model="dialog.form.slaughterCode" placeholder="不填将自动生成" />
                </el-form-item>
                <el-form-item label="容量" prop="capacity">
                    <el-input-number v-model="dialog.form.capacity" :min="0" :step="1" style="width: 200px" />
                </el-form-item>
                <el-form-item label="地址" prop="address">
                    <el-input
                        v-model="dialog.form.address"
                        placeholder="请输入地址"
                        style="width: calc(100% - 100px); margin-right: 10px"
                    />
                    <el-button type="primary" @click="openLocationMap">选择位置</el-button>
                </el-form-item>
                <el-form-item label="经度" prop="longitude">
                    <el-input v-model="dialog.form.longitude" placeholder="经度" disabled />
                </el-form-item>
                <el-form-item label="纬度" prop="latitude">
                    <el-input v-model="dialog.form.latitude" placeholder="纬度" disabled />
                </el-form-item>
                <el-form-item label="负责人姓名" prop="person">
                    <el-input v-model="dialog.form.person" placeholder="请输入负责人姓名" />
                </el-form-item>
                <el-form-item label="联系电话" prop="phone">
                    <el-input v-model="dialog.form.phone" placeholder="请输入联系电话" />
                </el-form-item>
                <el-form-item label="状态" prop="status">
                    <el-switch v-model="dialog.form.status" :active-value="1" :inactive-value="0" />
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input v-model="dialog.form.remark" type="textarea" :rows="3" placeholder="请输入备注" />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="dialog.visible = false">取消</el-button>
                <el-button type="primary" @click="submitDialog">确定</el-button>
            </template>
        </el-dialog>

        <!-- 地址选择地图 -->
        <el-dialog v-model="showLocationMap" title="选择地址" width="900px">
            <baidu-map
                class="map"
                :center="mapCenter"
                :zoom="15"
                :scroll-wheel-zoom="true"
                @click="handleLocationClick"
                style="height: 500px"
            >
                <bm-marker
                    v-if="dialog.form.longitude && dialog.form.latitude"
                    :position="{ lng: parseFloat(dialog.form.longitude), lat: parseFloat(dialog.form.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>
    </div>
</template>

<script setup>
import { reactive, ref, onMounted, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { BaiduMap, BmMapType, BmMarker } from 'vue-baidu-map-3x';
import baseSearch from '@/components/common/searchCustom/index.vue';
import { slaughterHouseList, slaughterHouseAdd, slaughterHouseEdit, slaughterHouseDel } from '@/api/slaughter.js';

const baseSearchRef = ref();
const dialogFormRef = ref();
const showLocationMap = ref(false);

const formItemList = reactive([
    {
        label: '屠宰场名称',
        param: 'houseName',
        type: 'input',
        placeholder: '请输入屠宰场名称',
        span: 8,
        labelWidth: 100,
    },
    {
        label: '屠宰场编码',
        param: 'slaughterCode',
        type: 'input',
        placeholder: '请输入屠宰场编码',
        span: 8,
        labelWidth: 100,
    },
    {
        label: '状态',
        param: 'status',
        type: 'select',
        status: [
            { label: '启用', value: 1 },
            { label: '停用', value: 0 },
        ],
        placeholder: '请选择状态',
        span: 8,
        labelWidth: 100,
    },
]);

const data = reactive({
    rows: [],
    total: 0,
    loading: false,
});

const form = reactive({
    pageNum: 1,
    pageSize: 10,
});

const dialog = reactive({
    visible: false,
    title: '新增屠宰场',
    form: {
        id: null,
        houseName: '',
        slaughterCode: '',
        capacity: null,
        address: '',
        longitude: '',
        latitude: '',
        person: '',
        phone: '',
        status: 1,
        remark: '',
    },
    rules: {
        houseName: [{ required: true, message: '请输入屠宰场名称', trigger: 'blur' }],
        capacity: [{ required: true, message: '请输入容量', trigger: 'change' }],
        address: [{ required: true, message: '请输入地址', trigger: 'blur' }],
        phone: [{ pattern: /^1[3-9]\d{9}$/, message: '请输入有效手机号', trigger: 'blur' }],
    },
});

const resetDialogForm = () => {
    dialog.form = {
        id: null,
        houseName: '',
        slaughterCode: '',
        capacity: null,
        address: '',
        longitude: '',
        latitude: '',
        person: '',
        phone: '',
        status: 1,
        remark: '',
    };
    dialog.title = '新增屠宰场';
};

const getList = () => {
    data.loading = true;
    const params = { ...form, ...baseSearchRef.value.penetrateParams() };
    slaughterHouseList(params)
        .then((res) => {
            // 兼容结构：
            // axiosRes.data = { code, msg, data: { code, msg, data: { total, rows } } }
            // 或 axiosRes.data = { code, msg, data: { total, rows } }
            // 或 axiosRes.data = { total, rows }
            const resp = res?.data || {};
            const inner = resp?.data?.data || resp?.data || resp;
            data.rows = inner.rows || inner.data?.rows || [];
            data.total = inner.total || inner.data?.total || 0;
        })
        .catch((err) => {
            console.error(err);
            ElMessage.error('查询失败');
        })
        .finally(() => {
            data.loading = false;
        });
};

const handleSearch = () => {
    form.pageNum = 1;
    getList();
};

const openDialog = (row) => {
    resetDialogForm();
    if (row) {
        dialog.title = '编辑屠宰场';
        Object.assign(dialog.form, row);
    }
    dialog.visible = true;
};

const locateOnMap = (row) => {
    if (row && row.longitude && row.latitude) {
        dialog.form.longitude = row.longitude.toString();
        dialog.form.latitude = row.latitude.toString();
        dialog.form.address = row.address || dialog.form.address;
        showLocationMap.value = true;
    } else {
        ElMessage.warning('该记录无有效经纬度');
    }
};

const openLocationMap = () => {
    // 如果输入了地址，先尝试地理编码定位
    if (dialog.form.address && dialog.form.address.trim()) {
        showLocationMap.value = true;
        setTimeout(() => {
            geocodeAddress(dialog.form.address, true);
        }, 300);
    } else {
        showLocationMap.value = true;
    }
};

const geocodeAddress = (address, showToast = false) => {
    if (!address || !window.BMap || !window.BMap.Geocoder) {
        return;
    }
    try {
        const geocoder = new window.BMap.Geocoder();
        geocoder.getPoint(address, (point) => {
            if (point) {
                dialog.form.longitude = point.lng.toFixed(6);
                dialog.form.latitude = point.lat.toFixed(6);
                showToast && ElMessage.success('已定位到该地址');
            } else {
                showToast && ElMessage.warning('未找到该地址，请在地图上手动选择');
            }
        });
    } catch (e) {
        // ignore geocode errors
    }
};

const handleLocationClick = (e) => {
    if (e && e.point) {
        dialog.form.longitude = e.point.lng.toFixed(6);
        dialog.form.latitude = e.point.lat.toFixed(6);
        // 反向地理编码回填地址
        if (window.BMap && window.BMap.Geocoder) {
            const geocoder = new window.BMap.Geocoder();
            geocoder.getLocation(e.point, (res) => {
                if (res && res.address) {
                    dialog.form.address = res.address;
                }
            });
        }
    }
};

const handleMarkerDrag = (e) => {
    if (e && e.point) {
        dialog.form.longitude = e.point.lng.toFixed(6);
        dialog.form.latitude = e.point.lat.toFixed(6);
        if (window.BMap && window.BMap.Geocoder) {
            const geocoder = new window.BMap.Geocoder();
            geocoder.getLocation(e.point, (res) => {
                if (res && res.address) {
                    dialog.form.address = res.address;
                }
            });
        }
    }
};

const mapCenter = computed(() => {
    if (dialog.form.longitude && dialog.form.latitude) {
        return { lng: parseFloat(dialog.form.longitude), lat: parseFloat(dialog.form.latitude) };
    }
    return { lng: 116.404, lat: 39.915 };
});

const submitDialog = () => {
    dialogFormRef.value?.validate((valid) => {
        if (!valid) return;
        const payload = { ...dialog.form };
        const requestApi = payload.id ? slaughterHouseEdit : slaughterHouseAdd;
        requestApi(payload)
            .then(() => {
                ElMessage.success(payload.id ? '更新成功' : '新增成功');
                dialog.visible = false;
                getList();
            })
            .catch((err) => {
                console.error(err);
                ElMessage.error(payload.id ? '更新失败' : '新增失败');
            });
    });
};

const handleDelete = (row) => {
    ElMessageBox.confirm('确认删除该屠宰场吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(() => slaughterHouseDel(row.id))
        .then(() => {
            ElMessage.success('删除成功');
            getList();
        })
        .catch((err) => {
            if (err !== 'cancel') {
                console.error(err);
                ElMessage.error('删除失败');
            }
        });
};

onMounted(() => {
    getList();
});
</script>

<style scoped>
.page-container {
    padding: 0 0 16px;
}

.action-bar {
    display: flex;
    padding: 10px;
    background: #fff;
    margin-bottom: 10px;
}
</style>

