import { ElMessage } from 'element-plus';
import { ref } from 'vue';

/**
 * 图书操作相关的混入方法
 * @param {Object} pageRef - 页面表格组件实例
 * @returns {Object} - 包含各种图书操作方法的对象
 */
export function useBookOperation(pageRef) {
    // 弹窗组件引用
    const blacklistRef = ref(null);
    const discountRef = ref(null);
    const paramsRef = ref(null);

    /**
     * 回收书单操作（添加/移除）
     * @param {String} type - 操作类型：'add'添加，'remove'移除
     * @param {Object} row - 单行数据，不传则为批量操作
     */
    function handleOptBooklist(type, row) {
        let selections = row ? [row] : pageRef.value?.getSelections();
        if (!selections || selections.length === 0) {
            ElMessage.warning('请选择要操作的图书');
            return;
        }
        const isbnList = selections.map((item) => item.isbn);

        const url =
            type === 'remove'
                ? '/book/bookRecycleInfo/removeOut'
                : '/book/bookRecycleInfo/addIn';

        const title =
            type === 'remove' ? '确认移除回收书单？' : '确认加入回收书单？';

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

    /**
     * 黑名单操作（添加/移除）
     * @param {String} type - 操作类型：'add'添加，'remove'移除
     * @param {Object} row - 单行数据，不传则为批量操作
     */
    function handleOptBlacklist(type, row) {
        let selections = row ? [row] : 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 },
                row,
                success: () => {
                    if (typeof pageRef.value?.reload === 'function') {
                        pageRef.value.reload();
                    }
                }
            });
        } else {
            // 加入黑名单，打开选择原因弹窗
            blacklistRef.value?.handleOpen(isbnList);
        }
    }

    /**
     * 回收操作（开启/暂停）
     * @param {Object} row - 单行数据，不传则为批量操作
     */
    function handleOptRecycle(type, row) {
        let selections = row ? [row] : pageRef.value?.getSelections();
        if (!selections || selections.length === 0) {
            ElMessage.warning('请选择要操作的图书');
            return;
        }

        const isbnList = selections.map((item) => item.isbn);

        const url =
            type === 'pause'
                ? '/book/bookRecycleInfo/stopRecycle'
                : '/book/bookRecycleInfo/openRecycle';

        const title = type === 'pause' ? '确认暂停回收？' : '确认开启回收？';

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

    /**
     * 类型操作（社科库/教材库）
     * @param {Number} type - 类型：1社科库，2教材库
     */
    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: () => {
                if (typeof pageRef.value?.reload === 'function') {
                    pageRef.value.reload();
                }
            }
        });
    }

    /**
     * 指定折扣加入回收书单
     */
    function handleAddDiscount() {
        let selections = pageRef.value?.getSelections();
        if (!selections || selections.length === 0) {
            ElMessage.warning('请选择要操作的图书');
            return;
        }

        const isbnList = selections.map((item) => item.isbn);
        discountRef.value?.handleOpen({ isbnList });
    }

    /**
     * 设置独立参数
     * @param {Object} row - 图书数据
     */
    function handleSetParams(row) {
        paramsRef.value?.handleOpen(row);
    }

    /**
     * 修改回收折扣
     * @param {Object} row - 图书数据
     */
    const modifyDiscountRef = ref(null);
    function handleModifyDiscount(row) {
        modifyDiscountRef.value?.handleOpen(row);
    }

    /**
     * 查看当当、淘宝、豆瓣链接
     * @param {Object} row - 图书数据
     * @param {String} type - 链接类型：'dd'当当，'tb'淘宝，'db'豆瓣，'kw'孔网
     */
    const handleViewUrl = (row, type) => {
        let url = '';
        if (type == 'dd') {
            url = `https://search.dangdang.com/?key=${row.isbn}&act=input`;
        } else if (type == 'tb') {
            url = `https://s.taobao.com/search?page=1&q=${row.isbn}&sort=sale-desc&tab=all`;
        } else if (type == 'db') {
            url = `https://search.douban.com/book/subject_search?search_text=${row.isbn}`;
        } else if (type == 'kw') {
            url = `https://search.kongfz.com/product_result/?key=${row.isbn}&status=0&_stpmt=eyJzZWFyY2hfdHlwZSI6ImFjdGl2ZSJ9`;
        }
        window.open(url, '_blank');
    };

    return {
        blacklistRef,
        discountRef,
        paramsRef,
        handleOptBooklist,
        handleOptBlacklist,
        handleOptRecycle,
        handleOptType,
        handleAddDiscount,
        handleSetParams,
        modifyDiscountRef,
        handleModifyDiscount,
        handleViewUrl
    };
}
