package com.xxfc.platform.order.biz;

import com.github.wxiaoqi.security.common.biz.BaseBiz;
import com.github.wxiaoqi.security.common.exception.BaseException;
import com.xxfc.platform.order.entity.DailyMembersOrderStatistics;
import com.xxfc.platform.order.entity.OrderStatistics;
import com.xxfc.platform.order.mapper.DailyMembersOrderStatisticsMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
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.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 每日购买会员订单统计
 *
 * @author Administrator
 */
@Service
@Slf4j
public class DailyMembersOrderStatisticsBiz extends BaseBiz<DailyMembersOrderStatisticsMapper, DailyMembersOrderStatistics> {

    private final Integer headOfficeId = 1;

    @Value("${order.day}")
    private Integer day;

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

            Map<String, Object> travelGmv = mapper.getTravelGmv(day);
            if (travelGmv.isEmpty()) {
                return true;
            }


            DailyMembersOrderStatistics MembersStatistics = new DailyMembersOrderStatistics();
            BeanUtils.copyProperties(MembersStatistics, travelGmv);

            String oneDay = MembersStatistics.getOneDay();

            if (StringUtils.isBlank(oneDay)) {
                throw new BaseException();
            }

            Example exa = new Example(DailyMembersOrderStatistics.class);
            exa.createCriteria().andEqualTo("oneDay", oneDay);
            List<DailyMembersOrderStatistics> statistics = selectByExample(exa);
            if (CollectionUtils.isEmpty(statistics)) {
                insertSelective(MembersStatistics);
            }
            return true;
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public int insertSelectiveRe(DailyMembersOrderStatistics entity) {
        Date date = new Date();
        if (log.isDebugEnabled()) {
            log.debug("时间******[{}]", date);
        }
        entity.setBranchCompanyId(headOfficeId);
        entity.setCrtTime(date);
        return mapper.insertSelective(entity);
    }

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