<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="slaughterHouseId" min-width="140">
                    <template #default="scope">
                        {{ houseNameMap[scope.row.slaughterHouseId] || '-' }}
                    </template>
                </el-table-column>
                <el-table-column label="运送清单ID" prop="deliveryId" width="120" />
                <el-table-column label="订单ID" prop="orderId" width="120" />
                <el-table-column label="起始地" prop="startLocation" min-width="150" />
                <el-table-column label="目的地" prop="endLocation" min-width="150" />
                <el-table-column label="司机" prop="driverName" width="120" />
                <el-table-column label="联系方式" prop="driverMobile" width="140" />
                <el-table-column label="车牌号" prop="licensePlate" width="120" />
                <el-table-column label="出肉率(%)" prop="yieldRate" width="110" />
                <el-table-column label="创建时间" prop="create_time" width="180" />
                <el-table-column label="操作" width="200">
                    <template #default="scope">
                        <el-button link type="primary" @click="openDialog(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="600px" :close-on-click-modal="false">
            <el-form ref="dialogFormRef" :model="dialog.form" :rules="dialog.rules" label-width="120px">
                <el-form-item label="屠宰场" prop="slaughterHouseId">
                    <el-select v-model="dialog.form.slaughterHouseId" placeholder="请选择屠宰场" filterable style="width: 100%">
                        <el-option v-for="item in houseOptions" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                </el-form-item>
                <el-form-item label="运送清单ID" prop="deliveryId">
                    <el-input v-model.number="dialog.form.deliveryId" placeholder="请输入运送清单ID" />
                </el-form-item>
                <el-form-item label="订单ID" prop="orderId">
                    <el-input v-model.number="dialog.form.orderId" placeholder="请输入订单ID（可选）" />
                </el-form-item>
                <el-row :gutter="12">
                    <el-col :span="12">
                        <el-form-item label="起始地" prop="startLocation">
                            <el-input v-model="dialog.form.startLocation" placeholder="请输入起始地" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="目的地" prop="endLocation">
                            <el-input v-model="dialog.form.endLocation" placeholder="请输入目的地" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="12">
                    <el-col :span="12">
                        <el-form-item label="起始经度" prop="startLon">
                            <el-input v-model="dialog.form.startLon" placeholder="请输入起始经度" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="起始纬度" prop="startLat">
                            <el-input v-model="dialog.form.startLat" placeholder="请输入起始纬度" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="12">
                    <el-col :span="12">
                        <el-form-item label="目的地经度" prop="endLon">
                            <el-input v-model="dialog.form.endLon" placeholder="请输入目的地经度" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="目的地纬度" prop="endLat">
                            <el-input v-model="dialog.form.endLat" placeholder="请输入目的地纬度" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="12">
                    <el-col :span="12">
                        <el-form-item label="司机姓名" prop="driverName">
                            <el-input v-model="dialog.form.driverName" placeholder="请输入司机姓名" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="联系方式" prop="driverMobile">
                            <el-input v-model="dialog.form.driverMobile" placeholder="请输入联系方式" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="12">
                    <el-col :span="12">
                        <el-form-item label="车牌号" prop="licensePlate">
                            <el-input v-model="dialog.form.licensePlate" placeholder="请输入车牌号" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="出肉率(%)" prop="yieldRate">
                            <el-input-number v-model="dialog.form.yieldRate" :min="0" :max="100" :step="0.1" style="width: 100%" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <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>
    </div>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import baseSearch from '@/components/common/searchCustom/index.vue';
import {
    slaughterEntryList,
    slaughterEntryAdd,
    slaughterEntryEdit,
    slaughterEntryDel,
} from '@/api/slaughter.js';
import { slaughterHouseAll } from '@/api/slaughter.js';

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

const houseOptions = ref([]);
const houseNameMap = reactive({});

const formItemList = reactive([
    {
        label: '屠宰场',
        param: 'slaughterHouseId',
        type: 'select',
        options: [],
        placeholder: '请选择屠宰场',
        span: 8,
        labelWidth: 100,
    },
    {
        label: '运送清单ID',
        param: 'deliveryId',
        type: 'input',
        placeholder: '请输入运送清单ID',
        span: 8,
        labelWidth: 100,
    },
    {
        label: '订单ID',
        param: 'orderId',
        type: 'input',
        placeholder: '请输入订单ID',
        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,
        slaughterHouseId: null,
        deliveryId: null,
        orderId: null,
        startLocation: '',
        startLon: '',
        startLat: '',
        endLocation: '',
        endLon: '',
        endLat: '',
        driverName: '',
        driverMobile: '',
        licensePlate: '',
        yieldRate: null,
        remark: '',
    },
    rules: {
        slaughterHouseId: [{ required: true, message: '请选择屠宰场', trigger: 'change' }],
        deliveryId: [{ required: true, message: '请输入运送清单ID', trigger: 'blur' }],
    },
});

const resetDialogForm = () => {
    dialog.form = {
        id: null,
        slaughterHouseId: null,
        deliveryId: null,
        orderId: null,
        startLocation: '',
        startLon: '',
        startLat: '',
        endLocation: '',
        endLon: '',
        endLat: '',
        driverName: '',
        driverMobile: '',
        licensePlate: '',
        yieldRate: null,
        remark: '',
    };
    dialog.title = '新增进场';
};

const loadHouseOptions = () => {
    slaughterHouseAll()
        .then((res) => {
            const options = (res.data || []).map((item) => ({
                label: item.house_name || item.houseName,
                value: item.id,
            }));
            houseOptions.value = options;
            formItemList[0].options = options;
            Object.keys(houseNameMap).forEach((key) => delete houseNameMap[key]);
            options.forEach((opt) => {
                houseNameMap[opt.value] = opt.label;
            });
        })
        .catch((err) => {
            console.error(err);
        });
};

const getList = () => {
    data.loading = true;
    const params = { ...form, ...baseSearchRef.value.penetrateParams() };
    slaughterEntryList(params)
        .then((res) => {
            data.rows = res.data.rows || [];
            data.total = res.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 submitDialog = () => {
    dialogFormRef.value?.validate((valid) => {
        if (!valid) return;
        const payload = { ...dialog.form };
        const api = payload.id ? slaughterEntryEdit : slaughterEntryAdd;
        api(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(() => slaughterEntryDel(row.id))
        .then(() => {
            ElMessage.success('删除成功');
            getList();
        })
        .catch((err) => {
            if (err !== 'cancel') {
                console.error(err);
                ElMessage.error('删除失败');
            }
        });
};

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

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

