package com.xxfc.platform.order.biz;

import com.alibaba.fastjson.JSON;
import com.github.wxiaoqi.security.common.exception.BaseException;
import com.github.wxiaoqi.security.common.util.process.ResultCode;;
import com.xxfc.platform.order.contant.enumerate.DeductionTypeEnum;
import com.xxfc.platform.order.contant.enumerate.OrderStatusEnum;
import com.xxfc.platform.order.entity.*;
import com.xxfc.platform.order.pojo.account.OrderAccountDeduction;
import com.xxfc.platform.order.pojo.account.OrderAccountDetail;
import com.xxfc.platform.order.pojo.dto.OrderDetailDTO;
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.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;


@Service
@Slf4j
public class OrderDetailBiz{


    @Autowired
    BaseOrderBiz orderBiz;

    @Autowired
    OrderRentVehicleBiz orderRentVehicleBiz;


    @Autowired
    OrderItemBiz orderItemBiz;

    @Autowired
    CompanyWalletBiz  companyWalletBiz;

    @Autowired
    OrderAccountBiz orderAccountBiz;





    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    //type1-支付;2-退款；3-完成
    public OrderDetailDTO getOrderDetail(String orderNo,Integer type){
        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 ||(type == 1 && !baseOrder.getStatus() .equals(OrderStatusEnum.ORDER_TOSTART.getCode()))  ||
                ( (type == 2 || type == 3) && !(baseOrder.getStatus().equals(OrderStatusEnum.ORDER_FINISH.getCode()) || baseOrder.getStatus().equals(OrderStatusEnum.ORDER_CANCEL.getCode()) )  )){
            throw  new BaseException("订单不存在或状态不是已完成",ResultCode.FAILED_CODE);
        }
        BigDecimal goodsAmount=baseOrder.getGoodsAmount().subtract(baseOrder.getCouponAmount());
        List<OrderRentVehicleDetail> orderRentVehicleDetails = orderRentVehicleBiz.listByOrderId(baseOrder.getId());
        if (orderRentVehicleDetails == null || orderRentVehicleDetails.size() == 0){
            throw  new BaseException("订单详情不存在",ResultCode.FAILED_CODE);
        }
        List<Integer> types=new ArrayList<>();
        if (type == 2){
            types.add(201);
            types.add(202);
            types.add(203);
        }else if (type == 3) {
            types.add(204);
        }
        OrderAccountDetail accountDetail = null;
        if (types.size() > 0){
             accountDetail = getAccountDetail(types, baseOrder.getId());
            if (accountDetail == null ){
                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));

        Integer insureStatus = baseOrder.getInsureStatus() == null ? 0 : baseOrder.getInsureStatus();

        BigDecimal insureAmount = BigDecimal.ZERO;
        if ((insureStatus == 1 && baseOrder.getStatus() .equals(OrderStatusEnum.ORDER_TOSTART.getCode())) ||insureStatus == 2 )
            insureAmount = orderItems.stream().filter(x->x.getType()==104).map(OrderItem::getRealAmount).reduce(BigDecimal.ZERO, (x, y) -> x.add(y));

        goodsAmount = goodsAmount.subtract(insureAmount);
        OrderRentVehicleDetail vehicleDetail=orderRentVehicleDetails.get(0);
        //获取营收明细dto
        OrderDetailDTO orderDetailDTO = new OrderDetailDTO();
        orderDetailDTO.setRentVehicleDetail(vehicleDetail);
        orderDetailDTO.setDamageSafeAmount(damageSafeAmount);
        orderDetailDTO.setGoodsAmount(goodsAmount);
        orderDetailDTO.setOrderType(baseOrder.getType());
        orderDetailDTO.setOrderId(baseOrder.getId());
        orderDetailDTO.setUserId(baseOrder.getUserId());
        orderDetailDTO.setOrderNo(baseOrder.getNo());
        orderDetailDTO.setInsureAmount(insureAmount);
        orderDetailDTO.setGoodsDepositType(vehicleDetail.getGoodsDepositType());
        if (accountDetail !=  null){
            List<OrderAccountDeduction> deductions = accountDetail.getDeductions();
            if (CollectionUtils.isNotEmpty(deductions)){
                setDeductionDetail(deductions,orderDetailDTO);
            }
        }
        return  orderDetailDTO;
    }


    public OrderAccountDetail getAccountDetail(List<Integer> types,Integer orderId) {
            Example example = new Example(OrderAccount.class);
            example.createCriteria().andEqualTo("orderId", orderId).andIn("accountType", types);
            List<OrderAccount> orderAccounts = orderAccountBiz.selectByExample(example);
            if (orderAccounts.size() > 0){
                OrderAccount orderAccount = orderAccounts.get(0);
                return  org.springframework.util.StringUtils.hasText(orderAccount.getAccountDetail()) ? JSON.parseObject(orderAccount.getAccountDetail(), OrderAccountDetail.class) : null;
            }

            return null;
    }


    public  void  setDeductionDetail(List<OrderAccountDeduction> deductions, OrderDetailDTO orderDetailDTO){
        Integer orderStatus=0;
        for (OrderAccountDeduction orderAccountDeduction:deductions){
             Integer type=orderAccountDeduction.getType() == null ? 0 : orderAccountDeduction.getType();
             BigDecimal amount=orderAccountDeduction.getAmount() == null ?BigDecimal.ZERO : orderAccountDeduction.getAmount();
             if (Objects.equals(DeductionTypeEnum.VIOLATE_CANCEL.getCode(),type)){
                 orderStatus=OrderDetailDTO.CANEL;
                 orderDetailDTO.setViolateAmount(amount);
             }else {
                 if (Objects.equals(DeductionTypeEnum.VIOLATE_ADVANCE.getCode(),type)){
                     orderStatus=OrderDetailDTO.ADVANCE;
                     orderDetailDTO.setViolateAmount(amount);
                 }else if (Objects.equals(DeductionTypeEnum.VIOLATE_DELAY.getCode(),type)){
                     orderStatus=OrderDetailDTO.DELAY;
                     orderDetailDTO.setViolateAmount(amount);
                 } else if (Objects.equals(DeductionTypeEnum.VIOLATE_CHANGE_C.getCode(),type)){
                     orderDetailDTO.setChageAmount(amount);
                 }else if (Objects.equals(DeductionTypeEnum.CONSUME.getCode(),type)){
                     orderDetailDTO.setOrderAmount(amount);
                 }else if (Objects.equals(DeductionTypeEnum.DAMAGES.getCode(),type)){
                     orderDetailDTO.setLossSpecifiedAmount(amount);
                 }else if (Objects.equals(DeductionTypeEnum.VIOLATE_TRAFFIC_DEDUCT.getCode(),type)){
                     orderDetailDTO.setBreakRulesRegulation(amount);
                 }else if (Objects.equals(DeductionTypeEnum.OTHER_DELAY_SAFE.getCode(),type)){
                     orderDetailDTO.setDamageSafeAmount2(amount);
                 }
             }
        }
        orderDetailDTO.setOrderStatus(orderStatus);

    }




}
