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 cn.hutool.extra.template.Template;
import cn.hutool.extra.template.TemplateConfig;
import cn.hutool.extra.template.TemplateEngine;
import cn.hutool.extra.template.TemplateUtil;
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.OrderRentVehicleBiz;
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.OrderCostDetail;
import com.xxfc.platform.order.entity.OrderTemplate;
import com.xxfc.platform.order.pojo.order.RentVehicleBO;
import com.xxfc.platform.order.pojo.order.TourBO;
import com.xxfc.platform.order.pojo.price.RentVehiclePriceVO;
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.entity.VehicleModel;
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;

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

    @Autowired
    TourFeign tourFeign;

    @Autowired
    VehicleFeign vehicleFeign;


    private static Integer IS_CHILD = 1;

//    private static BigDecimal DRIVER_PRICE = new BigDecimal("600.00");
//    private static BigDecimal DAMAGE_SAFE = new BigDecimal("100.00"); //车损免赔
    private static Integer LEVEL_DEFAULT = 0;
    private static Integer NUMBER_ZERO = 0;
//    private static BigDecimal DEPOSIT = new BigDecimal("20000.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());

        super.handleDetail(bo);
    }

    @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;

        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();

            //总价
        tourAmount = tourAmount.add(tourSpePriceVo.getTotalPrice()).add(tourSpePriceVo.getChildPrice());

            //商品价格
        goodsAmount = goodsAmount.add(tourAmount);
            //总价格
        orderAmount = orderAmount.add(goodsAmount);
            //真实价格
        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());

        //设置收费明细
        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}");
        }

        String str = childrenStr.toString();
        if(str.length() > 0) {
            str = str.substring(1, str.length());
        }
        return str;
    }

    /**
     * 计算费用明细
     * @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);
    }
}
