package com.xxfc.platform.order.biz;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.json.JSONUtil;
import com.github.wxiaoqi.security.common.biz.BaseBiz;
import com.github.wxiaoqi.security.common.exception.BaseException;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.xxfc.platform.order.contant.enumerate.DeductionTypeEnum;
import com.xxfc.platform.order.contant.enumerate.OrderTypeEnum;
import com.xxfc.platform.order.contant.enumerate.RefundTypeEnum;
import com.xxfc.platform.order.entity.DailyTravelOrderStatistics;
import com.xxfc.platform.order.entity.OrderAccount;
import com.xxfc.platform.order.entity.OrderStatistics;
import com.xxfc.platform.order.mapper.DailyTravelOrderStatisticsMapper;
import com.xxfc.platform.order.pojo.account.OrderAccountDTO;
import com.xxfc.platform.order.pojo.account.OrderAccountDeduction;
import com.xxfc.platform.order.pojo.account.OrderAccountDetail;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 每日旅游订单统计
 *
 * @author Administrator
 */
@Service
@Slf4j
public class DailyTravelOrderStatisticsBiz extends BaseBiz<DailyTravelOrderStatisticsMapper, DailyTravelOrderStatistics> {
    @Value("${order.day}")
    private Integer day;


    @Autowired
    private OrderAccountBiz accountBiz;
//     @Transactional(rollbackFor = Exception.class)
//    public boolean StatisticsOfTravelOrders() {
//        try {
//
//            ArrayList<DailyTravelOrderStatistics> objects = new ArrayList<>();
//            List<DailyTravelOrderStatistics> travelGmv = mapper.getTravelGmv(day);
//            objects.addAll(travelGmv);
//            List<DailyTravelOrderStatistics> travelPenalSum = mapper.getTravelPenalSum(day);
//            objects.addAll(travelPenalSum);
//            insertByList(objects);
//
//            return true;
//        } catch (Exception e) {
//            e.printStackTrace();
//            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//            return false;
//        }
//    }
//
//    private void insertByList(ArrayList<DailyTravelOrderStatistics> objects) throws Exception {
//
//        if (CollectionUtils.isNotEmpty(objects)) {
//            HashMap<Integer, DailyTravelOrderStatistics> map = new HashMap<>();
//            for (DailyTravelOrderStatistics object : objects) {
//
//                DailyTravelOrderStatistics statistics = map.get(object.getBranchCompanyId());
//                if (statistics == null) {
//                    statistics = new DailyTravelOrderStatistics();
//                    map.put(object.getBranchCompanyId(), statistics);
//                }
//
//                BeanUtil.copyProperties(object, statistics, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
//
//            }
//            String oneDay = map.entrySet().parallelStream().map(Map.Entry::getValue).collect(Collectors.toList()).get(0).getOneDay();
//
//            if (StringUtils.isBlank(oneDay)) {
//                throw new BaseException();
//            }
//            Example exa= new Example(DailyTravelOrderStatistics.class);
//            exa.createCriteria().andEqualTo("oneDay",oneDay);
//            List<DailyTravelOrderStatistics> statistics= selectByExample(exa);
//            if (CollectionUtils.isEmpty(statistics)){
//                for (Map.Entry<Integer, DailyTravelOrderStatistics> entry : map.entrySet()) {
//                    insertSelectiveRe(entry.getValue());
//                }
//            }else {
//                log.error("今日已统计车辆订单,请不要重复统计!");
//            }
//
////
////            for (Map.Entry<Integer, DailyTravelOrderStatistics> e : map.entrySet()) {
////                insertSelectiveRe(e.getValue());
////            }
//        }
//    }
/******************************************************************************************************************************/

    /**
     * 统计订单并保存到数据库当中
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean saveDailyTravelOrderRecord() {
        try {
            //获取每日订单统计
            List<DailyTravelOrderStatistics> orderStatistics = getDailyTravelOrderStatistics();
            if (CollectionUtils.isNotEmpty(orderStatistics)) {
                for (DailyTravelOrderStatistics orderStatistic : orderStatistics) {
                    //保存统计
                    insertSelectiveRe(orderStatistic);
                }
            }
            return true;
        } catch (Exception e) {
            log.error(e.getMessage());
            return false;
        }
    }

    private List<DailyTravelOrderStatistics> getDailyTravelOrderStatistics() {
        //获取当天所有订单账目
        List<OrderAccountDTO> accountList = accountBiz.getOrderAccountByOrderType(OrderTypeEnum.TOUR.getCode(), day);
        if (CollectionUtils.isEmpty(accountList)) {
            return null;
        }
        //获取每个分公司,当天所有的订单帐目
        HashMap<Integer, List<OrderAccountDTO>> companyIdmap = new HashMap<>();
        for (OrderAccountDTO orderAccountDTO : accountList) {
            List<OrderAccountDTO> list = companyIdmap.get(orderAccountDTO.getCompanyId());
            if (list == null) {
                list = new ArrayList<>();
                companyIdmap.put(orderAccountDTO.getCompanyId(), list);
            }
            list.add(orderAccountDTO);
        }

        //获取每个公司当天订单的总数据
        ArrayList<DailyTravelOrderStatistics> statistics = new ArrayList<>();
        for (Map.Entry<Integer, List<OrderAccountDTO>> integerListEntry : companyIdmap.entrySet()) {
            //获取不同类型的账单详情
            List<OrderAccountDTO> orderAccountDTOS = integerListEntry.getValue();
            if (CollectionUtils.isNotEmpty(orderAccountDTOS)) {
                Map<Integer, List<OrderAccountDTO>> typeMap = Maps.newHashMap();
                for (OrderAccountDTO orderAccountDTO : orderAccountDTOS) {
                    List<OrderAccountDTO> list = typeMap.get(orderAccountDTO.getAccountType());
                    if (list == null) {
                        list = new ArrayList<>();
                        companyIdmap.put(orderAccountDTO.getAccountType(), list);
                    }
                    list.add(orderAccountDTO);
                }

                if (MapUtils.isNotEmpty(typeMap)) {
                    //获取该公司当天的账单数据
                    if (CollectionUtils.isNotEmpty(orderAccountDTOS)) {
                        DailyTravelOrderStatistics dvos = getStatisticsByOrderAccountDetail(typeMap);
                        if (dvos != null) {
                            statistics.add(dvos);
                            dvos.setBranchCompanyId(integerListEntry.getKey());
                            dvos.setOneDay(orderAccountDTOS.get(0).getOneDay());
                        }
                    }
                }
            }
        }

        return statistics;
    }

    private DailyTravelOrderStatistics getStatisticsByOrderAccountDetail(Map<Integer, List<OrderAccountDTO>> map) {
        //获取收入金额
        DailyTravelOrderStatistics orderStatistics = getGmvAndSecurityDeposit(map);
        //获取扣款和退还金额
        refundAndDeductions(map, orderStatistics);
        return orderStatistics;
        
    }

    /**
     * 获取扣款和退款金额
     *
     * @param map
     * @param orderStatistics
     */
    private void refundAndDeductions(Map<Integer, List<OrderAccountDTO>> map, DailyTravelOrderStatistics orderStatistics) {
        ArrayList<OrderAccountDTO> arrayList = Lists.newArrayList();
        for (Integer key : map.keySet()) {
            if (!key.equals(RefundTypeEnum.ORDER_FUND.getCode())) {
                arrayList.addAll(map.get(key));
            }
        }
        if (CollectionUtils.isNotEmpty(arrayList)) {
            ArrayList<OrderAccountDetail> orderAccountDetail = getOrderAccountDetail(arrayList);
            if (CollectionUtils.isNotEmpty(orderAccountDetail)) {
                List<OrderAccountDeduction> OrderAccountDeductions = gettDeductions(orderAccountDetail);
                //获取违约总额
                BigDecimal bigDecimal = get(OrderAccountDeductions, new ArrayList<Integer>() {{
                    add(DeductionTypeEnum.VIOLATE_CANCEL.getCode());
                }});
                orderStatistics.setDefaultMoney(bigDecimal);

                //订单退还总额
                orderStatistics.setReturnGmv(orderStatistics.getGmv().subtract(bigDecimal));

            }
        }
    }
   

    
    private DailyTravelOrderStatistics getGmvAndSecurityDeposit(Map<Integer, List<OrderAccountDTO>> map) {
        DailyTravelOrderStatistics orderStatistics = new DailyTravelOrderStatistics();
        List<OrderAccountDTO> orderAccountDTOS = map.get(RefundTypeEnum.ORDER_FUND.getCode());

        if (CollectionUtils.isNotEmpty(orderAccountDTOS)) {
            ArrayList<OrderAccountDetail> orderAccountDetails = getOrderAccountDetail(orderAccountDTOS);
            if (CollectionUtils.isNotEmpty(orderAccountDetails)) {
                //获取订单总额
                BigDecimal gmv = getOrderAmountTotal(orderAccountDetails);
                orderStatistics.setGmv(gmv);

            }
        }
        return orderStatistics;
    }

    /**
     * 获取金额详情
     *
     * @param orderAccountDTOS
     * @return
     */
    private ArrayList<OrderAccountDetail> getOrderAccountDetail(List<OrderAccountDTO> orderAccountDTOS) {
        ArrayList<OrderAccountDetail> arrayList = Lists.newArrayList();
        orderAccountDTOS.parallelStream()
                .map(OrderAccount::getAccountDetail)
                .forEach(detail -> {
                    if (StringUtils.isNotBlank(detail)) {
                        arrayList.add(JSONUtil.toBean(detail, OrderAccountDetail.class));
                    }
                });

        return arrayList;
    }


    /**
     * 获取订单和
     *
     * @param orderAccountDetails
     * @return
     */
    private BigDecimal getOrderAmountTotal(ArrayList<OrderAccountDetail> orderAccountDetails) {
        return orderAccountDetails.stream()
                .map(OrderAccountDetail::getOrderAmount)
                .reduce(BigDecimal.ZERO, BigDecimal::add);
    }

    /**
     * 获取赔款数据
     *
     * @param orderAccountDetails
     * @return
     */
    private List<OrderAccountDeduction> gettDeductions(ArrayList<OrderAccountDetail> orderAccountDetails) {
        ArrayList<OrderAccountDeduction> arrayList = Lists.newArrayList();
        for (OrderAccountDetail orderAccountDetail : orderAccountDetails) {
            arrayList.addAll(orderAccountDetail.getDeductions());
        }
        return arrayList;
    }


    /**
     * 根据type获取对应的金额总和
     *
     * @param OrderAccountDeduction
     * @param type                  金额类型
     * @return
     */
    private BigDecimal get(List<OrderAccountDeduction> OrderAccountDeduction, List<Integer> type) {
        return OrderAccountDeduction.parallelStream()
                .filter(el -> el.getType().equals(type))
                .map(com.xxfc.platform.order.pojo.account.OrderAccountDeduction::getAmount)
                .reduce(BigDecimal.ZERO,BigDecimal::add);

    }

    @Override
    public int insertSelectiveRe(DailyTravelOrderStatistics entity) {
        entity.setCrtTime(new Date());
        return mapper.insertSelective(entity);
    }

    public OrderStatistics findAll(Integer branchCompanyId) {
        return mapper.monthOrderTotal(branchCompanyId);
    }
}
