package com.xxfc.platform.order.biz;



import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
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.order.contant.enumerate.CompanyWalletITypeEnum;
import com.xxfc.platform.order.contant.enumerate.CompanyWalletSourceEnum;
import com.xxfc.platform.order.contant.enumerate.OrderStatusEnum;
import com.xxfc.platform.order.entity.*;
import com.xxfc.platform.order.mapper.CompanyWalletDetailMapper;
import com.xxfc.platform.order.pojo.dto.CompanyWalletDetailDTO;
import com.xxfc.platform.order.pojo.dto.WalletDetailDTO;
import com.xxfc.platform.order.pojo.vo.CompanyWalletDetailVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
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 java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;


@Service
@Slf4j
public class CompanyWalletDetailBiz extends BaseBiz<CompanyWalletDetailMapper, CompanyWalletDetail>{


    @Autowired
    BaseOrderBiz orderBiz;

    @Autowired
    OrderRentVehicleBiz orderRentVehicleBiz;


    @Autowired
    OrderItemBiz orderItemBiz;

    @Autowired
    CompanyWalletBiz  companyWalletBiz;






    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void addOrUpd(CompanyWalletDetail companyWalletDetail){
        String orderNo=companyWalletDetail.getCono();
        if (StringUtils.isBlank(orderNo)){
          throw  new BaseException("订单号不存在",ResultCode.FAILED_CODE);
        }
        log.info("---orderNo==="+orderNo);

        //获取订单相关信息
        BaseOrder baseOrder=new BaseOrder();
        baseOrder.setNo(orderNo);
        baseOrder=orderBiz.selectOne(baseOrder);
        if (baseOrder == null || baseOrder.getStatus()  < OrderStatusEnum.ORDER_FINISH.getCode() || StringUtils.isBlank(baseOrder.getRevenueJson())){
            throw  new BaseException("订单不存在或状态不是已完成",ResultCode.FAILED_CODE);
        }
        List<OrderRentVehicleDetail> orderRentVehicleDetails = orderRentVehicleBiz.listByOrderId(baseOrder.getId());
        if (orderRentVehicleDetails == null || orderRentVehicleDetails.size() == 0){
            throw  new BaseException("订单详情不存在",ResultCode.FAILED_CODE);
        }
        OrderItem orderItem=new OrderItem();
        orderItem.setOrderId(baseOrder.getId());
        List<OrderItem> orderItems = orderItemBiz.selectList(orderItem);
        BigDecimal damageSafeAmount = orderItems.stream().filter(x->x.getType()==102).map(OrderItem::getRealAmount).reduce(BigDecimal.ZERO, (x, y) -> x.add(y));
        OrderRentVehicleDetail vehicleDetail=orderRentVehicleDetails.get(0);

        //获取营收明细dto
        CompanyWalletDetailDTO walletDetailDTO=JSONUtil.toBean(baseOrder.getRevenueJson(), CompanyWalletDetailDTO.class);
        walletDetailDTO.setDamageSafeAmount(damageSafeAmount);
        walletDetailDTO.setOrderAmount(baseOrder.getRealAmount() );
        walletDetailDTO.setDeposit(vehicleDetail.getDeposit());
        walletDetailDTO.setViolateAmount(baseOrder.getViolateAmount());
        walletDetailDTO.setBreakRulesRegulation(vehicleDetail.getViolateTrafficAmount());
        walletDetailDTO.setLossSpecifiedAmount(baseOrder.getViolateAmount());

        //获取门店钱包信息
        CompanyWallet endCompany=companyWalletBiz.selectById(vehicleDetail.getActualEndCompanyId());
        BigDecimal endCompanyAmount=BigDecimal.ZERO;
        if (endCompany != null){
            endCompanyAmount=endCompany.getBalance();
        }
        CompanyWallet vehicleCompany=companyWalletBiz.selectById(vehicleDetail.getVehicleCompanyId());
        BigDecimal vehicleCompanyAmount=BigDecimal.ZERO;
        if (vehicleCompany != null){
            vehicleCompanyAmount=vehicleCompany.getBalance();
        }
        CompanyWallet startCompany=companyWalletBiz.selectById(vehicleDetail.getStartCompanyId());
        BigDecimal startCompanyAmount=BigDecimal.ZERO;
        if (startCompany != null){
            startCompanyAmount=startCompany.getBalance();
        }
        CompanyWallet platformCompany=companyWalletBiz.selectById(walletDetailDTO.getPlatformCompanyId());
        BigDecimal platformCompanyAmount=BigDecimal.ZERO;
        if (platformCompany != null){
            platformCompanyAmount=platformCompany.getBalance();
        }

        //插入营收明细
        if (walletDetailDTO.getClosedVehicleAmout() != null && walletDetailDTO.getClosedVehicleAmout().compareTo(BigDecimal.ZERO)>0){
            endCompanyAmount=endCompanyAmount.add(walletDetailDTO.getClosedVehicleAmout());
            companyWalletDetail.setAmount(walletDetailDTO.getClosedVehicleAmout());
            companyWalletDetail.setCompanyId(vehicleDetail.getActualEndCompanyId());
            companyWalletDetail.setBranchId(vehicleDetail.getActualEndBranchId());
            companyWalletDetail.setSAmount(endCompanyAmount);
            companyWalletDetail.setSource(CompanyWalletSourceEnum.CLOSED_VEHICLE.getCode());
            companyWalletDetail.setItype(CompanyWalletITypeEnum.VEHICLE.getCode());
            companyWalletDetail.setId(null);
            insertSelective(companyWalletDetail);
        }if (walletDetailDTO.getDamageSafeAmount() != null && walletDetailDTO.getDamageSafeAmount().compareTo(BigDecimal.ZERO)>0){
            BigDecimal amount=mapper.sumAmountByNo(orderNo,vehicleDetail.getVehicleCompanyId());
            vehicleCompanyAmount=vehicleCompanyAmount.add(walletDetailDTO.getDamageSafeAmount());
            companyWalletDetail.setAmount(walletDetailDTO.getDamageSafeAmount());
            companyWalletDetail.setCompanyId(vehicleDetail.getVehicleCompanyId());
            companyWalletDetail.setBranchId(vehicleDetail.getVehicleBranchId());
            companyWalletDetail.setSAmount(walletDetailDTO.getDamageSafeAmount().add(amount));
            companyWalletDetail.setSource(CompanyWalletSourceEnum.DAMAGE_SAFE.getCode());
            companyWalletDetail.setItype(CompanyWalletITypeEnum.VEHICLE.getCode());
            companyWalletDetail.setId(null);
            insertSelective(companyWalletDetail);
        }if (walletDetailDTO.getRentVehicleAmount() != null && walletDetailDTO.getRentVehicleAmount().compareTo(BigDecimal.ZERO)>0){
            BigDecimal amount=mapper.sumAmountByNo(orderNo,vehicleDetail.getVehicleCompanyId());
            vehicleCompanyAmount=vehicleCompanyAmount.add(walletDetailDTO.getRentVehicleAmount());
            companyWalletDetail.setAmount(walletDetailDTO.getRentVehicleAmount());
            companyWalletDetail.setCompanyId(vehicleDetail.getVehicleCompanyId());
            companyWalletDetail.setBranchId(vehicleDetail.getVehicleBranchId());
            companyWalletDetail.setSAmount(walletDetailDTO.getRentVehicleAmount().add(amount));
            companyWalletDetail.setSource(CompanyWalletSourceEnum.RENT_VEHICLE.getCode());
            companyWalletDetail.setItype(CompanyWalletITypeEnum.VEHICLE.getCode());
            companyWalletDetail.setId(null);
            insertSelective(companyWalletDetail);
        }if (walletDetailDTO.getOrderAmount() != null && walletDetailDTO.getOrderAmount().compareTo(BigDecimal.ZERO)>0){
            BigDecimal amount=mapper.sumAmountByNo(orderNo,vehicleDetail.getStartCompanyId());
            startCompanyAmount=startCompanyAmount.add(walletDetailDTO.getOrderAmount());
            companyWalletDetail.setAmount(walletDetailDTO.getOrderAmount());
            companyWalletDetail.setCompanyId(vehicleDetail.getStartCompanyId());
            companyWalletDetail.setBranchId(vehicleDetail.getStartBranchId());
            companyWalletDetail.setSAmount(walletDetailDTO.getOrderAmount().add(amount));
            companyWalletDetail.setSource(CompanyWalletSourceEnum.ORDER_COMSSION.getCode());
            companyWalletDetail.setItype(CompanyWalletITypeEnum.VEHICLE.getCode());
            companyWalletDetail.setId(null);
            insertSelective(companyWalletDetail);
        }if (walletDetailDTO.getPlatformComssion() != null && walletDetailDTO.getPlatformComssion().compareTo(BigDecimal.ZERO)>0){
            BigDecimal amount=mapper.sumAmountByNo(orderNo,walletDetailDTO.getPlatformCompanyId());
            platformCompanyAmount=platformCompanyAmount.add(walletDetailDTO.getPlatformComssion());
            companyWalletDetail.setAmount(walletDetailDTO.getPlatformComssion());
            companyWalletDetail.setCompanyId(walletDetailDTO.getPlatformCompanyId());
            companyWalletDetail.setBranchId(walletDetailDTO.getPlatformBranchId());
            companyWalletDetail.setSAmount(walletDetailDTO.getPlatformComssion().add(amount));
            companyWalletDetail.setSource(CompanyWalletSourceEnum.PLATFORM_COMSSION.getCode());
            companyWalletDetail.setItype(CompanyWalletITypeEnum.PLATFORM.getCode());
            companyWalletDetail.setId(null);
            insertSelective(companyWalletDetail);
        }if (walletDetailDTO.getLossSpecifiedAmount() != null && walletDetailDTO.getLossSpecifiedAmount().compareTo(BigDecimal.ZERO)>0){
            BigDecimal amount=mapper.sumAmountByNo(orderNo,vehicleDetail.getVehicleCompanyId());
            vehicleCompanyAmount=vehicleCompanyAmount.add(walletDetailDTO.getLossSpecifiedAmount());
            companyWalletDetail.setAmount(walletDetailDTO.getLossSpecifiedAmount());
            companyWalletDetail.setCompanyId(vehicleDetail.getVehicleCompanyId());
            companyWalletDetail.setBranchId(vehicleDetail.getVehicleBranchId());
            companyWalletDetail.setSAmount(walletDetailDTO.getLossSpecifiedAmount().add(amount));
            companyWalletDetail.setSource(CompanyWalletSourceEnum.LOSS_SPECIFIED.getCode());
            companyWalletDetail.setItype(CompanyWalletITypeEnum.LOSS.getCode());
            companyWalletDetail.setId(null);
            insertSelective(companyWalletDetail);
        }if (walletDetailDTO.getBreakRulesRegulation() != null && walletDetailDTO.getBreakRulesRegulation().compareTo(BigDecimal.ZERO)>0){
            BigDecimal amount=mapper.sumAmountByNo(orderNo,vehicleDetail.getVehicleCompanyId());
            vehicleCompanyAmount=vehicleCompanyAmount.add(walletDetailDTO.getBreakRulesRegulation());
            companyWalletDetail.setAmount(walletDetailDTO.getBreakRulesRegulation());
            companyWalletDetail.setCompanyId(vehicleDetail.getVehicleCompanyId());
            companyWalletDetail.setBranchId(vehicleDetail.getVehicleBranchId());
            companyWalletDetail.setSAmount(walletDetailDTO.getBreakRulesRegulation().add(amount));
            companyWalletDetail.setSource(CompanyWalletSourceEnum.BREAK_RULES_REGULATION.getCode());
            companyWalletDetail.setItype(CompanyWalletITypeEnum.REGULATION.getCode());
            companyWalletDetail.setId(null);
            insertSelective(companyWalletDetail);
        }if (walletDetailDTO.getBreakRulesRegulation() != null && walletDetailDTO.getBreakRulesRegulation().compareTo(BigDecimal.ZERO)>0){
            BigDecimal amount=mapper.sumAmountByNo(orderNo,vehicleDetail.getVehicleCompanyId());
            vehicleCompanyAmount=vehicleCompanyAmount.add(walletDetailDTO.getViolateAmount());
            companyWalletDetail.setAmount(walletDetailDTO.getViolateAmount());
            companyWalletDetail.setCompanyId(vehicleDetail.getVehicleCompanyId());
            companyWalletDetail.setBranchId(vehicleDetail.getVehicleBranchId());
            companyWalletDetail.setSAmount(walletDetailDTO.getViolateAmount().add(amount));
            companyWalletDetail.setSource(CompanyWalletSourceEnum.VIOLATE_AMOUNT.getCode());
            companyWalletDetail.setItype(CompanyWalletITypeEnum.VIOLATE.getCode());
            companyWalletDetail.setId(null);
            insertSelective(companyWalletDetail);
        }

        //更新钱包
        Long time=System.currentTimeMillis();
       if (endCompany == null ){
           endCompany=new CompanyWallet();
           endCompany.setCompanyId(vehicleDetail.getActualEndCompanyId());
           endCompany.setBalance(endCompanyAmount);
           endCompany.setLastIntime(time);
           endCompany.setTotalAmount(endCompanyAmount);
           companyWalletBiz.insertSelective(endCompany);
       }else {
           endCompany.setTotalAmount(endCompany.getTotalAmount().add(endCompanyAmount));
           endCompany.setBalance(endCompany.getBalance().add(endCompanyAmount));
           endCompany.setLastIntime(time);
           companyWalletBiz.updCompanyWallet(endCompany);
       }
        vehicleCompany=companyWalletBiz.selectById(vehicleDetail.getVehicleCompanyId());
        if (vehicleCompany == null ){
            vehicleCompany=new CompanyWallet();
            vehicleCompany.setCompanyId(vehicleDetail.getVehicleCompanyId());
            vehicleCompany.setBalance(vehicleCompanyAmount);
            vehicleCompany.setLastIntime(time);
            vehicleCompany.setTotalAmount(vehicleCompanyAmount);
            companyWalletBiz.insertSelective(vehicleCompany);
        }else {
            vehicleCompany.setTotalAmount(vehicleCompany.getTotalAmount().add(vehicleCompanyAmount));
            vehicleCompany.setBalance(vehicleCompany.getBalance().add(vehicleCompanyAmount));
            vehicleCompany.setLastIntime(time);
            companyWalletBiz.updCompanyWallet(vehicleCompany);
        }
        startCompany=companyWalletBiz.selectById(vehicleDetail.getStartCompanyId());
        if (startCompany == null ){
            startCompany=new CompanyWallet();
            startCompany.setCompanyId(vehicleDetail.getStartCompanyId());
            startCompany.setBalance(startCompanyAmount);
            startCompany.setLastIntime(time);
            startCompany.setTotalAmount(startCompanyAmount);
            companyWalletBiz.insertSelective(startCompany);
        }else {
            startCompany.setTotalAmount(startCompany.getTotalAmount().add(startCompanyAmount));
            startCompany.setBalance(startCompany.getBalance().add(startCompanyAmount));
            startCompany.setLastIntime(time);
            companyWalletBiz.updCompanyWallet(startCompany);
        }
        platformCompany=companyWalletBiz.selectById(walletDetailDTO.getPlatformCompanyId());
        if (platformCompany == null ){
            platformCompany=new CompanyWallet();
            platformCompany.setCompanyId(walletDetailDTO.getPlatformCompanyId());
            platformCompany.setBalance(platformCompanyAmount);
            platformCompany.setLastIntime(time);
            platformCompany.setTotalAmount(platformCompanyAmount);
            companyWalletBiz.insertSelective(platformCompany);
        }else {
            platformCompany.setTotalAmount(platformCompany.getTotalAmount().add(platformCompanyAmount));
            platformCompany.setBalance(platformCompany.getBalance().add(platformCompanyAmount));
            platformCompany.setLastIntime(time);
            companyWalletBiz.updCompanyWallet(platformCompany);
        }
    }


    public PageDataVO<CompanyWalletDetailVo> selectList(WalletDetailDTO walletDetailDTO) {
        return PageDataVO.pageInfo(walletDetailDTO.getPage(), walletDetailDTO.getLimit(), () -> getList(walletDetailDTO));
    }

    public List<CompanyWalletDetailVo> getList(WalletDetailDTO walletDetailDTO){
        return  mapper.selectList(walletDetailDTO);
    }

    public JSONObject  getSumAmount(WalletDetailDTO walletDetailDTO){
        List<Integer> itypes=new ArrayList<>();
        itypes.add(1);
        walletDetailDTO.setItypes(itypes);
        BigDecimal amount = mapper.sumAmount(walletDetailDTO);
        JSONObject jsonObject=new JSONObject();
        jsonObject.put("orderAmount",amount);
        itypes=new ArrayList<>();
        itypes.add(2);
        itypes.add(3);
        itypes.add(4);
        walletDetailDTO.setItypes(itypes);
        amount = mapper.sumAmount(walletDetailDTO);
        jsonObject.put("otherAmount",amount);
        CompanyWallet companyWallet=companyWalletBiz.sumAmount(walletDetailDTO);
        if (companyWallet != null ){
            jsonObject.put("balance",companyWallet.getBalance());
            jsonObject.put("withdrawals",companyWallet.getWithdrawals());
        }

        return jsonObject;
    }




}
