package com.pcloud.book.consumer.trade;

import com.pcloud.book.base.exception.BookBizException;
import cn.hutool.core.collection.CollUtil;
import com.pcloud.common.core.aspect.ParamLog;
import com.pcloud.common.dto.ResponseDto;
import com.pcloud.common.exceptions.BizException;
import com.pcloud.common.utils.ListUtils;
import com.pcloud.common.utils.ResponseHandleUtil;
import com.pcloud.facade.tradecenter.dto.BookGroupSaleSearchDto;
import com.pcloud.facade.tradecenter.dto.BookIncomeQueryVo;
import com.pcloud.facade.tradecenter.dto.ClassifyPayDetailDto;
import com.pcloud.facade.tradecenter.dto.GroupIncomeSearchDto;
import com.pcloud.facade.tradecenter.dto.GroupMoneyDto;
import com.pcloud.facade.tradecenter.dto.IncomeBackDto;
import com.pcloud.facade.tradecenter.dto.OrderGroupFormDto;
import com.pcloud.facade.tradecenter.dto.OrderSearchDto;
import com.pcloud.facade.tradecenter.dto.ProductSaleDetailDto;
import com.pcloud.facade.tradecenter.dto.QrGroupBuyDetailDto;
import com.pcloud.facade.tradecenter.dto.SaleDetailByQrcodeDto;
import com.pcloud.facade.tradecenter.dto.SpeWechatGroupDto;
import com.pcloud.facade.tradecenter.dto.WechatGroupDto;
import com.pcloud.facade.tradecenter.service.OrderFormService;
import com.pcloud.facade.tradecenter.service.OrderItemService;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author:lili
 * @Desr:交易调用
 * @Date:2019/5/7 17:22
 */
@Component("tradeConsr")
public class TradeConsr {

    /**
     * logger
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(TradeConsr.class);
    @Autowired
    private OrderFormService orderFormService;
    @Autowired
    private OrderItemService orderItemService;

    public Map<Long, QrGroupBuyDetailDto> getQrGroupSaleDetail(List<Long> qrcodeIds) throws BizException {
        if (ListUtils.isEmpty(qrcodeIds)) {
            return null;
        }
        try {
            return ResponseHandleUtil.parseMapResponse(orderFormService.getQrGroupSaleDetail(qrcodeIds)
                    , Long.class, QrGroupBuyDetailDto.class);
        } catch (Exception e) {
            LOGGER.error("获取购买次数.[getQrGroupSaleDetail]:" + e.getMessage(), e);
        }
        return null;
    }

    /**
     * 获取交易额
     * @param wechatGroupDto
     * @return
     * @throws BizException
     */
    public Map<Long, GroupMoneyDto> getQrGroupSaleMoney(WechatGroupDto wechatGroupDto) throws BizException {
        Map<Long, GroupMoneyDto> map = new HashMap<>();
        if (wechatGroupDto == null) {
            return map;
        }
        try {
            ResponseEntity<ResponseDto<Map<Long, GroupMoneyDto>>> responseEntityP = orderFormService.getQrGroupSaleMoney(wechatGroupDto);
            map = ResponseHandleUtil.parseMap(responseEntityP, Long.class, GroupMoneyDto.class);
        } catch (Exception e) {
            LOGGER.error("获取交易额.[getQrGroupSaleMoney]:" + e.getMessage(), e);
        }
        if (map == null) {
            map = new HashMap<>();
        }
        return map;
    }

    /**
     * 获取购买人数量
     */
    public Map<Long, GroupMoneyDto> getSpeQrGroupSaleMoney(SpeWechatGroupDto speWechatGroupDto) throws BizException{
        Map<Long, GroupMoneyDto> map = new HashMap<>();
        if (speWechatGroupDto == null) {
            return map;
        }
        try {
            ResponseEntity<ResponseDto<Map<Long, GroupMoneyDto>>> responseEntityP = orderFormService.getSpeQrGroupSaleMoney(speWechatGroupDto);
            map = ResponseHandleUtil.parseMap(responseEntityP, Long.class, GroupMoneyDto.class);
        } catch (Exception e) {
            LOGGER.error("获取交易额.[获取购买人数量]:" + e.getMessage(), e);
        }
        if (map == null) {
            map = new HashMap<>();
        }
        return map;
    }

    @ParamLog("根据微信群id查询销售情况")
    public List<SaleDetailByQrcodeDto> getSaleDetailByQrcodeId(Long qrcodeId) throws BizException{
        List<SaleDetailByQrcodeDto> list=new ArrayList<>();
        if (qrcodeId == null) {
            return list;
        }
        try {
            ResponseEntity<ResponseDto<List<SaleDetailByQrcodeDto>>> responseEntity = orderFormService.getSaleDetailByQrcodeId(qrcodeId);
            list = ResponseHandleUtil.parseListResponse(responseEntity, SaleDetailByQrcodeDto.class);
        } catch (Exception e) {
            LOGGER.error("根据微信群id查询销售情况:" + e.getMessage(), e);
        }
        if (list == null) {
            list = new ArrayList<>();
        }
        return list;
    }

    @ParamLog("根据微信群id和wechatUserId查询销售额")
    public BigDecimal getAmountByQrcodeId(Long qrcodeId,Long wechatUserId) throws BizException{
        BigDecimal amount=BigDecimal.ZERO;
        if (qrcodeId == null) {
            return amount;
        }
        try {
            ResponseEntity<ResponseDto<BigDecimal>> responseEntity = orderFormService.getAmountByQrcodeId(qrcodeId,wechatUserId);
            amount = ResponseHandleUtil.parseResponse(responseEntity, BigDecimal.class);
        } catch (Exception e) {
            LOGGER.error("根据微信群id和wechatUserId查询销售额:" + e.getMessage(), e);
        }
        if (amount == null) {
            amount = BigDecimal.ZERO;
        }
        return amount;
    }


    @ParamLog("获取用户购买或者参与过的社群码ID")
    public List<Long> getBuyBookGroupIdList(Long channelId, Long wechatUserId) throws BizException {
        List<Long> results = new ArrayList<>();
        try {
            ResponseEntity<ResponseDto<List<Long>>> responseEntity = orderFormService.getBuyBookGroupIdList(wechatUserId, channelId);
            results = ResponseHandleUtil.parseListResponse(responseEntity, Long.class);
        } catch (Exception e) {
            LOGGER.error("获取用户购买或者参与过的社群码ID详情:" + e.getMessage(), e);
        }
        return results;
    }

    @ParamLog("获取社群码下的应用作品购买量")
    public List<ClassifyPayDetailDto> getGroupBuyCount(Long bookGroupId, Long classifyId, Long qrcodeId, Date startDate, Date endDate) throws BizException{
        List<ClassifyPayDetailDto> classifyPayDetailDtos = new ArrayList<>();
        try {
            ResponseEntity<ResponseDto<List<ClassifyPayDetailDto>>> responseEntity = orderFormService.getSaleVolume(startDate,endDate,bookGroupId,classifyId,qrcodeId);
            classifyPayDetailDtos = ResponseHandleUtil.parseListResponse(responseEntity, ClassifyPayDetailDto.class);
        } catch (Exception e) {
            LOGGER.error("获取社群码下的应用作品购买量:" + e.getMessage(), e);
        }
        if (ListUtils.isEmpty(classifyPayDetailDtos)) {
            classifyPayDetailDtos = new ArrayList<>();
        }
        return classifyPayDetailDtos;
    }

    @ParamLog("查询社区码下购买应用详情")
    public Map<Long, GroupMoneyDto> getSaleDetail4Group(GroupIncomeSearchDto groupIncomeSearchDto) throws BizException {
        Map<Long, GroupMoneyDto> groupMoneyDtoMap = new HashMap<>();
        try {
            ResponseEntity<ResponseDto<Map<Long, GroupMoneyDto>>> responseEntity = orderFormService.getSaleDetail4Group(groupIncomeSearchDto);
            groupMoneyDtoMap = ResponseHandleUtil.parseMap(responseEntity, Long.class, GroupMoneyDto.class);
        } catch (Exception e) {
            LOGGER.error("查询社区码下购买应用详情:" + e.getMessage(), e);
        }
        if (MapUtils.isEmpty(groupMoneyDtoMap)) {
            groupMoneyDtoMap = new HashMap<>();
        }
        return groupMoneyDtoMap;
    }

    @ParamLog("查询社群码下购买应用或作品的总销售额")
    public BigDecimal getTotalSale(Long bookGroupId, Long classifyId, Long qrcodeId, String type) throws BizException {
        BigDecimal totalSale = BigDecimal.ZERO;
        try {
            ResponseEntity<ResponseDto<BigDecimal>> responseEntity = orderFormService.getSaleAmount4Group(bookGroupId,classifyId,qrcodeId,type);
            totalSale = ResponseHandleUtil.parseResponse(responseEntity, BigDecimal.class);
        } catch (Exception e) {
            LOGGER.error("查询社区码下购买应用详情:" + e.getMessage(), e);
        }
        return totalSale;
    }

    @ParamLog("查社群码资源购买情况")
    public Map<Long, ProductSaleDetailDto> getSaleInfo4Group(List<Long> bookGroupIds, String month) {
        Map<Long, ProductSaleDetailDto> map = new HashMap<>();
        try {
            OrderSearchDto orderSearchDto = new OrderSearchDto();
            orderSearchDto.setBookGroupIds(bookGroupIds);
            orderSearchDto.setDate(month);
            map = ResponseHandleUtil.parseMapResponse(orderFormService.getSaleInfo4Group(orderSearchDto), Long.class, ProductSaleDetailDto.class);

        } catch (Exception e) {
            LOGGER.error("查社群码资源购买情况失败" + e.getMessage(), e);
        }
        return map;
    }

    @ParamLog("通过群id和群分类id拿到群购买情况")
    public Map<Long, QrGroupBuyDetailDto> getQrGroupSaleInfo(List<BookGroupSaleSearchDto> list) throws BizException {
        if (ListUtils.isEmpty(list)) {
            return null;
        }
        try {
            return ResponseHandleUtil.parseMapResponse(orderFormService.getQrGroupSaleInfo(list)
                    , Long.class, QrGroupBuyDetailDto.class);
        } catch (Exception e) {
            LOGGER.error("通过群id和群分类id拿到群购买情况c出错.[getQrGroupSaleInfo]:" + e.getMessage(), e);
        }
        return null;
    }

    @ParamLog("获取图书收益")
    public Map<String, IncomeBackDto> getBookIncome(List<BookIncomeQueryVo> bookIncomeQueryVos, String date)throws BizException {
        Map<String, IncomeBackDto> incomeMap = null;
        if (ListUtils.isEmpty(bookIncomeQueryVos)){
            return incomeMap;
        }
        try {
            ResponseEntity<ResponseDto<Map<String, IncomeBackDto>>> responseTemp = orderFormService.getBookIncome(bookIncomeQueryVos, date);
            incomeMap = ResponseHandleUtil.parseMapResponse(responseTemp, String.class, IncomeBackDto.class);
        } catch (Exception e) {
            LOGGER.error("[消TRADECENTER.orderFormService.getBookIncome]出现异常，信息为:"+ e.getMessage(), e);
            throw new BookBizException(BookBizException.ERROR, "ERROR TRADECENTER");
        }
        if (incomeMap == null) {
            return new HashMap<String, IncomeBackDto>();
        }
        return incomeMap;
    }

    /**
     * 根据群ID去交易中心查询群内订单统计信息
     */
    public Map<Long, OrderGroupFormDto> getOrderGroupForm4ES(List<Long> qrcodeIds) {
        LOGGER.error("根据群ID去交易中心查询群内订单统计信息.[getOrderGroupForm4ES] qrcodeIds:{}", qrcodeIds);
        Map<Long, OrderGroupFormDto> map = CollUtil.newHashMap(0);
        if (CollUtil.isEmpty(qrcodeIds)) {
            return map;
        }
        try {
            map = ResponseHandleUtil.parseMap(orderItemService.getOrderGroupForms(qrcodeIds), Long.class, OrderGroupFormDto.class);
        } catch (Exception e) {
            LOGGER.error("根据群ID去交易中心查询群内订单统计信息失败.[getOrderGroupForm4ES]:" + e.getMessage(), e);
        }
        return map;
    }
}
