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

import cn.hutool.core.collection.CollUtil;
import com.pcloud.book.base.enums.BookStatusEnum;
import com.pcloud.book.base.exception.BookBizException;
import com.pcloud.book.book.biz.BookBiz;
import com.pcloud.book.book.dto.BookInfoAndAuthStatusDTO;
import com.pcloud.book.consumer.app.AppConsr;
import com.pcloud.book.consumer.channel.QrcodeSceneConsr;
import com.pcloud.book.consumer.resource.ProductConsr;
import com.pcloud.book.copyright.biz.BookAuthServeBiz;
import com.pcloud.book.copyright.dao.BookAuthServeDao;
import com.pcloud.book.copyright.dto.ServeDTO;
import com.pcloud.book.copyright.entity.BookAuthServe;
import com.pcloud.book.copyright.vo.ServeVO;
import com.pcloud.channelcenter.qrcode.dto.QrcodeSceneDto;
import com.pcloud.common.core.aspect.ParamLog;
import com.pcloud.common.utils.ListUtils;

import com.pcloud.message.common.enums.YesNoEnums;
import com.pcloud.resourcecenter.product.dto.ProductDto;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

/**
 * @author lily
 * @date 2018/12/3 12:02
 */
@Component("bookAuthServeBiz")
public class BookAuthServeBizImpl implements BookAuthServeBiz {
    @Autowired
    private BookAuthServeDao bookAuthServeDao;
    @Autowired
    private QrcodeSceneConsr qrcodeSceneConsr;
    @Autowired
    private BookBiz bookBiz;
    @Autowired
    private AppConsr appConsr;
    @Autowired
    private ProductConsr productConsr;

    @Override
    @ParamLog("设置图书授权服务")
    public void setBookAuthServes(List<ServeVO> serves, Long bookId, Long channelId, Long adviserId) {
          if(bookId == null || channelId == null || adviserId == null) {
            throw new BookBizException(BookBizException.ERROR, "图书不存在");
          }
          deleteServesByBook(bookId, channelId, adviserId);
          if(!ListUtils.isEmpty(serves)){
              List<BookAuthServe> bookAuthServes = changeToBookAuthServe(serves, bookId, channelId, adviserId);
              bookAuthServeDao.insert(bookAuthServes);
          }
    }

    /**
     * 是否设置应用授权  return   key : typeCode_serveId
     */
    @Override
    @ParamLog("是否设置应用授权")
    public Map<String, Boolean> isSetServeAuth(Long bookId, Long channelId, Long adviserId, List<Long> serveIds) {
        if (bookId == null || channelId == null || adviserId == null || ListUtils.isEmpty(serveIds)) {
            return null;
        }
        List<ServeDTO> serveDTOS = bookAuthServeDao.isSetServeAuth(bookId, channelId, adviserId, serveIds);
        if (ListUtils.isEmpty(serveDTOS)) {
            return null;
        }
        Map<String, Boolean> isSetServesMap = new HashMap<>();
        for (ServeDTO serveDTO : serveDTOS) {
            isSetServesMap.put(serveDTO.getServeType() + serveDTO.getServeId(), true);
        }
        return isSetServesMap;
    }

    @Override
    @ParamLog("服务是否开启版权保护，以及授权后仍付费")
    public Map<String, Boolean> isSetServeAuthPay(Long bookId, Long channelId, Long adviserId, List<Long> serveIds) {
        if (bookId == null || channelId == null || adviserId == null || ListUtils.isEmpty(serveIds)) {
            return null;
        }
        List<ServeDTO> serveDTOS = bookAuthServeDao.isSetServeAuth(bookId, channelId, adviserId, serveIds);
        if (ListUtils.isEmpty(serveDTOS)) {
            return null;
        }
        Map<String, Boolean> isSetServesMap = new HashMap<>();
        List<Long> productIds = CollUtil.toList();
        for (ServeDTO serveDTO : serveDTOS) {
            if(serveDTO.getServeType().equalsIgnoreCase("product")){
                productIds.add(serveDTO.getServeId());
            }
        }
        // TAPD:1005196 目前只支持视频、题库等作品
        List<String> openAuthPayProductTypeCodeList = CollUtil.toList("VIDEO", "PRETEST");
        Map<String, String> productMap = productConsr.getProTypeCodeByIds(productIds);
        if(CollUtil.isNotEmpty(productMap)){
            for (Entry<String, String> entry : productMap.entrySet()) {
                if(openAuthPayProductTypeCodeList.contains(entry.getValue())){
                    isSetServesMap.put("PRODUCT" + entry.getKey(), true);
                }
            }
        }
        return isSetServesMap;
    }

    @Override
    public List<ServeVO> listServesByBook(Long bookId, Long channelId, Long adviserId) {
        return bookAuthServeDao.listServesByBook(bookId, channelId, adviserId);
    }

    @Override
    public Boolean checkIsNeedAuth(Long bookId, Long channelId, Long adviserId, Long serveId, String serveType) {
        return bookAuthServeDao.checkIsNeedAuth(bookId, channelId, adviserId, serveId, serveType);
    }

    @Override
    public Map<String, Boolean> listIsOpen4ServeIdsAndQrcode(Long sceneId, List<Long> serveIds) {
        //获取二维码基本信息
        QrcodeSceneDto qrcodeSceneDTO = qrcodeSceneConsr.getById(sceneId);
        if (qrcodeSceneDTO == null || qrcodeSceneDTO.getAdviserBookId() == null) return null;
        //获取图书是否开启授权
        Long bookId = qrcodeSceneDTO.getAdviserBookId();
        Long channelId = qrcodeSceneDTO.getChannelPartyId();
        Long adviserId = qrcodeSceneDTO.getCreatedByUserLogin();
        BookInfoAndAuthStatusDTO baseAndAuthStatus = bookBiz.getBaseAndAuthStatus(bookId, channelId, adviserId);
        if (baseAndAuthStatus != null && BookStatusEnum.PROTECT.value.equals(baseAndAuthStatus.getBookStatus()) && BookStatusEnum.BookDeleteStatus.NOT_DELETE.value.equals(baseAndAuthStatus.getIsDelete())) {
            Map<String, Boolean> setServeAuth = isSetServeAuth(bookId, channelId, adviserId, serveIds);
            return setServeAuth;
        }
        return null;
    }

    @Override
    @ParamLog("listIsOpen4ServeIdsAndBookId")
    public Map<String, Boolean> listIsOpen4ServeIdsAndBookId(Long bookId, Long adviserId, Long channelId, List<Long> serveIds) {
        BookInfoAndAuthStatusDTO baseAndAuthStatus = bookBiz.getBaseAndAuthStatus(bookId, channelId, adviserId);
        final boolean boo = baseAndAuthStatus != null && BookStatusEnum.PROTECT.value.equals(baseAndAuthStatus.getBookStatus())
                && BookStatusEnum.BookDeleteStatus.NOT_DELETE.value.equals(baseAndAuthStatus.getIsDelete());
        if (boo) {
            return isSetServeAuth(bookId, channelId, adviserId, serveIds);
        }
        return null;
    }


    private List<BookAuthServe> changeToBookAuthServe(List<ServeVO> serves, Long bookId, Long channelId, Long adviserId) {
        List<BookAuthServe> bookAuthServes = new ArrayList<>();
        for (ServeVO serveVO : serves){
            BookAuthServe bookAuthServe = new BookAuthServe();
            bookAuthServe.setBookId(bookId);
            bookAuthServe.setChannelId(channelId);
            bookAuthServe.setAdviserId(adviserId);
            BeanUtils.copyProperties(serveVO, bookAuthServe);
            bookAuthServes.add(bookAuthServe);
        }
        return bookAuthServes;
    }

    @ParamLog("删除图书授权服务")
    private void deleteServesByBook(Long bookId, Long channelId, Long adviserId){
        if (bookId == null || channelId == null || adviserId == null) {
            throw new BookBizException(BookBizException.ERROR, "图书不存在");
        }
        List<Long> ids = bookAuthServeDao.selectNeedDelete(bookId, channelId, adviserId);
        if(ListUtils.isEmpty(ids)) return;
        bookAuthServeDao.deleteServes(ids);
    }

    @Override
    public Map<String, Boolean> listIsOpen4AuthorizedPay(Long bookId, Long adviserId, Long channelId, List<Long> serveIds) {
        BookInfoAndAuthStatusDTO baseAndAuthStatus = bookBiz.getBaseAndAuthStatus(bookId, channelId, adviserId);
        final boolean boo = baseAndAuthStatus != null && BookStatusEnum.PROTECT.value.equals(baseAndAuthStatus.getBookStatus())
                && BookStatusEnum.BookDeleteStatus.NOT_DELETE.value.equals(baseAndAuthStatus.getIsDelete())
                && YesNoEnums.YES.code.equals(baseAndAuthStatus.getIsAuthorizedPay());
        if (boo) {
            return isSetServeAuthPay(bookId, channelId, adviserId, serveIds);
        }
        return null;
    }
}
