package com.xxfc.platform.order.biz;

import cn.hutool.json.JSONUtil;
import com.github.wxiaoqi.security.common.biz.BaseBiz;
import com.google.common.collect.Lists;
import com.xxfc.platform.order.contant.enumerate.OrderTypeEnum;
import com.xxfc.platform.order.entity.DailyMembersOrderStatistics;
import com.xxfc.platform.order.entity.MembersOrder;
import com.xxfc.platform.order.entity.OrderStatistics;
import com.xxfc.platform.order.mapper.DailyMembersOrderStatisticsMapper;
import com.xxfc.platform.order.pojo.OrderQuery;
import com.xxfc.platform.order.pojo.Term;
import com.xxfc.platform.order.pojo.account.OrderAccountDTO;
import com.xxfc.platform.order.pojo.account.OrderAccountDetail;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.weekend.WeekendSqls;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

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

    private final Integer headOfficeId = 1;


    /**
     * 总公司id默认为1
     */
    private final Integer OMPANY_ID = 1;
    @Autowired
    private OrderAccountBiz accountBiz;

    @Transactional(rollbackFor = Exception.class)
    public boolean dailyMembersOrderRecord(Integer day) {
        try {
            DailyMembersOrderStatistics orderStatistics = statistics(new Term(OrderTypeEnum.MEMBER.getCode(), day, 1, null, null, null));
            log.info("Members:统计完成");
            save(orderStatistics);
            log.info("Members:保存成功");
            return true;
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            log.error("Members:" + e.getMessage());

            return false;
        }
    }

    public void save(DailyMembersOrderStatistics orderStatistics) {
        if (orderStatistics != null) {
            if (JudgmentOfExistence(orderStatistics)) {
                insertSelectiveRe(orderStatistics);
            } else {
                mapper.updateByExampleSelective(orderStatistics, Example.builder(DailyMembersOrderStatistics.class)
                        .where(WeekendSqls.<DailyMembersOrderStatistics>custom()
                                .andEqualTo(DailyMembersOrderStatistics::getOneDay, orderStatistics.getOneDay())
                                .andEqualTo(DailyMembersOrderStatistics::getBranchCompanyId, orderStatistics.getBranchCompanyId()))
                        .build());
            }
        }
    }

    public DailyMembersOrderStatistics statistics(Term term) {
        List<OrderAccountDTO> accountList = accountBiz.getOrderAccountByOrderType(term);

        log.error("Members:accountList:"+accountList);

        if (CollectionUtils.isNotEmpty(accountList)) {
            DailyMembersOrderStatistics orderStatistics = new DailyMembersOrderStatistics();
            ArrayList<OrderAccountDetail> orderAccountDetails = getOrderAccountDetail(accountList);
            log.error("Members:orderAccountDetails:"+orderAccountDetails);
            if (CollectionUtils.isNotEmpty(orderAccountDetails)) {
                //获取订单总额
                BigDecimal gmv = getOrderAmountTotal(orderAccountDetails);
                orderStatistics.setGmv(gmv);
                orderStatistics.setBranchCompanyId(OMPANY_ID);
                orderStatistics.setOneDay(accountList.get(0).getOneDay());
            }
            return orderStatistics;
        }
        return null;
    }

    /**
     * 添加前查询是否存在这条数据
     *
     * @param orderStatistic
     * @return
     */
    private boolean JudgmentOfExistence(DailyMembersOrderStatistics orderStatistic) {
        List<DailyMembersOrderStatistics> statistics = selectByExample(Example.builder(DailyMembersOrderStatistics.class)
                .where(WeekendSqls.<DailyMembersOrderStatistics>custom()
                        .andEqualTo(DailyMembersOrderStatistics::getOneDay, orderStatistic.getOneDay())
                        .andEqualTo(DailyMembersOrderStatistics::getBranchCompanyId, orderStatistic.getBranchCompanyId()))
                .build());
        if (CollectionUtils.isNotEmpty(statistics)) {
            return false;
        }
        return true;
    }

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

    /**
     * 获取所有订单详情数据
     *
     * @param orderAccountDTOS
     * @return
     */
    private ArrayList<OrderAccountDetail> getOrderAccountDetail(List<OrderAccountDTO> orderAccountDTOS) {
        ArrayList<OrderAccountDetail> arrayList = Lists.newArrayList();
        List<OrderAccountDetail> oad = Collections.synchronizedList(arrayList);
        orderAccountDTOS.parallelStream()
                .map(OrderAccountDTO::getAccountDetail)
                .forEach(detail -> {
                    if (StringUtils.isNotBlank(detail)) {
                        oad.add(JSONUtil.toBean(detail, OrderAccountDetail.class));
                    }
                });
        return new ArrayList<OrderAccountDetail>(oad);
    }

    @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(List<Integer> companyIds) {
        return mapper.monthOrderTotal(companyIds);
    }

    /**
     * 根据时间按年月日分组
     *
     * @param query
     * @return
     */
    public List<MembersOrder> getMemberOrderStatistics(OrderQuery query) {
        return mapper.getMemberOrderStatistics(query);
    }
}
