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

        <common-table
            ref="pageRef"
            :pageConfig="pageConfig"
            :columns="columns"
            :tools="false"
        >
            <template #toolbar>
                <el-radio-group @change="handleStatusChange" v-model="history">
                    <el-radio-button label="库存预警" value="0" />
                    <el-radio-button label="历史库存预警" value="1" />
                </el-radio-group>

                <span class="ml-8"></span>
                <el-button
                    type="success"
                    plain
                    v-permission="'recycle:inventoryAlert:batchAddBooklist'"
                    @click="handleOptBooklist()"
                >
                    加入回收书单
                </el-button>
                <el-button
                    type="warning"
                    plain
                    v-permission="'recycle:inventoryAlert:batchRemoveBlacklist'"
                    @click="handleOptBlacklist('remove')"
                >
                    移除黑名单
                </el-button>
                <el-button
                    type="success"
                    plain
                    v-permission="'recycle:inventoryAlert:batchAddSocial'"
                    @click="handleOptType(1)"
                >
                    加社科库
                </el-button>
                <el-button
                    type="danger"
                    plain
                    v-permission="'recycle:inventoryAlert:batchAddBlacklist'"
                    @click="handleOptBlacklist('add')"
                >
                    加黑名单
                </el-button>

                <el-button
                    type="warning"
                    plain
                    v-permission="'recycle:inventoryAlert:batchPauseRecycle'"
                    @click="handleOptRecycle()"
                >
                    暂停回收
                </el-button>
                <el-button
                    color="#192bbe"
                    plain
                    v-permission="'recycle:inventoryAlert:batchAddTeach'"
                    @click="handleOptType(2)"
                >
                    加教材库
                </el-button>
                <el-button
                    color="#7728f5"
                    plain
                    v-permission="'recycle:inventoryAlert:oneUpdate'"
                    @click="handleOneUpdate()"
                >
                    一键更新
                </el-button>
            </template>

            <template #cover="{ row }">
                <el-image
                    style="width: 90px; height: 120px; border-radius: 4px"
                    fit="cover"
                    :src="row.cover"
                    :preview-src-list="[row.cover]"
                    :initial-index="0"
                    preview-teleported
                />
            </template>
            <template #baseInfo="{ row }">
                <div class="flex justify-start items-center">
                    <div style="flex: 2">
                        <book-stat-info :row="row" @refresh="reload" />
                    </div>
                </div>
            </template>

            <template #action="{ row }">
                <el-button
                    type="danger"
                    link
                    v-permission="'recycle:inventoryAlert:setParams'"
                    @click="handleSetParams(row)"
                    v-if="row.recycleStatus == 1"
                >
                    [设置独立参数]
                </el-button>
                <el-button
                    type="danger"
                    link
                    v-else
                    v-permission="'recycle:inventoryAlert:addDiscount'"
                    @click="handleAddDiscount(row)"
                >
                    [指定折扣加回收书单]
                </el-button>
                <el-button
                    type="warning"
                    link
                    v-permission="'recycle:inventoryAlert:recycleLog'"
                    @click="handleRecycleLog(row)"
                >
                    [回收日志]
                </el-button>
                <el-button
                    type="success"
                    link
                    v-permission="'recycle:inventoryAlert:remind'"
                    @click="handleRemind(row)"
                >
                    [一个月后提醒]
                </el-button>
            </template>
        </common-table>

        <orderRecycleLog ref="recycleLogRef" />
        <setParams ref="setParamsRef" @refresh="reload" />
        <addDiscount ref="addDiscountRef" @refresh="reload" />
        <orderBlacklist ref="blacklistRef" @refresh="reload" />
        <oneUpdate ref="oneUpdateRef" @submit="handleOneUpdateSubmit" />
    </ele-page>
</template>

<script setup>
    import { ref, reactive, getCurrentInstance } from 'vue';
    import CommonTable from '@/components/CommonPage/CommonTable.vue';
    import bookSearch from '@/views/recycle/components/book-search.vue';
    import bookStatInfo from '@/views/recycle/components/book-stat-info.vue';
    import { useDictData } from '@/utils/use-dict-data';
    import orderRecycleLog from '@/views/recycleOrder/detail/order-recycle-log.vue';
    import setParams from '@/views/recycle/components/set-params.vue';
    import addDiscount from '@/views/recycle/components/add-discount.vue';
    import orderBlacklist from '@/views/recycleOrder/detail/order-blacklist.vue';
    import oneUpdate from '@/views/recycle/components/one-update.vue';
    import dayjs from 'dayjs';
    import { ElMessage } from 'element-plus';

    const { proxy } = getCurrentInstance();
    defineOptions({ name: 'InventoryAlert' });

    const history = ref('0');
    function handleStatusChange(value) {
        pageRef.value.reload({ history: value });
    }

    /** 表格列配置 */
    const columns = ref([
        {
            type: 'selection',
            columnKey: 'selection',
            width: 50,
            align: 'center',
            fixed: 'left'
        },
        {
            label: '图片',
            prop: 'cover',
            width: 120,
            slot: 'cover'
        },
        {
            label: '信息',
            prop: 'baseInfo',
            width: 540,
            slot: 'baseInfo'
        },
        { label: '回收折扣', prop: 'recycleDiscount' },
        { label: '预估金额', prop: 'recyclePrice' },
        { label: '最大回收量', prop: 'recycleMax' },
        { label: '剩余回收量', prop: 'restRecycleNum' },
        { label: '预警次数', prop: 'alarmNum' },
        {
            label: '销量',
            prop: 'salesNum',
            formatter: (row) => row.salesNum || 0
        },
        {
            columnKey: 'action',
            label: '操作',
            width: 160,
            slot: 'action',
            fixed: 'right'
        }
    ]);

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

    const pageConfig = reactive({
        pageUrl: '/book/stockAlarm/pagelist',
        fileName: '图书库存预警',
        cacheKey: 'inventoryAlertTable',
        params: {
            alarmType: '2',
            delStatus: '1',
            history: history.value
        }
    });

    //刷新表格
    function reload(where) {
        where && (where.history = history.value);
        pageRef.value?.reload(where);
    }

    //回收日志
    const recycleLogRef = ref(null);
    function handleRecycleLog(row) {
        recycleLogRef.value?.handleOpen(row);
    }
    //设置独立参数
    const setParamsRef = ref(null);
    function handleSetParams(row) {
        setParamsRef.value?.handleOpen(row);
    }
    //指定折扣加回收书单
    const addDiscountRef = ref(null);
    function handleAddDiscount(row) {
        addDiscountRef.value?.handleOpen({ isbnList: [row.isbn] });
    }

    //回收书单操作
    function handleOptBooklist() {
        let selections = pageRef.value?.getSelections();
        if (!selections || selections.length === 0) {
            ElMessage.warning('请选择要操作的图书');
            return;
        }
        const isbnList = selections.map((item) => item.isbn);

        pageRef.value?.operatBatch({
            title: '确认加入回收书单？',
            method: 'post',
            url: '/book/bookRecycleInfo/addIn',
            data: { isbnList },
            success: () => {
                reload();
            }
        });
    }
    //黑名单操作
    const blacklistRef = ref(null);
    function handleOptBlacklist(type) {
        let selections = pageRef.value?.getSelections();
        if (!selections || selections.length === 0) {
            ElMessage.warning('请选择要操作的图书');
            return;
        }
        const isbnList = selections.map((item) => item.isbn);

        if (type == 'remove') {
            // 移除黑名单
            pageRef.value?.operatBatch({
                title: '确认移除黑名单？',
                method: 'post',
                url: '/book/bookRecycleInfo/removeBlackList',
                data: { isbnList },
                success: () => {
                    reload();
                }
            });
        } else {
            // 加入黑名单，打开选择原因弹窗
            blacklistRef.value?.handleOpen(isbnList);
        }
    }
    //回收操作
    function handleOptRecycle() {
        let selections = pageRef.value?.getSelections();
        if (!selections || selections.length === 0) {
            ElMessage.warning('请选择要操作的图书');
            return;
        }
        const isbnList = selections.map((item) => item.isbn);

        pageRef.value?.operatBatch({
            title: '确认暂停回收？',
            method: 'post',
            url: '/book/bookRecycleInfo/stopRecycle',
            data: { isbnList },
            success: () => {
                reload();
            }
        });
    }
    //类型操作
    function handleOptType(type) {
        let selections = pageRef.value?.getSelections();
        if (!selections || selections.length === 0) {
            ElMessage.warning('请选择要操作的图书');
            return;
        }

        const isbnList = selections.map((item) => item.isbn);
        const url =
            type == 1
                ? '/book/bookRecycleInfo/changeBookTag2'
                : '/book/bookRecycleInfo/changeBookTag1';
        const title = type == 1 ? '确认加社科库？' : '确认加教材库？';

        pageRef.value?.operatBatch({
            title,
            method: 'post',
            url,
            data: { isbnList },
            success: () => {
                reload();
            }
        });
    }

    //一个月后提醒
    function handleRemind(row) {
        pageRef.value?.messageBoxConfirm({
            message: '确定一个月后提醒吗？',
            fetch: () =>
                proxy.$http.post('/book/stockAlarm/setAlarmTime', {
                    id: row.id
                })
        });
    }

    //一键更新
    const oneUpdateRef = ref(null);
    function handleOneUpdate() {
        oneUpdateRef.value?.handleOpen();
    }

    //处理一键更新提交
    function handleOneUpdateSubmit(data) {
        data.alarmType = 2;
        proxy.$http.post('/book/stockAlarm/alarmReload', data).then((res) => {
            if (res.data.code == 200) {
                ElMessage.success('操作成功');
            } else {
                ElMessage.error(res.data.msg);
            }
        });
    }
</script>
