package com.github.wxiaoqi.security.admin.biz;

import com.github.wxiaoqi.security.admin.bo.UserIncomeBo;
import com.github.wxiaoqi.security.admin.dto.*;
import com.github.wxiaoqi.security.admin.entity.*;
import com.github.wxiaoqi.security.admin.mapper.BaseOrderAcceptDetailedMapper;
import com.github.wxiaoqi.security.admin.vo.SellingWalletPagVo;
import com.github.wxiaoqi.security.admin.vo.SellingWalletVo;
import com.github.wxiaoqi.security.common.biz.BaseBiz;
import com.github.wxiaoqi.security.common.exception.BaseException;
import com.github.wxiaoqi.security.common.util.process.ResultCode;
import com.github.wxiaoqi.security.common.vo.PageDataVO;
import com.xxfc.platform.vehicle.pojo.dto.order.VMCalendarPriceCostDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;
import java.math.BigDecimal;
import java.util.*;

/**
 * 订单分账表
 *
 * @author zjw
 * @email 18178966185@163.com
 * @date 2019-07-11 14:14:54
 */
@Service
@Slf4j
public class BaseOrderAcceptDetailedBiz extends BaseBiz<BaseOrderAcceptDetailedMapper, BaseOrderAcceptDetailed> {


    @Autowired
    AppUserRelationBiz relationBiz;

    @Autowired
    BaseGoodCommissionBiz commissionBiz;

    @Autowired
    AppUserPositionBiz positionBiz;

    @Autowired
    AppUserDetailBiz detailBiz;

    @Autowired
    private AppUserLoginBiz appUserLoginBiz;

    @Autowired
    private AppUserDetailBiz appUserDetailBiz;

    @Autowired
    MyWaterBiz myWaterBiz;

    @Autowired
    BaseCommissionRatioBiz commissionRatioBiz;

    @Autowired
    BranchCompanyBiz companyBiz;

    @Autowired
    AppUserSellingWaterBiz sellingWaterBiz;


    //计算用户拥金
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void orderWater(OrderWaterDTO orderWaterDTO) {
        //订单状态
        Integer status = orderWaterDTO.getStatus();
        if (status == null || status == 0) {
            log.info("购买计算用户拥金----payOrderWater----参数不能为空----status===" + status);
            return;
        }
        if (status == 1) {
            payOrderAccept(orderWaterDTO);
        } else if (status == 2) {
            finishOrderAccept(orderWaterDTO);
            sellingWaterBiz.updWalletByOrderId(orderWaterDTO);
        } else {
            refundOrderAccept(orderWaterDTO);
            sellingWaterBiz.updWalletByOrderId(orderWaterDTO);
        }
    }

    //下单分账
    public void payOrderAccept(OrderWaterDTO orderWaterDTO) {
        //订单id
        Integer orderId = orderWaterDTO.getOrderId() == null ? 0 : orderWaterDTO.getOrderId();
        //订单号
        String orderNo = orderWaterDTO.getOrderNo();
        //用户id
        Integer userId = orderWaterDTO.getUserId()  == null ? 0 : orderWaterDTO.getUserId();
        Integer companyId = orderWaterDTO.getCompanyId()  == null ? 0 : orderWaterDTO.getCompanyId();
        List<OrderGoodsDTO> goodsDTOList = orderWaterDTO.getGoodsDTOList();
        log.info("分账----payOrderAccept----userId====" + userId + "---orderId===" + orderId + "---orderNo===" + orderNo+"----companyId==="+companyId);
        if (orderId == 0  || userId == 0 || companyId == 0 || CollectionUtils.isEmpty(goodsDTOList)) {
            throw  new BaseException("分账----payOrderAccept----参数不能为空----orderId===" + orderId,ResultCode.FAILED_CODE);
        }
        BigDecimal orderAmount = goodsDTOList.stream().map(OrderGoodsDTO::getPrice).reduce(BigDecimal.ZERO, BigDecimal::add);

        log.info("分账----payOrderAccept--------userId===" + userId + "---orderAmount===="+orderAmount);

        List<BaseCommissionRatio> baseCommissionRatios = commissionRatioBiz.getList();
        BigDecimal amount=BigDecimal.ZERO;
        BigDecimal companyDivisionAmount=orderAmount;
        if (baseCommissionRatios.size() > 0){
            //先计算分给店铺
            BigDecimal  companyExtrac = baseCommissionRatios.stream().map(BaseCommissionRatio::getExtract).reduce(BigDecimal.ZERO,BigDecimal::add);
            companyExtrac = new BigDecimal(100).subtract(companyExtrac);
            //店铺金额
            companyDivisionAmount=orderAmount.multiply(companyExtrac).divide(new BigDecimal(100)).setScale(2,   BigDecimal.ROUND_HALF_UP);
            //其他金额
            BigDecimal  otherDivisionAmount=orderAmount.subtract(companyDivisionAmount);

            Integer num = 0;
            for (BaseCommissionRatio commissionRatio:baseCommissionRatios){
                num++;
                Integer type = commissionRatio.getType() == null ? 0 : commissionRatio.getType();
                Integer mchId=0;
                Integer divisionType=0;
                if (type == 1 ){
                    BranchCompany branchCompany = companyBiz.selectById(companyId);
                    if (branchCompany != null ){
                        mchId=branchCompany.getInviterAccount() == null ? 0 : branchCompany.getInviterAccount();
                    }
                    divisionType=4;
                }else if (type == 2){
                    AppUserRelation relation = relationBiz.getRelationByIdUserIdAndTime(userId);
                    if (relation == null ) {
                        log.info("分账----payOrderAccept--------userId===" + userId + "---无有效上线");
                        continue;
                    }
                    mchId = relation.getParentId() == null ? 0 : relation.getParentId();
                    divisionType = mchId > 0 ? 2: 3;
                    mchId = mchId == 0 ? relation.getCompanyId() : mchId;
                }else if (type == 3){
                    divisionType=1;
                }
                log.info("分账----payOrderAccept----mchId===="+mchId+"----divisionType==="+divisionType);
                if (type != 3 && mchId  == 0){
                    continue;
                }
                BigDecimal divisionAmount ;
                if (num.equals(baseCommissionRatios.size())){
                    divisionAmount=otherDivisionAmount.subtract(amount);
                }else {
                    divisionAmount=otherDivisionAmount.multiply(commissionRatio.getExtract()).divide(new BigDecimal(100)).setScale(2,   BigDecimal.ROUND_HALF_UP);
                }
                BaseOrderAcceptDetailed acceptDetailed=new BaseOrderAcceptDetailed();
                BeanUtils.copyProperties(orderWaterDTO,acceptDetailed);
                acceptDetailed.setMchId(mchId);
                acceptDetailed.setOrderAmount(orderAmount);
                acceptDetailed.setDivisionAmount(divisionAmount);
                acceptDetailed.setExtract(commissionRatio.getExtract());
                acceptDetailed.setDivisionType(divisionType);
                acceptDetailed.setAddTime(System.currentTimeMillis());
                acceptDetailed.setStatus(0);
                insertSelective(acceptDetailed);
                amount=amount.add(divisionAmount);
                orderWaterDTO.setAcceptId(acceptDetailed.getId());
                sellingWaterBiz.payOrderWater(orderWaterDTO);
            }
        }

        //店铺分账
        BaseOrderAcceptDetailed acceptDetailed=new BaseOrderAcceptDetailed();
        BeanUtils.copyProperties(orderWaterDTO,acceptDetailed);
        acceptDetailed.setMchId(companyId);
        acceptDetailed.setOrderAmount(orderAmount);
        acceptDetailed.setDivisionAmount(companyDivisionAmount);
        acceptDetailed.setDivisionType(5);
        acceptDetailed.setAddTime(System.currentTimeMillis());
        acceptDetailed.setStatus(0);
        insertSelective(acceptDetailed);


    }

    public void payOrderFAccept(OrderWaterDTO orderWaterDTO) {
        Integer orderId = orderWaterDTO.getOrderId() == null ? 0 : orderWaterDTO.getOrderId();
        List<OrderGoodsDTO> goodsDTOList = orderWaterDTO.getGoodsDTOList();
        if (goodsDTOList.size() > 0){
            BigDecimal goodsPries = goodsDTOList.stream().map(OrderGoodsDTO::getPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
            BaseOrderAcceptDetailed acceptDetailed=new BaseOrderAcceptDetailed();
            acceptDetailed.setOrderId(orderId);
            acceptDetailed.setStatus(1);
            List<BaseOrderAcceptDetailed> acceptDetaileds = selectList(acceptDetailed);
            if (acceptDetaileds.size() > 0){
                BigDecimal orderAmount = acceptDetaileds.get(0).getOrderAmount();
                if (orderAmount.compareTo(goodsPries) > 0){
                    orderAmount=orderAmount.subtract(goodsPries);
                    BigDecimal amount=BigDecimal.ZERO;
                    for (BaseOrderAcceptDetailed acceptDetailed1:acceptDetaileds){
                        Integer zAcceptId = acceptDetailed1.getId();
                        acceptDetailed1.setType(2);
                        acceptDetailed1.setId(null);
                        acceptDetailed1.setOrderAmount(orderAmount);
                        if (acceptDetailed1.getDivisionType() == 5 ){
                            if (orderAmount.compareTo(amount) > 0){
                                BigDecimal divisionAmount=orderAmount.subtract(amount).setScale(2,   BigDecimal.ROUND_HALF_UP);
                                acceptDetailed1.setDivisionAmount(divisionAmount);
                                insertSelective(acceptDetailed1);
                            }
                        }else {
                            BigDecimal divisionAmount=orderAmount.multiply(acceptDetailed1.getExtract()).divide(new BigDecimal(100)).setScale(2,   BigDecimal.ROUND_HALF_UP);
                            acceptDetailed1.setDivisionAmount(divisionAmount);
                            insertSelective(acceptDetailed1);
                            amount=amount.add(divisionAmount);
                            orderWaterDTO.setAcceptId(acceptDetailed1.getId());
                            orderWaterDTO.setZAcceptId(zAcceptId);
                            orderWaterDTO.setOrderAmount(orderAmount);
                            sellingWaterBiz.finishOrderFWater(orderWaterDTO);
                        }
                    }
                }
            }
        }


    }

    //订单完成计算用户拥金
    public void finishOrderAccept(OrderWaterDTO orderWaterDTO) {
        //订单id
        Integer orderId = orderWaterDTO.getOrderId() == null ? 0 : orderWaterDTO.getOrderId();
        log.info("订单完成计算用户拥金----finishOrderWater----orderId====" + orderId);
        if (orderId == 0) {
            return;
        }
        List<BaseOrderAcceptDetailed> list = getAcceptList(orderId);
        BigDecimal amount =BigDecimal.ZERO;
        if (list.size() > 0) {
            for (BaseOrderAcceptDetailed acceptDetailed : list) {
                Integer id = acceptDetailed.getId();
                Integer  divisionType = acceptDetailed.getDivisionType();
                acceptDetailed.setStatus(1);
                acceptDetailed.setStatusTime(System.currentTimeMillis());
                updateSelectiveById(acceptDetailed);
                orderWaterDTO.setAcceptId(id);
                BigDecimal commison=sellingWaterBiz.finishOrderWater(orderWaterDTO);
                log.info("分账----finishOrderAccept----id====" + id + "---commison==" + commison + "----divisionType===" + divisionType);
                amount = amount.add(commison);
            }
            Integer orderType = 0;
            List<OrderGoodsDTO> goodsDTOList = orderWaterDTO.getGoodsDTOList();
            if (goodsDTOList.size() > 0){
                OrderGoodsDTO orderGoodsDTO=goodsDTOList.get(0);
                orderType=orderGoodsDTO.getType() == null ? 0 : orderGoodsDTO.getType();
            }
            BigDecimal unbooked = amount;
            log.info("订单完成计算用户拥金----finishOrderWater----orderId====" + orderId + "---amount==" + amount + "---unbooked==" + unbooked);
            if (orderType == 1) {
                payOrderFAccept(orderWaterDTO);
            }
            log.info("订单完成计算用户拥金----finishOrderWater--------orderId===" + orderId + "----amount====" + amount + "--orderType===" + orderType);
        }


    }

    //订单退款
    public void refundOrderAccept(OrderWaterDTO orderWaterDTO) {
        Integer orderId = orderWaterDTO.getOrderId() == null ? 0 :orderWaterDTO.getOrderId();
        log.info("分账----refundOrderAccept----orderId====" + orderId);
        if (orderId == 0) {
            return;
        }
        List<BaseOrderAcceptDetailed> list = getAcceptList(orderId);
        if (list.size() > 0) {
            for (BaseOrderAcceptDetailed acceptDetailed : list) {
                acceptDetailed.setStatus(1);
                acceptDetailed.setStatusTime(System.currentTimeMillis());
                updateSelectiveById(acceptDetailed);
                acceptDetailed.setId(null);
                acceptDetailed.setType(2);
                insertSelective(acceptDetailed);
            }
            sellingWaterBiz.refundOrderWater(orderWaterDTO);
        }
    }

    //获取拥金列表
    public List<BaseOrderAcceptDetailed> getAcceptList(Integer orderId) {
        Example example = new Example(BaseOrderAcceptDetailed.class);
        example.createCriteria().andEqualTo("orderId", orderId).andEqualTo("type", 1).andEqualTo("status", 0);
        return mapper.selectByExample(example);

    }

}