package com.pcloud.book.book.biz.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import com.pcloud.book.book.biz.BookSwitchBiz;
import com.pcloud.book.book.entity.BookSwitch;
import com.pcloud.book.book.mapper.BookSwitchMapper;
import com.pcloud.book.book.vo.request.BookSwitchParam;
import com.pcloud.common.exceptions.BizException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @描述：
 * @作者：张扬
 * @创建时间：2022/6/17 21:06:02
 * @版本：1.0
 */
@Component
public class BookSwitchBizImpl implements BookSwitchBiz {

    @Resource
    private BookSwitchMapper bookSwitchMapper;

    @Override
    public void saveSwitch(BookSwitchParam param) {
        if (ObjectUtil.isEmpty(param.getBookId()) || ObjectUtil.isAllEmpty(param.getIsBlackBoxEnable(), param.getIsResShareEnable())) {
            throw BizException.PARAM_DELETION;
        }
        bookSwitchMapper.insertSelective(buildBookSwitch(param));
    }

    @Override
    public Map<Long, BookSwitch> mapByBookIds(List<Long> bookIds) {
        if (CollUtil.isEmpty(bookIds)) {
            return MapUtil.empty();
        }
        List<BookSwitch> datas = bookSwitchMapper.listByBookIds(bookIds);
        if (CollUtil.isEmpty(datas)) {
            return MapUtil.empty();
        }
        return datas.stream().collect(Collectors.toMap(BookSwitch::getBookId, Function.identity()));
    }

    @Override
    public void batchSaveSwitch(BookSwitchParam param) {
        List<BookSwitchParam> switchList = param.getSwitchList();
        if (CollUtil.isEmpty(switchList)) {
            throw BizException.PARAM_DELETION;
        }
        List<BookSwitch> bookSwitches = new ArrayList<>();
        for (BookSwitchParam val : switchList) {
            if (val == null || ObjectUtil.hasEmpty(val.getBookId(),val.getIsBlackBoxEnable(), val.getIsResShareEnable())) {
                throw BizException.PARAM_DELETION;
            }
            val.setPartyId(param.getPartyId());
            bookSwitches.add(buildBookSwitch(val));
        }
        bookSwitchMapper.batchInsert(bookSwitches);
    }

    private BookSwitch buildBookSwitch(BookSwitchParam param) {
        BookSwitch bookSwitch = new BookSwitch();
        bookSwitch.setBookId(param.getBookId());
        bookSwitch.setIsBlackBoxEnable(param.getIsBlackBoxEnable());
        bookSwitch.setIsResShareEnable(param.getIsResShareEnable());
        bookSwitch.setCreateUser(param.getPartyId());
        bookSwitch.setUpdateUser(param.getPartyId());
        return bookSwitch;
    }
}
