package com.xxfc.platform.order.service;

import com.alibaba.fastjson.JSONArray;
import com.github.wxiaoqi.security.common.msg.ObjectRestResponse;
import com.xxfc.platform.order.biz.BaseOrderBiz;
import com.xxfc.platform.order.biz.OrderVehicleCrosstownBiz;
import com.xxfc.platform.order.biz.OrderViolationBiz;
import com.xxfc.platform.order.entity.OrderRentVehicleDetail;
import com.xxfc.platform.order.entity.OrderVehicleCrosstown;
import com.xxfc.platform.order.entity.OrderViolation;
import com.xxfc.platform.order.mapper.OrderRentVehicleDetailMapper;
import com.xxfc.platform.order.pojo.OrderViolateVo;
import com.xxfc.platform.order.pojo.order.OrderPageVO;
import com.xxfc.platform.universal.constant.DictionaryKey;
import com.xxfc.platform.universal.dto.VehicleViolateDto;
import com.xxfc.platform.universal.entity.Dictionary;
import com.xxfc.platform.universal.feign.ThirdFeign;
import com.xxfc.platform.vehicle.entity.Vehicle;
import com.xxfc.platform.vehicle.feign.VehicleFeign;
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.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName : OrderViolateService
 * @Description : 查询订单车辆违章
 * @Author : jiaoruizhen
 * @Date: 2020-11-19 11:23
 */
@Service
@Slf4j
public class OrderViolateService {

	@Autowired
	BaseOrderBiz baseOrderBiz;

	@Autowired
	OrderVehicleCrosstownBiz orderVehicleCrosstownBiz;

	@Autowired
	ThirdFeign thirdFeign;

	@Autowired
	OrderRentVehicleDetailMapper orderRentVehicleDetailMapper;

	@Autowired
	VehicleFeign vehicleFeign;

	@Autowired
	OrderViolationBiz orderViolationBiz;


	//查询所有符合条件的订单，已交车，未扣押金
	private List<OrderPageVO> getOrderList() {
		Map<String, Object> params = new HashMap<>();
		params.put("refundStatus", 2);
		params.put("status", 6);
		return baseOrderBiz.getRentVehicle(params);
	}

	//过滤时间，根据还车时间，符合几天后的订单执行查询违章操作
	private List<OrderRentVehicleDetail> getAllVehicleCrosstown() {
		List<OrderPageVO> orderPageVOList = getOrderList();
		List<OrderRentVehicleDetail> orderRentVehicleDetailList = new ArrayList<>();
		if (orderPageVOList != null && orderPageVOList.size() > 0) {
			List<OrderVehicleCrosstown> arrayList = new ArrayList<>();
			List<Integer> orderIdList = orderPageVOList.stream().map(OrderPageVO::getId).collect(Collectors.toList());
			List<Integer> time = getTimeList();
			if (time != null && time.size() > 0) {
				time.parallelStream().forEach(time1-> {
					List<OrderVehicleCrosstown> orderVehicleCrosstownList = orderVehicleCrosstownBiz.selectOrderList(orderIdList, 1, time1);
					if (orderVehicleCrosstownList != null && orderVehicleCrosstownList.size() > 0) {
						arrayList.addAll(orderVehicleCrosstownList);
					}
				});
			} else {
				List<OrderVehicleCrosstown> orderVehicleCrosstownList = orderVehicleCrosstownBiz.selectOrderList(orderIdList, 1, 0);
				if (orderVehicleCrosstownList != null && orderVehicleCrosstownList.size() > 0) {
					arrayList.addAll(orderVehicleCrosstownList);
				}
			}
			List<Integer> idList = arrayList.stream().map(OrderVehicleCrosstown::getOrderId).collect(Collectors.toList());
			if (CollectionUtils.isNotEmpty(idList)) {
				Example example = new Example(OrderRentVehicleDetail.class);
				example.createCriteria().andIn("orderId", idList);
				orderRentVehicleDetailList.addAll(orderRentVehicleDetailMapper.selectByExample(example));
			}
		}
		return orderRentVehicleDetailList;
	}

	//获取所有车辆信息
	private List<Vehicle> getAllVehicleInfo() {
		List<OrderRentVehicleDetail> orderRentVehicleDetailList = getAllVehicleCrosstown();
		if (CollectionUtils.isNotEmpty(orderRentVehicleDetailList)) {
			String idString = orderRentVehicleDetailList.stream().map(OrderRentVehicleDetail::getVehicleId).collect(Collectors.joining(","));
			ObjectRestResponse<List<Vehicle>> restResponse = vehicleFeign.getAllVehicleById(idString);
			return restResponse.getData();
		}
		return new ArrayList<>();
	}


	//获取查询时间列表
	private List<Integer> getTimeList() {
		Dictionary dictionary = thirdFeign.findDictionaryByTypeAndCode(DictionaryKey.VEHICLE, DictionaryKey.VEHICLE_VIOLATE_TIME);
		if (dictionary != null && StringUtils.isNotBlank(dictionary.getDetail())) {
			return JSONArray.parseArray(dictionary.getDetail(), Integer.class);
		}
		return new ArrayList<>();
	}

	//讲查询结果存入违章信息表中
	@Scheduled(cron = "0 0 1 * * ?")
	public void generateData() {
		List<Vehicle> vehicleList = getAllVehicleInfo();
		List<OrderRentVehicleDetail> orderRentVehicleDetailList = getAllVehicleCrosstown();
		List<OrderViolation> orderViolationList = new ArrayList<>();
		Map<String, List<OrderRentVehicleDetail>> orderRentVehicleMap = orderRentVehicleDetailList.stream().collect(Collectors.groupingBy(OrderRentVehicleDetail::getVehicleId));
		if (vehicleList != null && vehicleList.size() > 0) {
			vehicleList.parallelStream().forEach(vehicle -> {
				List<OrderRentVehicleDetail> orderRentVehicleDetail = orderRentVehicleMap.get(vehicle.getId());
				requestViolate(vehicle, orderRentVehicleDetail, orderViolationList);
			});
		}

		if (orderViolationList.size() > 0) {
			orderViolationBiz.batchSave(orderViolationList);
		}

	}


	private void requestViolate(Vehicle vehicle, List<OrderRentVehicleDetail> orderRentVehicleDetailList, List<OrderViolation> orderViolationList) {
		ObjectRestResponse response = thirdFeign.getVehicleViolate(new VehicleViolateDto(){{
			setNumberPlate(vehicle.getNumberPlate());
			setEngineNo(vehicle.getEngineNum());
			setClassNo(vehicle.getVin());
		}});
		if (response.isRel() && response.getData() != null) {
			List<OrderViolateVo>  list = JSONArray.parseArray(response.getData().toString(), OrderViolateVo.class);
			if (list != null) {
				Map<Integer, List<OrderViolateVo>> map = new HashMap<>();
					if (orderRentVehicleDetailList.size() > 0) {
							orderRentVehicleDetailList.parallelStream().forEach(orderRentVehicleDetail -> {
							List<OrderViolateVo> orderViolateVoList = map.get(orderRentVehicleDetail.getId());
							if (orderViolateVoList == null) {
								orderViolateVoList = new ArrayList<>();
							}

							List<OrderViolateVo> finalOrderViolateVoList = orderViolateVoList;
							list.parallelStream().forEach(orderViolateVo -> {
								if (orderViolateVo.getDate().getTime() >= orderRentVehicleDetail.getDeliveryTime() && orderViolateVo.getDate().getTime() <= orderRentVehicleDetail.getCollectTime()) {
									finalOrderViolateVoList.add(orderViolateVo);
								}
							});
							map.put(orderRentVehicleDetail.getId(), orderViolateVoList);
						});
					}
				for (Map.Entry<Integer, List<OrderViolateVo>> entry : map.entrySet()) {
					List<OrderViolateVo> orderViolateVoList = entry.getValue();

					OrderViolation orderViolation = new OrderViolation();
					orderViolation.setViolateJson(response.getData().toString());
					if(orderViolateVoList != null && orderViolateVoList.size() > 0) {
						Double amount = orderViolateVoList.stream().mapToDouble(e->Double.parseDouble(e.getMoney())).reduce(0, Double::sum);
						if (amount != null) {
							orderViolation.setPrice(new BigDecimal(amount));
						} else {
							orderViolation.setPrice(BigDecimal.ZERO);
						}

					} else {
						orderViolation.setPrice(BigDecimal.ZERO);
					}
					orderViolation.setDetailId(entry.getKey());
					orderViolationList.add(orderViolation);
				}
			}
		}
		log.error("违章查询失败: {}", response.getMessage());
	}
}
