package com.xxfc.platform.order.biz;

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.xxfc.platform.order.contant.enumerate.OrderTypeEnum;
import com.xxfc.platform.order.entity.DailyMembersOrderStatistics;
import com.xxfc.platform.order.entity.OrderAccount;
import com.xxfc.platform.order.entity.OrderStatistics;
import com.xxfc.platform.order.mapper.DailyMembersOrderStatisticsMapper;
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.beanutils.BeanUtils;
import org.apache.commons.collections.CollectionUtils;
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.ArrayList;
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;

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

    @Transactional(rollbackFor = Exception.class)
    public boolean saveDailyMembersOrderRecord() {
        try {
            List<OrderAccountDTO> accountList = accountBiz.getOrderAccountByOrderType(OrderTypeEnum.MEMBER.getCode(), day);

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

            return true;
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 获取押金和
     *
     * @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();
        orderAccountDTOS.parallelStream()
                .map(OrderAccount::getAccountDetail)
                .forEach(detail -> {
                    if (StringUtils.isNotBlank(detail)) {
                        arrayList.add(JSONUtil.toBean(detail, OrderAccountDetail.class));
                    }
                });

        return arrayList;
    }

    @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);
    }
}
