package com.xxfc.platform.order.biz;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.github.wxiaoqi.security.common.biz.BaseBiz;
import com.xxfc.platform.order.entity.DailyTravelOrderStatistics;
import com.xxfc.platform.order.entity.OrderStatistics;
import com.xxfc.platform.order.mapper.DailyTravelOrderStatisticsMapper;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.*;

/**
 * 每日旅游订单统计
 *
 * @author Administrator
 */
@Service
public class DailyTravelOrderStatisticsBiz extends BaseBiz<DailyTravelOrderStatisticsMapper, DailyTravelOrderStatistics> {

     @Transactional(rollbackFor = Exception.class)
    public boolean StatisticsOfTravelOrders() {
        try {

            ArrayList<DailyTravelOrderStatistics> objects = new ArrayList<>();
            List<DailyTravelOrderStatistics> travelGmv = mapper.getTravelGmv();
            objects.addAll(travelGmv);
            List<DailyTravelOrderStatistics> travelPenalSum = mapper.getTravelPenalSum();
            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));

            }

            for (Map.Entry<Integer, DailyTravelOrderStatistics> e : map.entrySet()) {
                insertSelectiveRe(e.getValue());
            }
        }
    }


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

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