<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="recordCode" min-width="140" />
                <el-table-column label="进场编码" prop="entryCode" min-width="140" />
                <el-table-column label="屠宰场" prop="slaughterHouseName" min-width="140">
                    <template #default="scope">
                        {{ scope.row.slaughterHouseName || '-' }}
                    </template>
                </el-table-column>
                <el-table-column label="屠宰头数" prop="slaughterCount" width="120" />
                <el-table-column label="出肉率(%)" prop="yieldRate" width="120">
                    <template #default="scope">
                        <span v-if="scope.row.yieldRate !== null && scope.row.yieldRate !== undefined">
                            {{ scope.row.yieldRate }}%
                        </span>
                        <span v-else>-</span>
                    </template>
                </el-table-column>
                <el-table-column label="进场剩余头数" prop="remainingCapacity" width="140">
                    <template #default="scope">
                        {{ scope.row.remainingCapacity ?? '-' }}
                    </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="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="120px">
                <el-form-item label="屠宰记录编码" prop="recordCode">
                    <el-input
                        v-model="dialog.form.recordCode"
                        placeholder="请输入屠宰记录编码或点击自动生成"
                        style="width: calc(100% - 100px); margin-right: 10px;"
                    />
                    <el-button type="primary" @click="generateRecordCode">自动生成</el-button>
                </el-form-item>
                <el-form-item label="进场记录" prop="entryId">
                    <el-select
                        v-model="dialog.form.entryId"
                        placeholder="请选择进场记录"
                        filterable
                        style="width: 100%"
                        @change="handleEntryChange"
                    >
                        <el-option
                            v-for="item in entryOptions"
                            :key="item.id"
                            :label="`${item.entryCode || '--'}（剩余${item.remainingCapacity ?? '--'}头）`"
                            :value="item.id"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="屠宰头数" prop="slaughterCount">
                    <el-input-number
                        v-model="dialog.form.slaughterCount"
                        :min="1"
                        :max="999999"
                        placeholder="请输入屠宰头数"
                        style="width: 100%"
                    />
                </el-form-item>
                <el-form-item label="出肉率(%)" prop="yieldRate">
                    <el-input-number
                        v-model="dialog.form.yieldRate"
                        :min="0"
                        :max="100"
                        :step="0.1"
                        placeholder="请输入出肉率(0-100)"
                        style="width: 100%"
                    />
                </el-form-item>
                <el-form-item>
                    <el-alert
                        type="info"
                        :closable="false"
                        show-icon
                        title="选中的进场记录"
                        description="进场编码：{{ dialog.state.entryCode || '--' }}，当前剩余头数：{{ dialog.state.remaining ?? '--' }}"
                    />
                </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 {
    slaughterRecordList,
    slaughterRecordAdd,
    slaughterRecordEdit,
    slaughterRecordDel,
    slaughterRecordDetail,
    slaughterEntryList,
    slaughterHouseList,
} from '@/api/slaughter.js';

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

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

const formItemList = reactive([
    {
        label: '屠宰场',
        param: 'slaughterHouseId',
        type: 'select',
        selectOptions: [],
        placeholder: '请选择屠宰场',
        span: 8,
        labelWidth: 100,
        labelKey: 'label',
        valueKey: 'value',
    },
    {
        label: '屠宰记录编码',
        param: 'recordCode',
        type: 'input',
        placeholder: '请输入屠宰记录编码',
        span: 8,
        labelWidth: 120,
    },
    {
        label: '进场编码',
        param: 'entryCode',
        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,
        recordCode: '',
        entryId: null,
        slaughterCount: 1,
        yieldRate: null,
    },
    state: {
        remaining: null,
        entryCode: '',
    },
    rules: {
        entryId: [{ required: true, message: '请选择进场记录', trigger: 'change' }],
        slaughterCount: [{ required: true, message: '请输入屠宰头数', trigger: 'blur' }],
    },
});

const resetDialogForm = () => {
    dialog.form = {
        id: null,
        recordCode: '',
        entryId: null,
        slaughterCount: 1,
        yieldRate: null,
    };
    dialog.state = {
        remaining: null,
        entryCode: '',
    };
    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;
        })
        .catch((err) => console.error(err));
};

const loadEntryOptions = () => {
    slaughterEntryList({ 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 || [];
            entryOptions.value = list;
            Object.keys(entryMap).forEach((key) => delete entryMap[key]);
            list.forEach((item) => {
                entryMap[item.id] = {
                    entryCode: item.entryCode,
                    remainingCapacity: item.remainingCapacity,
                };
            });
        })
        .catch((err) => console.error(err));
};

const getList = () => {
    data.loading = true;
    const params = { ...form, ...baseSearchRef.value.penetrateParams() };
    slaughterRecordList(params)
        .then((res) => {
            let responseData = res.data;
            if (responseData && responseData.data && typeof responseData.data === 'object') {
                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 generateRecordCode = () => {
    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}`;
    const seq = Date.now().toString().slice(-3);
    dialog.form.recordCode = `SL${dateStr}${seq}`;
};

const handleEntryChange = (entryId) => {
    if (!entryId) {
        dialog.state.remaining = null;
        dialog.state.entryCode = '';
        return;
    }
    const info = entryMap[entryId];
    dialog.state.remaining = info?.remainingCapacity ?? null;
    dialog.state.entryCode = info?.entryCode || '';
};

const openDialog = (row) => {
    resetDialogForm();
    loadEntryOptions();
    if (row) {
        dialog.title = '编辑屠宰记录';
        // 重新获取详情，保证剩余头数为最新
        slaughterRecordDetail(row.id)
            .then((res) => {
                const responseData = res.data?.data || res.data || {};
                Object.assign(dialog.form, responseData);
                dialog.state.entryCode = responseData.entryCode;
                // 可用剩余 = 后端剩余 + 当前记录屠宰头数
                const remaining = (responseData.remainingCapacity ?? 0) + (responseData.slaughterCount ?? 0);
                dialog.state.remaining = remaining;
            })
            .catch((err) => console.error(err));
    } else {
        if (!dialog.form.recordCode) {
            generateRecordCode();
        }
    }
    dialog.visible = true;
};

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

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

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

<style scoped>
.action-bar {
    margin-bottom: 16px;
}
</style>

