package com.xxfc.platform.order.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.StrUtil;
import com.github.wxiaoqi.security.admin.feign.UserFeign;
import com.github.wxiaoqi.security.admin.feign.dto.AppUserDTO;
import com.github.wxiaoqi.security.auth.client.config.UserAuthConfig;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.xxfc.platform.order.biz.OrderCostDetailBiz;
import com.xxfc.platform.order.biz.OrderTemplateBiz;
import com.xxfc.platform.order.biz.OrderTourDetailBiz;
import com.xxfc.platform.order.contant.enumerate.OrderCostEnum;
import com.xxfc.platform.order.contant.enumerate.OrderStatusEnum;
import com.xxfc.platform.order.contant.enumerate.OrderTypeEnum;
import com.xxfc.platform.order.entity.OrderTemplate;
import com.xxfc.platform.order.pojo.order.TourBO;
import com.xxfc.platform.order.pojo.price.TourPriceVO;
import com.xxfc.platform.tour.dto.TourSpePriceDTO;
import com.xxfc.platform.tour.entity.TourGood;
import com.xxfc.platform.tour.entity.TourGoodVerification;
import com.xxfc.platform.tour.entity.TourUser;
import com.xxfc.platform.tour.feign.TourFeign;
import com.xxfc.platform.tour.vo.TourSpePriceVo;
import com.xxfc.platform.vehicle.entity.SysRegion;
import com.xxfc.platform.vehicle.feign.VehicleFeign;
import com.xxfc.platform.vehicle.pojo.CompanyDetail;
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.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

import static com.github.wxiaoqi.security.common.constant.CommonConstants.SYS_FALSE;
import static com.github.wxiaoqi.security.common.constant.CommonConstants.SYS_TRUE;

@Service
@Log4j
public class OrderTourService extends AbstractOrderHandle<OrderTourDetailBiz, TourBO> {

    @Autowired
    TourFeign tourFeign;

    @Autowired
    VehicleFeign vehicleFeign;


    private static Integer IS_CHILD = 1;

    private static Integer LEVEL_DEFAULT = 0;
    private static Integer NUMBER_ZERO = 0;
    private static BigDecimal INSURE_PRICE = new BigDecimal("5.00"); //保险

    @Autowired
    OrderCostDetailBiz orderCostDetailBiz;

    @Autowired
    OrderTemplateBiz orderTemplateBiz;

    @Autowired
    protected UserAuthConfig userAuthConfig;

    @Autowired
    UserFeign userFeign;

    @Autowired
    public HttpServletRequest request;

    @PostConstruct
    public void init(){
        this.orderTypeEnum = OrderTypeEnum.TOUR;
    }

    public AppUserDTO getUserInfo(){
        return  userFeign.userDetailByToken(userAuthConfig.getToken(request)).getData();
    }

    @Override
    public void initDetail(TourBO bo) {
        super.initDetail(bo);
        TourGood tourGood = tourFeign.usableGet(bo.getGoodId()).getData();
        bo.setTourGood(tourGood);
        bo.setAppUserDTO(getUserInfo());
    }

    @Override
    public void handleDetail(TourBO bo) {
        //设置订单状态为3
        bo.getOrder().setStatus(OrderStatusEnum.ORDER_UNPAY.getCode());
        //设置订单图片
        bo.getOrder().setPicture(bo.getTourGood().getCover());
        //设置订单名称
        bo.getOrder().setName(bo.getTourGood().getName());

        //设置城市
        CompanyDetail companyDetail = vehicleFeign.getCompanyDetail(bo.getStartCompanyId()).getData();
        SysRegion sysRegion = companyDetail.getSysRegions().get(1);
        bo.setStartCity(sysRegion.getId().intValue());
        bo.setStartCityName(sysRegion.getName());

        //设置verificationId 核销id
        bo.setVerificationId(tourFeign.entityList(BeanUtil.beanToMap(new TourGoodVerification(){{
            setSpeId(bo.getSpePriceId());
            setGoodId(bo.getGoodId());
            setSiteId(bo.getSiteId());
        }})).getData().get(0).getId());

        //扣減庫存
        tourFeign.stock(bo.getSpePriceId(), bo.getTotalNumber(), TourFeign.STOCK_SUBTRACT);

        super.handleDetail(bo);

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

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

    @Override
    public TourPriceVO calculatePrice(TourBO detail) {
        BigDecimal orderAmount = BigDecimal.ZERO;
        BigDecimal goodsAmount = BigDecimal.ZERO;
        BigDecimal tourAmount = BigDecimal.ZERO;
        BigDecimal realAmount = BigDecimal.ZERO;
        BigDecimal insureAmount = BigDecimal.ZERO;

        if(StrUtil.isNotBlank(detail.getTourUserIds())) {
            List<TourUser> users = new ArrayList<TourUser>();
            if(StrUtil.isNotBlank(detail.getTourUserIds())) {
                users = tourFeign.getTourUsers(detail.getTourUserIds()).getData();
            }

            List<TourUser> notChilds = users.parallelStream().filter(tourUser ->{
                return !IS_CHILD.equals(tourUser.getIsChild());
            }).collect(Collectors.toList());

            List<TourUser> childs = users.parallelStream().filter(tourUser ->{
                return IS_CHILD.equals(tourUser.getIsChild());
            }).collect(Collectors.toList());

            detail.setAdultNum(notChilds.size());
            detail.setChildNum(childs.size());
            detail.setTotalNumber(users.size());
        }else{
            detail.setTotalNumber(detail.getAdultNum() + detail.getChildNum());
        }

        //计算旅游价格
        ObjectRestResponse<TourSpePriceVo> objectRestResponse = tourFeign.refund(new TourSpePriceDTO(){{
            setChildNumber(detail.getChildNum());
            setNumber(detail.getAdultNum());
            setLevel(LEVEL_DEFAULT);
            setSpeId(detail.getSpePriceId());
            setUserId(detail.getAppUserDTO().getUserid());
        }});
        TourSpePriceVo tourSpePriceVo = objectRestResponse.getData();

        //需要保险
        if(SYS_TRUE.equals(detail.getHasInsure())) {
            //人数 * 天数 * 价格
            insureAmount = insureAmount.add(INSURE_PRICE.multiply(new BigDecimal(String.valueOf(detail.getTotalNumber() * detail.getTourGood().getNumber()))));
        }
            //总价
        tourAmount = tourAmount.add(tourSpePriceVo.getTotalPrice()).add(tourSpePriceVo.getChildPrice());
            //商品价格
        goodsAmount = goodsAmount.add(tourAmount);
            //总价格
        orderAmount = orderAmount.add(goodsAmount).add(insureAmount);
            //真实价格
        realAmount = realAmount.add(tourSpePriceVo.getRealPrice()).add(tourSpePriceVo.getRealChildPrice());

            //生成订单明细
        TourPriceVO tpv = BeanUtil.toBean(tourSpePriceVo, TourPriceVO.class);
        tpv.setOrderAmount(orderAmount);
        tpv.setGoodsAmount(goodsAmount);
        tpv.setRealAmount(realAmount);
        tpv.setNumber(detail.getAdultNum());
        tpv.setChildNumber(detail.getChildNum());
        tpv.setInsurePrice(INSURE_PRICE);
        tpv.setDayNum(detail.getTourGood().getNumber());
        tpv.setInsureAmount(insureAmount);
        tpv.setTotalNumber(detail.getTotalNumber());

        //设置收费明细
        costDetail(tpv, handlechildren(detail));
        return tpv;
    }

    private String handlechildren(TourBO detail) {
        StringBuffer childrenStr = new StringBuffer("");
        if(NUMBER_ZERO < detail.getAdultNum()) {
            childrenStr.append(",${tem_0201}");
        }
        if(NUMBER_ZERO < detail.getChildNum()) {
            childrenStr.append(",${tem_0202}");
        }
        if(SYS_TRUE.equals(detail.getHasInsure())) {
            childrenStr.append(",${tem_0203}");
        }

        if(childrenStr.length() > 0){
            childrenStr.deleteCharAt(0);
        }
        return childrenStr.toString();
    }

    /**
     * 计算费用明细
     * @param vo
     * @return
     */
    private void costDetail(TourPriceVO vo, String children) {
        OrderTemplate template = orderTemplateBiz.selectById(OrderCostEnum.RentVehicle.getCode());
        template.setTemplate(orderTemplateBiz.result(template.getTemplate(), new HashMap(){{
            put("children", children);
        }}));
        String result = orderTemplateBiz.result(template, Dict.parse(vo));
        vo.setCostDetail(result);
    }
}
