package com.xxfc.platform.order.service;

import cn.hutool.core.bean.BeanUtil;
import com.github.wxiaoqi.security.admin.feign.rest.UserRestInterface;
import com.github.wxiaoqi.security.auth.client.config.UserAuthConfig;
import com.github.wxiaoqi.security.common.exception.BaseException;
import com.github.wxiaoqi.security.common.util.process.ResultCode;
import com.xxfc.platform.activity.feign.ActivityFeign;
import com.xxfc.platform.order.biz.*;
import com.xxfc.platform.order.contant.enumerate.OrderStatusEnum;
import com.xxfc.platform.order.contant.enumerate.OrderTypeEnum;
import com.xxfc.platform.order.entity.BaseOrder;
import com.xxfc.platform.order.pojo.dto.ReceiveRefundDTO;
import com.xxfc.platform.order.pojo.order.PulishReceiveBO;
import com.xxfc.platform.order.pojo.price.OrderPriceVO;
import com.xxfc.platform.universal.constant.DictionaryKey;
import com.xxfc.platform.universal.feign.ThirdFeign;
import com.xxfc.platform.vehicle.feign.VehicleFeign;
import com.xxfc.platform.vehicle.pojo.dto.VehiclePublishReceiveDTO;
import com.xxfc.platform.vehicle.pojo.vo.VehiclePublishReceiveVo;
import lombok.extern.log4j.Log4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;
import java.util.*;

import static com.github.wxiaoqi.security.common.constant.CommonConstants.SYS_FALSE;
import static com.github.wxiaoqi.security.common.constant.CommonConstants.SYS_TRUE;
import static com.xxfc.platform.universal.constant.DictionaryKey.APP_ORDER;

@Service
@Log4j
public class OrderPulishReceiveService extends AbstractOrderHandle<OrderPulishReceiveDetailBiz, PulishReceiveBO> implements UserRestInterface {


    @Autowired
    VehicleFeign vehicleFeign;

    @Autowired
    ThirdFeign thirdFeign;

    @Autowired
    OrderAccountBiz orderAccountBiz;


    @Autowired
    BaseOrderBiz baseOrderBiz;


    private static Integer IS_CHILD = 1;
    private static Integer LEVEL_DEFAULT = 0;
    private static Integer NUMBER_ZERO = 0;
    private static Long autoCancelTime;

    @Autowired
    OrderCostDetailBiz orderCostDetailBiz;

    @Autowired
    OrderTemplateBiz orderTemplateBiz;

    @Autowired
    protected UserAuthConfig userAuthConfig;

    @Autowired
    ActivityFeign activityFeign;

    @Autowired
    public HttpServletRequest request;

    private SimpleDateFormat simleFormatter = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");

    private  DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("YYYYMMddHHmmss");

    @PostConstruct
    public void init() {
        this.channel = null;
        this.orderTypeEnum = OrderTypeEnum.PUBLISH;
    }


    @Override
    public void initDetail(PulishReceiveBO bo) {
        super.initDetail(bo);
        initDictionary();
    }

    public void initDictionary() {
        dictionaryMap = thirdFeign.dictionaryGetAll4Map().getData();
        this.autoCancelTime = Long.valueOf(dictionaryMap.get(APP_ORDER + "_" + DictionaryKey.ACT_MEMBER).getDetail());
    }



    @Override
    public void handleDetail(PulishReceiveBO bo) {
        //设置订单状态为3
        bo.getOrder().setStatus(OrderStatusEnum.ORDER_UNPAY.getCode());
        List<VehiclePublishReceiveVo> receiveVos = bo.getReceiveVos();
        if (receiveVos.size() > 0 ){
            VehiclePublishReceiveVo receiveVo = receiveVos.get(0);
            //设置订单图片
            bo.getOrder().setPicture(receiveVo.getCover());
            //设置订单名称
            bo.getOrder().setName(receiveVo.getName());
        }


        super.handleDetail(bo);

        //发送定时取消订单(30分钟)
        rabbitProduct.sendDelayMessage(bo.getOrder(), autoCancelTime);
    }

    @Override
    public void handleCalculate(PulishReceiveBO bo) {
        OrderPriceVO tpv = calculatePrice(bo);
        BeanUtil.copyProperties(tpv, bo.getOrder());
        BeanUtil.copyProperties(tpv, bo);
    }

    @Override
    public OrderPriceVO calculatePrice(PulishReceiveBO detail) {
        BigDecimal orderAmount = BigDecimal.ZERO;
        BigDecimal goodsAmount = BigDecimal.ZERO;
        BigDecimal realAmount = BigDecimal.ZERO;
        BigDecimal couponAmount = BigDecimal.ZERO;

        //设置Item
       /* OrderItem memberOrderItem = orderItemBiz.initOrderItem(detail.getBaseUserMemberLevel().getPrice(), 1, detail.getBaseUserMemberLevel().getName(), detail.getBaseUserMemberLevel().getId() + "", ItemTypeEnum.MEMBER);

        detail.setItems(new ArrayList<OrderItem>());
        detail.getItems().add(memberOrderItem);*/
        List<VehiclePublishReceiveVo> receiveVos = detail.getReceiveVos();
        BigDecimal receiveAmount = BigDecimal.ZERO;
        if (receiveVos.size() > 0 ) {
            if (detail.getType().equals(1)){
                receiveAmount = receiveVos.parallelStream().filter(oadTemp ->
                        (Integer.valueOf(VehiclePublishReceiveDTO.ADD).equals(oadTemp.getStatus()))
                ).map(VehiclePublishReceiveVo::getReceiveAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
            }else {
                receiveAmount = receiveVos.parallelStream().filter(oadTemp ->
                        (Integer.valueOf(VehiclePublishReceiveDTO.PAY).equals(oadTemp.getStatus()))
                ).map(VehiclePublishReceiveVo::getPublishAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
            }
        }

        //商品价格
        goodsAmount = goodsAmount.add(receiveAmount);

      /*  //vehicleAmount 优惠券处理
        if (null != detail.getTickerNo() && detail.getTickerNo().size() > 0) {
            couponAmount = activityFeign.use(detail.getOrder().getUserId(), detail.getTickerNo(), detail.getOrder().getNo(), channel, goodsAmount, ActivityFeign.TYPE_NO_USE);
            if (couponAmount.compareTo(BigDecimal.ZERO) > 0) {
                detail.getOrder().setCouponTickerNos(detail.getTickerNo().stream().collect(Collectors.joining(",")));
                detail.getOrder().setHasDiscount(SYS_TRUE);
                memberOrderItem.handleCouponAmount(couponAmount);
            }
        }*/

        //订单总价格
        orderAmount = orderAmount.add(goodsAmount);
        //真实价格
        realAmount = realAmount.add(orderAmount).subtract(couponAmount);

        //生成订单明细
        OrderPriceVO opv = new OrderPriceVO();
        opv.setOrderAmount(orderAmount);
        opv.setGoodsAmount(goodsAmount);
        opv.setRealAmount(realAmount);
        opv.setCouponAmount(couponAmount);

        return opv;
    }



    public  void  refund(ReceiveRefundDTO receiveRefundDTO){
        BaseOrder baseOrder = baseOrderBiz.selectOne(new BaseOrder() {{
            setNo(receiveRefundDTO.getOrderNo());
        }});
        if (baseOrder == null || !baseOrder.getHasPay().equals(SYS_TRUE)){
             throw  new BaseException("该订单无法退款", ResultCode.FAILED_CODE);
        }
        String refundDesc = receiveRefundDTO.getRefundDesc();
        BigDecimal  realAmount = baseOrder.getRealAmount();
        BigDecimal deductAmount = realAmount.subtract(receiveRefundDTO.getRefundAmount());
        orderAccountBiz.publishRefundProcess(baseOrder, refundDesc, baseOrder.getRealAmount(), deductAmount);
    }



}
