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

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.pcloud.appcenter.app.dto.AppDto;
import com.pcloud.book.consumer.app.AppConsr;
import com.pcloud.book.consumer.channel.QrcodeSceneConsr;
import com.pcloud.book.consumer.promotion.PromotionConsr;
import com.pcloud.book.consumer.resource.ProductConsr;
import com.pcloud.book.group.entity.ResourcePageBookstore;
import com.pcloud.book.group.dao.ResourcePageBookstoreDao;
import com.pcloud.book.group.biz.ResourcePageBookstoreBiz;
import com.pcloud.book.group.enums.ResourcePageFixtureTypeEnum;
import com.pcloud.book.group.tools.SendWeixinRequestTools;
import com.pcloud.book.group.vo.ResourcePageBookstoreVO;
import com.pcloud.channelcenter.wechat.dto.AccountSettingDto;
import com.pcloud.common.page.PageBeanNew;
import com.pcloud.common.page.PageParam;
import com.pcloud.common.exceptions.BizException;
import com.pcloud.common.utils.ListUtils;
import com.pcloud.common.utils.NumberUtil;
import com.pcloud.promotion.couponsnew.dto.CouponsNewDto;
import com.pcloud.resourcecenter.product.dto.ProductDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 实体书购买(ResourcePageBookstore)表服务实现类
 *
 * @author makejava
 * @since 2021-08-16 14:40:27
 */
@Service("resourcePageBookstoreBiz")
public class ResourcePageBookstoreBizImpl implements ResourcePageBookstoreBiz {

    private static final Logger LOGGER = LoggerFactory.getLogger(ResourcePageBookstoreBizImpl.class);

    @Autowired
    private ResourcePageBookstoreDao resourcePageBookstoreDao;
    @Autowired
    private AppConsr appConsr;
    @Autowired
    private ProductConsr productConsr;
    @Autowired
    private QrcodeSceneConsr qrcodeSceneConsr;
    @Autowired
    private PromotionConsr promotionConsr;

    @Override
    public ResourcePageBookstore getById(Long id) {
        return resourcePageBookstoreDao.getById(id);
    }

    @Override
    public PageBeanNew getList(Integer currentPage, Integer numPerPage) {
        PageBeanNew pageBeanNew = resourcePageBookstoreDao.listPageNew(new PageParam(currentPage, numPerPage), null, "getList");
        List recordList = pageBeanNew.getRecordList();
        if (ListUtils.isEmpty(recordList)){
            return pageBeanNew;
        }
        // 加载其它数据
        
        return pageBeanNew;
    }

    @Override
    public Long insert(ResourcePageBookstore resourcePageBookstore) {
        resourcePageBookstoreDao.insert(resourcePageBookstore);
        return resourcePageBookstore.getId();
    }

    @Override
    public void insert(List<ResourcePageBookstore> list) {
        resourcePageBookstoreDao.insert(list);
    }
    
    @Override
    public void update(ResourcePageBookstore resourcePageBookstore) {
        if(resourcePageBookstore == null || !NumberUtil.isNumber(resourcePageBookstore.getId())){
            throw BizException.PARAM_DELETION;
        }
        resourcePageBookstoreDao.update(resourcePageBookstore);
    }

    @Override
    public void deleteById(Long id) {
        resourcePageBookstoreDao.deleteById(id);
    }

    @Override
    public void deleteByResourcePageId(Long resourcePageId, Integer fixtureType) {
        resourcePageBookstoreDao.deleteByResourcePageId(resourcePageId, fixtureType);
    }

    @Override
    public List<ResourcePageBookstoreVO> getByResourcePageId(Long resourcePageId, Long channelId, Long wechatUserId, ResourcePageFixtureTypeEnum fixtureTypeEnum) {
        List<ResourcePageBookstoreVO> list = resourcePageBookstoreDao.getByResourcePageId(resourcePageId, fixtureTypeEnum.fixtureType);
        if(CollUtil.isEmpty(list)){
            return CollUtil.toList();
        }
        switch (fixtureTypeEnum){
            case  BOOKSTORE:
                if(channelId != null){
                    this.fillBookstore(list, channelId);
                }
                break;
            case COUPONS:
                this.fillCoupons(list, wechatUserId);
                break;
        }
        return CollUtil.defaultIfEmpty(list, CollUtil.toList());
    }

    private void fillCoupons(List<ResourcePageBookstoreVO> list, Long wechatUserId) {
        List<Long> couponIds = list.stream().map(x -> x.getServeId()).collect(Collectors.toList());
        Map<Long, CouponsNewDto> couponsNewMap = promotionConsr.mapByCouponIds(couponIds, wechatUserId);
        for (int i = list.size() - 1; i >= 0; i--) {
            ResourcePageBookstoreVO vo = list.get(i);
            CouponsNewDto couponsNewDto = couponsNewMap.get(vo.getServeId());
            if(couponsNewDto.getState() == -1){
                list.remove(vo);
            }
            vo.setCouponsNewDto(couponsNewDto);
        }
    }

    private void fillBookstore(List<ResourcePageBookstoreVO> list, Long channelId) {
        List<Long> appIds = list.stream().filter(x -> ObjectUtil.equal(x.getServeType(), "APP")).map(x -> x.getServeId()).collect(Collectors.toList());
        List<Long> productIds = list.stream().filter(x -> ObjectUtil.equal(x.getServeType(), "PRODUCT")).map(x -> x.getServeId()).collect(Collectors.toList());
        Map<Long, AppDto> appDtoMap = appConsr.getBaseByIds(appIds);
        Map<Long, ProductDto> productDtoMap = productConsr.getProBasesByIds(productIds);
        AccountSettingDto accountSettingDto = qrcodeSceneConsr.getWechatInfo(channelId);
        if (null == accountSettingDto) {
            LOGGER.info("未配置公众号");
            return;
        }
        for (ResourcePageBookstoreVO vo : list) {
            if(ObjectUtil.equal(vo.getServeType(), "APP")){
                AppDto appDto = appDtoMap.get(vo.getServeId());
                if(appDto == null){
                    continue;
                }
                vo.setServeName(appDto.getTitle());
                vo.setServePic(appDto.getSquareImg());
                vo.setServeTypeCode(appDto.getTypeCode());
                vo.setServeTypeName(appDto.getTypeName());
                vo.setResultUrl(SendWeixinRequestTools.splitUrl(accountSettingDto, vo.getLinkUrl()));
            }
            if(ObjectUtil.equal(vo.getServeType(), "PRODUCT")){
                ProductDto productDto = productDtoMap.get(vo.getServeId());
                if(productDto == null){
                    continue;
                }
                vo.setServeName(productDto.getProductName());
                vo.setServePic(productDto.getCoverImg());
                if (productDto.getProductTypeDto() != null){
                    vo.setServeTypeCode(productDto.getProductTypeDto().getTypeCode());
                    vo.setServeTypeName(productDto.getProductTypeDto().getTypeName());
                }
                vo.setResultUrl(SendWeixinRequestTools.splitUrl(accountSettingDto, vo.getLinkUrl()));
            }
        }
    }
}
