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.OrderAccount;
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.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.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 tk.mybatis.mapper.weekend.WeekendSqls;

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

/**
 * 每日购买会员订单统计
 *
 * @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());
                }
                log.info("Members:统计完成");
                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());

                }
                log.info("Members:保存成功");
            }

            return true;
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            log.error("Members:"+ e.getMessage());

            return false;
        }
    }

    /**
     * 添加前查询是否存在这条数据
     * @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();
        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);
    }

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