<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="entryCode" width="150" />
                <el-table-column label="屠宰场" prop="slaughterHouseId" min-width="140">
                    <template #default="scope">
                        {{ houseNameMap[scope.row.slaughterHouseId] || '-' }}
                    </template>
                </el-table-column>
                <el-table-column label="运送清单号" prop="deliveryNumber" width="150" />
                <el-table-column label="订单" min-width="200">
                    <template #default="scope">
                        <div v-if="scope.row.orderBuyerName || scope.row.orderSellerName">
                            <div v-if="scope.row.orderBuyerName">买方：{{ scope.row.orderBuyerName }}</div>
                            <div v-if="scope.row.orderSellerName">卖方：{{ scope.row.orderSellerName }}</div>
                        </div>
                        <span v-else>-</span>
                    </template>
                </el-table-column>
                <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="createTime" 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="entryCode">
                    <el-input 
                        v-model="dialog.form.entryCode" 
                        placeholder="请输入进场编码或点击自动生成"
                        style="width: calc(100% - 100px); margin-right: 10px;"
                    />
                    <el-button type="primary" @click="generateEntryCode">自动生成</el-button>
                </el-form-item>
                <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="运送清单" prop="deliveryId">
                    <el-select 
                        v-model="dialog.form.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-form-item label="订单" prop="orderId">
                    <el-select 
                        v-model="dialog.form.orderId" 
                        placeholder="请选择订单（可选）" 
                        clearable 
                        filterable 
                        style="width: 100%"
                    >
                        <el-option
                            v-for="item in orderList"
                            :key="item.id"
                            :label="`订单${item.id} -买方${item.buyerName}-卖方${item.sellerName}- 单价: ${item.firmPrice || '--'}元/斤`"
                            :value="item.id"
                        />
                    </el-select>
                </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-form-item label="车牌号" prop="licensePlate">
                    <el-input v-model="dialog.form.licensePlate" placeholder="请输入车牌号" />
                </el-form-item>
                <el-row :gutter="12">
                    <el-col :span="12">
                        <el-form-item label="牛只数量" prop="capacity">
                            <el-input-number
                                v-model="dialog.form.capacity"
                                :min="0"
                                :max="9999"
                                placeholder="请输入牛只数量"
                                style="width: 100%"
                            />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="剩余牛只数量" prop="remainingCapacity">
                            <el-input-number
                                v-model="dialog.form.remainingCapacity"
                                :min="0"
                                :max="9999"
                                placeholder="请输入剩余牛只数量"
                                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, slaughterHouseList } from '@/api/slaughter.js';
import { shippingList, orderPageQuery } from '@/api/shipping.js';

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

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

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

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

const loadHouseOptions = () => {
    // 调用列表接口，支持模糊查询
    slaughterHouseList({ pageNum: 1, pageSize: 1000 })
        .then((res) => {
            let responseData = res.data;
            if (responseData && responseData.data && typeof responseData.data === 'object') {
                responseData = responseData.data;
            }
            const list = responseData?.rows || responseData || [];
            const options = list.map((item) => ({
                label: item.house_name || item.houseName,
                value: item.id,
            }));
            houseOptions.value = options;
            formItemList[0].selectOptions = 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) => {
            // 处理嵌套的数据结构：res.data.data.rows 或 res.data.rows
            let responseData = res.data;
            if (responseData && responseData.data && typeof responseData.data === 'object') {
                // 嵌套结构：res.data.data
                responseData = responseData.data;
            }
            data.rows = responseData?.rows || [];
            data.total = responseData?.total || 0;
        })
        .catch((err) => {
            console.error(err);
            ElMessage.error('查询失败');
        })
        .finally(() => {
            data.loading = false;
        });
};

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

// 加载订单列表
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 handleDeliveryChange = (deliveryId) => {
    if (!deliveryId) {
        // 清空相关字段
        dialog.form.startLocation = '';
        dialog.form.startLon = '';
        dialog.form.startLat = '';
        dialog.form.endLocation = '';
        dialog.form.endLon = '';
        dialog.form.endLat = '';
        dialog.form.driverName = '';
        dialog.form.driverMobile = '';
        dialog.form.licensePlate = '';
        dialog.form.capacity = null;
        dialog.form.remainingCapacity = null;
        return;
    }
    
    // 从 deliveryList 中找到对应的运送清单
    const selectedDelivery = deliveryList.value.find(item => item.id === deliveryId);
    if (selectedDelivery) {
        // 自动填充起始地信息
        if (selectedDelivery.startLocation) {
            dialog.form.startLocation = selectedDelivery.startLocation;
        }
        if (selectedDelivery.startLon) {
            dialog.form.startLon = selectedDelivery.startLon;
        }
        if (selectedDelivery.startLat) {
            dialog.form.startLat = selectedDelivery.startLat;
        }
        
        // 自动填充目的地信息
        if (selectedDelivery.endLocation) {
            dialog.form.endLocation = selectedDelivery.endLocation;
        }
        if (selectedDelivery.endLon) {
            dialog.form.endLon = selectedDelivery.endLon;
        }
        if (selectedDelivery.endLat) {
            dialog.form.endLat = selectedDelivery.endLat;
        }
        
        // 自动填充司机信息
        if (selectedDelivery.driverName) {
            dialog.form.driverName = selectedDelivery.driverName;
        }
        // 兼容 driverPhone 和 driverMobile 两种字段名
        if (selectedDelivery.driverPhone || selectedDelivery.driverMobile) {
            dialog.form.driverMobile = selectedDelivery.driverPhone || selectedDelivery.driverMobile;
        }
        
        // 自动填充车牌号
        if (selectedDelivery.licensePlate) {
            dialog.form.licensePlate = selectedDelivery.licensePlate;
        }
        
        // 自动填充牛只数量（从运送清单的 ratedQuantity 填充）
        if (selectedDelivery.ratedQuantity) {
            dialog.form.capacity = selectedDelivery.ratedQuantity;
            // 默认剩余牛只数量等于牛只数量
            dialog.form.remainingCapacity = selectedDelivery.ratedQuantity;
        }
    }
};

// 自动生成进场编码
const generateEntryCode = () => {
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const dateStr = `${year}${month}${day}`;
    
    // 生成一个简单的编码：SE + yyyyMMdd + 时间戳后4位
    const timestamp = Date.now().toString();
    const seq = timestamp.slice(-4);
    dialog.form.entryCode = `SE${dateStr}${seq}`;
};

const openDialog = (row) => {
    resetDialogForm();
    // 加载运送清单列表和订单列表
    loadDeliveryList();
    loadOrderList();
    if (row) {
        dialog.title = '编辑进场';
        Object.assign(dialog.form, row);
    } else {
        // 新增时，如果没有编码则自动生成
        if (!dialog.form.entryCode) {
            generateEntryCode();
        }
    }
    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>

