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

        <common-table ref="pageRef" :pageConfig="pageConfig" :columns="columns" :tools="false">
            <template #toolbar>
                <el-radio-group @change="handleStatusChange" v-model="searchType">
                    <el-radio-button label="全部" value="0" />
                    <el-radio-button label="已加入回收书单（正在回收）" value="1" />
                    <el-radio-button label="已加入回收书单（暂停回收）" value="2" />
                </el-radio-group>

                <span class="ml-8"></span>
                <el-button type="danger" plain v-permission="'recycle:specifiedBooks:batchAddBlacklist'"
                    @click="handleOptBlacklist()">
                    加黑名单
                </el-button>
                <el-button type="warning" plain v-permission="'recycle:specifiedBooks:batchPauseRecycle'"
                    @click="handleOptRecycle(null, 2)">
                    暂停回收
                </el-button>
                <el-button type="warning" plain v-permission="'recycle:specifiedBooks:batchStartRecycle'"
                    @click="handleOptRecycle(null, 1)">
                    开启回收
                </el-button>
                <el-button type="success" plain v-permission="'recycle:specifiedBooks:batchAddSocial'"
                    @click="handleOptType(1)">
                    加社科库
                </el-button>
                <el-button type="primary" plain v-permission="'recycle:specifiedBooks:batchAddTeach'"
                    @click="handleOptType(2)">
                    加教材库
                </el-button>
            </template>

            <template #cover="{ row }">
                <el-image style="width: 90px; height: 120px; border-radius: 4px" fit="cover" :src="row.cover" />
            </template>
            <template #baseInfo="{ row }">
                <book-info :row="row" @edit="handleUpdateBook" :showFormat="false"></book-info>
            </template>
            <template #stock="{ row }">
                <book-stock :row="row"></book-stock>
            </template>
            <template #view="{ row }">
                <div class="flex justify-start items-center flex-wrap book-btns">
                    <el-button color="#951d1d" @click="handleViewUrl(row, 'kw')" v-permission="'recycle:specifiedBooks:viewUrl'">
                        查看孔网
                    </el-button>
                    <el-button color="#e99d42" @click="handleRecycleLog(row)" v-permission="'recycle:specifiedBooks:viewRecycleLog'">
                        回收日志
                    </el-button>
                    <el-button color="#f27606" @click="handleViewUrl(row, 'tb')" v-permission="'recycle:specifiedBooks:viewUrl'">
                        查看淘宝
                    </el-button>
                    <el-button color="#0f7dc7" @click="handleSalesLog(row)" v-permission="'recycle:specifiedBooks:viewSalesLog'">
                        售价日志
                    </el-button>
                    <el-button color="#399420" @click="handleViewUrl(row, 'db')" v-permission="'recycle:specifiedBooks:viewUrl'">
                        查看豆瓣
                    </el-button>
                    <el-button color="#a4adb3" @click="handleViewUrl(row, 'dd')" v-permission="'recycle:specifiedBooks:viewUrl'">
                        查看当当
                    </el-button>
                </div>
            </template>

            <template #action="{ row }">
                <div class="flex justify-start items-center flex-wrap  book-btns">
                    <el-button color="#7728f5" v-permission="'recycle:specifiedBooks:updateDiscount'"
                        @click="handleModifyDiscount(row)">
                        修改回收折扣
                    </el-button>
                    <el-button color="#333333" v-permission="'recycle:specifiedBooks:addBlacklist'"
                        @click="handleOptBlacklist(row)">
                        加入黑名单
                    </el-button>
                    <el-button color="#3ab54a" v-permission="'recycle:specifiedBooks:updateMaxRecycle'"
                        @click="handleModifyMaxRecycle(row)">
                        修改最大回收量
                    </el-button>
                    <el-button color="#bd3124" v-permission="'recycle:specifiedBooks:pauseRecycle'"
                        @click="handleOptRecycle(row, 2)" v-if="row.recycleStatus == 1">
                        暂停回收
                    </el-button>
                    <el-button color="#bd3124" v-permission="'recycle:specifiedBooks:startRecycle'"
                        @click="handleOptRecycle(row, 1)" v-else>
                        开启回收
                    </el-button>
                    <el-button color="#e99d42" v-permission="'recycle:specifiedBooks:updateOrderRecycle'"
                        @click="handleModifyOrderRecycle(row)">
                        修改订单回收量
                    </el-button>
                    <el-button color="#4095e5" v-permission="'recycle:specifiedBooks:removeBooklist'"
                        @click="handleOptBooklist(row)">
                        移除回收书单
                    </el-button>
                </div>
            </template>
        </common-table>

        <books-edit ref="editRef"></books-edit>
        <set-params ref="paramsRef" @refresh="reload"></set-params>
        <add-discount ref="discountRef" @refresh="reload"></add-discount>
        <orderRecycleLog ref="recycleLogRef" />
        <orderSalesLog ref="salesLogRef" />
        <modifyOrderRecycle ref="orderRecycleRef" @refresh="reload" />
        <modifyMaxRecycle ref="maxRecycleRef" @refresh="reload" />
        <modifyDiscount ref="modifyDiscountRef" @refresh="reload" />
        <orderBlacklist ref="blacklistRef" @refresh="reload" />
    </ele-page>
</template>

<script setup>
import { ref, reactive } from 'vue';
import CommonTable from '@/components/CommonPage/CommonTable.vue';
import booksEdit from '@/views/data/books/components/books-edit.vue';
import bookSearch from '@/views/recycle/components/book-search.vue';
import bookInfo from '@/views/recycle/components/book-info.vue';
import bookOtherInfo from '@/views/recycle/components/book-other-info.vue';
import bookStock from '@/views/recycle/components/book-stock.vue';
import setParams from '@/views/recycle/components/set-params.vue';
import addDiscount from '@/views/recycle/components/add-discount.vue';
import orderRecycleLog from '@/views/recycleOrder/detail/order-recycle-log.vue';
import orderSalesLog from '@/views/recycleOrder/detail/order-sales-log.vue';
import modifyOrderRecycle from '@/views/recycle/components/modify-order-recycle.vue';
import modifyMaxRecycle from '@/views/recycle/components/modify-max-recycle.vue';
import modifyDiscount from '@/views/recycle/components/modify-discount.vue';
import orderBlacklist from '@/views/recycleOrder/detail/order-blacklist.vue';

defineOptions({ name: 'specifiedBookslist' });

const searchType = ref('0');
const blacklistRef = ref(null);
function handleStatusChange(value) {
    searchType.value = value;
    pageConfig.params.searchType = value;
    pageRef.value.reload();
}

/** 表格列配置 */
const columns = ref([
    {
        type: 'selection',
        columnKey: 'selection',
        width: 50,
        align: 'center',
        fixed: 'left'
    },
    {
        label: '图片',
        prop: 'cover',
        width: 120,
        slot: 'cover'
    },
    {
        label: '信息',
        prop: 'baseInfo',
        width: 500,
        slot: 'baseInfo'
    },
    {
        label: '回收价格',
        prop: 'recyclePrice',
        sortable: true,
        columnKey: 'recyclePrice',
        minWidth: 100
    },
    {
        label: '最大回收量',
        minWidth: 120,
        prop: 'recycleMax',
        sortable: true,
        columnKey: 'recycleMax'
    },
    {
        label: '当前剩余回收量',
        minWidth: 140,
        prop: 'restRecycleNum',
        sortable: true,
        columnKey: 'restRecycleNum'
    },
    {
        label: '销量',
        prop: 'salesNum',
        sortable: true,
        columnKey: 'salesNum'
    },
    {
        label: '查看',
        prop: 'view',
        slot: 'view',
        width: 234,
        fixed: 'right'
    },
    {
        columnKey: 'action',
        label: '操作',
        width: 234,
        slot: 'action',
        fixed: 'right'
    }
]);

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

const pageConfig = reactive({
    pageUrl: '/book/bookRecycleInfo/designate/pageList',
    fileName: '指定图书管理',
    cacheKey: 'specifiedBookslistTable',
    rowKey: 'isbn',
    params: {
        searchType: '0'
    }
});

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

//编辑
const editRef = ref(null);
function handleUpdateBook(row) {
    let params = {
        id: row.bookId
    };
    editRef.value?.handleOpen(params);
}

//设置参数
const paramsRef = ref(null);
function handleSetParams(row) {
    paramsRef.value?.handleOpen(row);
}

//黑名单操作
function handleOptBlacklist(row) {
    let selections = row ? [row] : pageRef.value?.getSelections();
    if (!selections || selections.length === 0) {
        ElMessage.warning('请选择要操作的图书');
        return;
    }

    const isbnList = selections.map((item) => item.isbn);
    // 加入黑名单，打开选择原因弹窗
    blacklistRef.value?.handleOpen(isbnList);
}

//回收操作
function handleOptRecycle(row, status) {
    let selections = row ? [row] : pageRef.value?.getSelections();
    if (!selections || selections.length === 0) {
        ElMessage.warning('请选择要操作的图书');
        return;
    }

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

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

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

    pageRef.value?.operatBatch({
        title,
        method: 'post',
        url,
        data: { isbnList },
        row,
        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();
        }
    });
}

//指定折扣
const discountRef = ref(null);
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 });
}

//查看当当、淘宝、豆瓣链接
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');
};

//查看回收日志
const recycleLogRef = ref();
const handleRecycleLog = (row) => {
    recycleLogRef.value?.handleOpen(row);
};

//移除回收书单操作
function handleOptBooklist(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 = '/book/bookRecycleInfo/removeOut';
    const title = '确认移除回收书单？';

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

//查看售价日志
const salesLogRef = ref();
const handleSalesLog = (row) => {
    salesLogRef.value?.handleOpen(row);
};

//修改订单回收量
const orderRecycleRef = ref();
const handleModifyOrderRecycle = (row) => {
    orderRecycleRef.value?.handleOpen(row);
};

//修改最大回收量
const maxRecycleRef = ref();
const handleModifyMaxRecycle = (row) => {
    maxRecycleRef.value?.handleOpen(row);
};

//修改回收折扣
const modifyDiscountRef = ref();
const handleModifyDiscount = (row) => {
    modifyDiscountRef.value?.handleOpen(row);
};
</script>
<style lang="scss" scoped>
.book-btns {
    gap: 6px;
    .el-button {
        min-width: 100px;
        font-size: 12px;
        color: #ffffff;
        padding: 4px 6px;
        margin-right: 0;
    }
}
</style>