<template>
    <ele-page flex-table>
        <page-search @search="reload" />

        <common-table ref="pageRef" :pageConfig="pageConfig" :columns="columns">
            <template #toolbar>
                <div class="flex items-center mb-4">
                    <el-statistic
                        :value="statistics.totalStockNum || 0"
                        title="累计激活码数量"
                        value-style="font-size:30px"
                        class="mr-20"
                    />
                    <el-statistic
                        :value="statistics.totalOutNum || 0"
                        title="已出库数量"
                        value-style="font-size:30px"
                        class="mr-20"
                    />
                    <el-statistic
                        :value="statistics.totalOutPrice || 0"
                        title="已出库金额"
                        :precision="2"
                        value-style="font-size:30px"
                        class="mr-20"
                    />
                    <el-statistic
                        :value="statistics.stockNum || 0"
                        title="待出库数量"
                        value-style="font-size:30px"
                        class="mr-20"
                    />
                </div>
            </template>

            <template #type="{ row }">
                <el-tag :type="row.type == 1 ? 'success' : 'warning'">
                    {{ row.type == 1 ? '入库' : '出库' }}
                </el-tag>
            </template>

            <template #status="{ row }">
                <el-tag
                    :type="
                        row.status == 1
                            ? 'success'
                            : row.status == 2
                              ? 'warning'
                              : 'info'
                    "
                >
                    {{ getStatusText(row.status) }}
                </el-tag>
            </template>

            <template #operatorName="{ row }">
                {{ row.operatorName || '-' }}
            </template>

            <template #action="{ row }">
                <div>
                    <el-button
                        type="primary"
                        v-permission="'code:activation:detail'"
                        link
                        @click="handleViewDetails(row)"
                    >
                        [查看]
                    </el-button>
                    <el-button
                        type="danger"
                        v-permission="'code:activation:invalid'"
                        link
                        @click="handleInvalid(row)"
                        v-if="row.canCancel == 1"
                    >
                        [作废]
                    </el-button>
                </div>
            </template>
        </common-table>

        <!-- 出库详情弹窗 -->
        <out-detail-modal ref="outDetailModalRef" />

        <!-- 入库详情弹窗 -->
        <in-detail-modal ref="inDetailModalRef" />

        <!-- 作废弹窗 -->
        <invalid-modal ref="invalidModalRef" @success="handleInvalidSuccess" />
    </ele-page>
</template>

<script setup>
    import { ref, reactive, onMounted } from 'vue';
    import CommonTable from '@/components/CommonPage/CommonTable.vue';
    import pageSearch from './page-search.vue';
    import OutDetailModal from './components/out-detail-modal.vue';
    import InDetailModal from './components/in-detail-modal.vue';
    import InvalidModal from './components/invalid-modal.vue';
    import request from '@/utils/request';
    import { ElMessage } from 'element-plus';

    defineOptions({ name: 'CodeRecord' });

    // 统计数据的响应式对象
    const statistics = reactive({
        totalStockNum: 0,
        totalOutNum: 0,
        totalOutPrice: 0,
        stockNum: 0
    });

    // 获取统计数据
    async function fetchStatistics(where = {}) {
        request
            .get('/activation/bookActivationInfo/inOutSum', {
                params: {
                    repositoryId: where.repositoryId || undefined,
                    isbn: where.isbn || undefined,
                    bookName: where.bookName || undefined,
                    type: where.type || undefined,
                    remark: where.remark || undefined,
                    startTime: where.startTime || undefined,
                    endTime: where.endTime || undefined
                }
            })
            .then((res) => {
                console.log('获取统计数据:', res);
                if (res.data.code === 200) {
                    Object.assign(statistics, res.data.data || {});
                }
            });
    }

    onMounted(() => {
        fetchStatistics();
    });

    // 获取状态文本
    function getStatusText(status) {
        const statusMap = {
            1: '已完成',
            2: '进行中',
            3: '待处理'
        };
        return statusMap[status] || '未知';
    }

    /** 表格列配置 */
    const columns = ref([
        { label: 'ISBN', prop: 'isbn', align: 'center', width: 150 },
        {
            label: '商品名称',
            prop: 'bookName',
            align: 'left',
            minWidth: 300
        },
        {
            label: '操作类型',
            prop: 'type',
            align: 'center',
            width: 100,
            slot: 'type'
        },
        {
            label: '操作时间',
            prop: 'operatorTime',
            align: 'center',
            width: 180
        },
        { label: '数量', prop: 'num', align: 'center', width: 100 },
        {
            label: '金额',
            prop: 'totalPrice',
            align: 'center',
            width: 120,
            formatter: (row) => (row.totalPrice == null ? '-' : row.totalPrice)
        },
        {
            label: '单价',
            prop: 'price',
            align: 'center',
            width: 100,
            formatter: (row) => (row.price == null ? '-' : row.price)
        },
        {
            label: '操作员',
            prop: 'operatorName',
            align: 'center',
            width: 120,
            slot: 'operatorName'
        },
        {
            label: '仓库',
            prop: 'repositoryName',
            align: 'center',
            minWidth: 140,
            formatter: (row) => row.repositoryName || '-'
        },
        {
            columnKey: 'action',
            label: '操作',
            width: 150,
            align: 'center',
            slot: 'action',
            fixed: 'right'
        }
    ]);

    /** 页面组件实例 */
    const pageRef = ref(null);

    /** 出库详情弹窗引用 */
    const outDetailModalRef = ref(null);

    /** 入库详情弹窗引用 */
    const inDetailModalRef = ref(null);

    /** 作废弹窗引用 */
    const invalidModalRef = ref(null);

    const pageConfig = reactive({
        pageUrl: '/activation/bookActivationInfo/inOutList',
        fileName: '出入库记录',
        cacheKey: 'codeRecord',
        rowKey: 'id'
    });

    //刷新表格
    const whereCache = ref({});
    function reload(where) {
        pageRef.value?.reload(where);
        whereCache.value = where;
        fetchStatistics(whereCache.value);
    }

    // 查看详情
    const handleViewDetails = (row) => {
        if (row && row.id) {
            // 根据 type 类型打开不同的详情弹窗
            // type: 1-入库, 2-出库
            if (row.type == 1) {
                inDetailModalRef.value?.handleOpen(row.id);
            } else if (row.type == 2) {
                outDetailModalRef.value?.handleOpen(row.id);
            } else {
                ElMessage.error('未知的记录类型');
            }
        } else {
            ElMessage.error('缺少记录ID');
        }
    };

    // 作废操作
    const handleInvalid = (row) => {
        if (row && row.id) {
            invalidModalRef.value?.handleOpen(row);
        } else {
            ElMessage.error('缺少记录ID');
        }
    };

    // 作废成功回调
    const handleInvalidSuccess = () => {
        // 刷新表格数据
        reload();
        // 刷新统计数据
        fetchStatistics(whereCache.value);
    };
</script>

<style scoped>
    .book-info {
        text-align: left;
    }

    .book-title {
        font-size: 14px;
        font-weight: bold;
        color: #409eff;
        margin-bottom: 4px;
        cursor: pointer;
    }

    .book-details {
        font-size: 12px;
        color: #666;
    }

    .book-detail-item {
        margin-bottom: 2px;
    }
</style>
