<template>
    <div>
        <base-search :formItemList="formItemList" @search="searchFrom" ref="baseSearchRef"></base-search>

        <!-- 横向滚动操作栏 -->
        <div class="operation-scroll-bar">
            <div class="operation-scroll-container">
                <el-button
                    type="primary"
                    v-hasPermi="['warehousein:add']"
                    @click="showAddDialog"
                    style="margin-left: 10px"
                >
                    新增进仓记录
                </el-button>
            </div>
        </div>

        <div class="main-container">
            <el-table
                :data="rows"
                border
                v-loading="data.dataListLoading"
                element-loading-text="数据加载中..."
                style="width: 100%"
                :show-overflow-tooltip="true"
            >
                <el-table-column label="进仓单号" prop="inNumber" min-width="150" width="180">
                    <template #default="scope">
                        {{ scope.row.inNumber || '--' }}
                    </template>
                </el-table-column>
                <el-table-column label="中转仓" prop="warehouseName" min-width="120" width="150">
                    <template #default="scope">
                        {{ scope.row.warehouseName || '--' }}
                    </template>
                </el-table-column>
                <el-table-column label="运单号" prop="deliveryNumber" min-width="120" width="150">
                    <template #default="scope">
                        {{ scope.row.deliveryNumber || '--' }}
                    </template>
                </el-table-column>
                <el-table-column label="车牌号" prop="licensePlate" min-width="100" width="120">
                    <template #default="scope">
                        {{ scope.row.licensePlate || '--' }}
                    </template>
                </el-table-column>
                <el-table-column label="司机姓名" prop="driverName" min-width="100" width="120">
                    <template #default="scope">
                        {{ scope.row.driverName || '--' }}
                    </template>
                </el-table-column>
                <el-table-column label="司机手机号" prop="driverMobile" min-width="120" width="150">
                    <template #default="scope">
                        {{ scope.row.driverMobile || '--' }}
                    </template>
                </el-table-column>
                <el-table-column label="来源地" prop="sourceLocation" min-width="150" width="200">
                    <template #default="scope">
                        {{ scope.row.sourceLocation || '--' }}
                    </template>
                </el-table-column>
                <el-table-column label="牛只数量(头)" prop="cattleCount" min-width="100" width="120">
                    <template #default="scope">
                        {{ scope.row.cattleCount || '--' }}
                    </template>
                </el-table-column>
                <el-table-column label="重量(公斤)" prop="weight" min-width="100" width="120">
                    <template #default="scope">
                        {{ scope.row.weight || '--' }}
                    </template>
                </el-table-column>
                <el-table-column label="进仓时间" prop="inTime" min-width="160" width="180">
                    <template #default="scope">
                        {{ scope.row.inTime || '--' }}
                    </template>
                </el-table-column>
                <el-table-column label="状态" prop="status" min-width="80" width="100">
                    <template #default="scope">
                        <el-tag :type="getStatusType(scope.row.status)">
                            {{ scope.row.statusDesc || '--' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="创建时间" prop="createTime" min-width="160" width="180">
                    <template #default="scope">
                        {{ scope.row.createTime || '--' }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" min-width="200" width="250" fixed="right">
                    <template #default="scope">
                        <el-button link type="primary" v-hasPermi="['warehousein:edit']" @click="showEditDialog(scope.row)">
                            编辑
                        </el-button>
                        <el-button link type="primary" v-hasPermi="['warehousein:query']" @click="showDetailDialog(scope.row)">
                            详情
                        </el-button>
                        <el-button link type="danger" v-hasPermi="['warehousein:delete']" @click="del(scope.row.id)">
                            删除
                        </el-button>
                    </template>
                </el-table-column>
                <template #empty>
                    <div class="dataListOnEmpty">暂无数据</div>
                </template>
            </el-table>
            <Pagination
                v-if="data.total > 0"
                v-model:limit="form.pageSize"
                v-model:page="form.pageNum"
                :total="data.total"
                @pagination="handlePagination"
            />
        </div>

        <!-- 新增/编辑对话框 -->
        <warehouseInDialog ref="dialogRef" @success="getDataList" />
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import baseSearch from '@/components/common/searchCustom/index.vue';
import Pagination from '@/components/Pagination/index.vue';
import warehouseInDialog from './warehouseInDialog.vue';
import { warehouseInList, warehouseInDel } from '@/api/warehouseIn.js';

const baseSearchRef = ref();
const dialogRef = ref();
const data = reactive({
    total: 0,
    dataListLoading: false,
});
const rows = ref([]);
const form = reactive({
    pageNum: 1,
    pageSize: 10,
});

const formItemList = reactive([
    {
        label: '进仓单号',
        prop: 'inNumber',
        type: 'input',
        placeholder: '请输入进仓单号',
        span: 7,
        labelWidth: 100,
    },
    {
        label: '中转仓',
        prop: 'warehouseId',
        type: 'select',
        selectOptions: [],
        span: 7,
        labelWidth: 80,
    },
    {
        label: '状态',
        prop: 'status',
        type: 'select',
        selectOptions: [
            { value: 1, text: '待进仓' },
            { value: 2, text: '已进仓' },
            { value: 3, text: '已出仓' },
        ],
        span: 7,
        labelWidth: 80,
    },
    {
        label: '进仓时间',
        prop: 'inTime',
        type: 'daterange',
        startPlaceholder: '开始时间',
        endPlaceholder: '结束时间',
        span: 7,
        labelWidth: 100,
    },
]);

const searchFrom = () => {
    form.pageNum = 1;
    getDataList();
};

const handlePagination = (paginationData) => {
    if (paginationData) {
        form.pageNum = paginationData.page || form.pageNum;
        form.pageSize = paginationData.limit || form.pageSize;
    }
    getDataList();
};

const getDataList = () => {
    data.dataListLoading = true;
    const searchParams = baseSearchRef.value.penetrateParams();

    const params = {
        ...form,
        ...searchParams,
    };

    // 处理日期范围参数
    if (searchParams.inTime && Array.isArray(searchParams.inTime) && searchParams.inTime.length === 2) {
        params.startTime = searchParams.inTime[0];
        params.endTime = searchParams.inTime[1];
        delete params.inTime;
    }

    warehouseInList(params)
        .then((res) => {
            let responseData = res.data || res;

            if (responseData && typeof responseData === 'object' && 'total' in responseData && 'rows' in responseData) {
                rows.value = responseData.rows || [];
                data.total = responseData.total || 0;
            } else if (responseData && responseData.data) {
                rows.value = responseData.data.rows || [];
                data.total = responseData.data.total || 0;
            } else {
                rows.value = [];
                data.total = 0;
            }
        })
        .catch((error) => {
            console.error('查询失败:', error);
            ElMessage.error('查询失败：' + (error.message || '未知错误'));
            rows.value = [];
            data.total = 0;
        })
        .finally(() => {
            data.dataListLoading = false;
        });
};

const showAddDialog = () => {
    if (dialogRef.value) {
        dialogRef.value.onShowDialog(null);
    }
};

const showEditDialog = (row) => {
    if (dialogRef.value) {
        dialogRef.value.onShowDialog(row);
    }
};

const showDetailDialog = (row) => {
    if (dialogRef.value) {
        dialogRef.value.onShowDialog(row, true);
    }
};

const del = (id) => {
    ElMessageBox.confirm('确定要删除这条进仓记录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(() => {
            warehouseInDel(id)
                .then((res) => {
                    if (res.code === 200) {
                        ElMessage.success('删除成功');
                        getDataList();
                    } else {
                        ElMessage.error(res.msg || '删除失败');
                    }
                })
                .catch((error) => {
                    console.error('删除失败:', error);
                    ElMessage.error('删除失败：' + (error.message || '未知错误'));
                });
        })
        .catch(() => {
            // 用户取消删除
        });
};

const getStatusType = (status) => {
    const typeMap = {
        1: 'info',      // 待进仓 - 灰色
        2: 'success',   // 已进仓 - 绿色
        3: 'warning',  // 已出仓 - 橙色
    };
    return typeMap[status] || 'info';
};

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

<style scoped lang="scss">
.operation-scroll-bar {
    background: #fff;
    margin-bottom: 10px;
    padding: 10px;
    border-radius: 2px;
}

.operation-scroll-container {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
}

.main-container {
    background: #fff;
    padding: 16px;
    border-radius: 2px;
}

.dataListOnEmpty {
    text-align: center;
    padding: 20px;
    color: #999;
}
</style>

