package com.prolog.rdc.tms.service.impl.intransit;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.google.common.collect.Lists;
import com.prolog.common.util.ToolKits;
import com.prolog.framework.core.exception.BizException;
import com.prolog.framework.core.restriction.Criteria;
import com.prolog.framework.core.restriction.Order;
import com.prolog.framework.core.restriction.Restriction;
import com.prolog.framework.core.restriction.Restrictions;
import com.prolog.rdc.tms.constant.DataDictionaryConstant;
import com.prolog.rdc.tms.dao.mapper.TmsVehicleGpsMapper;
import com.prolog.rdc.tms.model.dto.ShipbillHeaderPageDTO;
import com.prolog.rdc.tms.model.dto.intransit.DeviceGpsDTO;
import com.prolog.rdc.tms.model.dto.intransit.InTransitTrackDTO;
import com.prolog.rdc.tms.model.dto.intransit.LoadingAndShipBillHeaderDTO;
import com.prolog.rdc.tms.model.dto.intransit.LoadingBillHeaderPageDTO;
import com.prolog.rdc.tms.model.dto.intransit.TmsVehicleGpsDTO;
import com.prolog.rdc.tms.model.entity.TmsLoadingBillHeaderModel;
import com.prolog.rdc.tms.model.entity.TmsShipbillHeaderModel;
import com.prolog.rdc.tms.model.entity.TmsVehicleGpsModel;
import com.prolog.rdc.tms.model.vo.intransit.InTransitQueryVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author hongbo.pan
 * @date 2022/9/20
 */
@Service
public class InTransitServiceImpl extends AbstractInTransit {

    @Autowired
    private TmsVehicleGpsMapper tmsVehicleGpsMapper;

    /**
     * 车辆定位
     * @param vo
     * @return
     */
    @Override
    public TmsVehicleGpsDTO getPosition(InTransitQueryVO vo) {
        checkCarAndPhoneNumber(vo);
        Criteria crt = Criteria.forClass(TmsVehicleGpsModel.class);
        Restriction r1 = StrUtil.isBlank(vo.getCarNumber()) ? null : Restrictions.eq("vehiclePlateNumber", vo.getCarNumber());
        Restriction r2 = StrUtil.isBlank(vo.getMobilePhone()) ? null : Restrictions.eq("driverPhoneNumber", vo.getMobilePhone());
        crt.setRestriction(Restrictions.and(r1, r2));
        crt.setOrder(Order.newInstance().desc("updatetime", "createtime"));
        List<TmsVehicleGpsModel> tmsVehicleGpsModelList = tmsVehicleGpsMapper.findByCriteria(crt);
        if (CollectionUtil.isEmpty(tmsVehicleGpsModelList)) {
            throw new BizException("车辆定位不存在");
        } else {
            tmsVehicleGpsModelList = tmsVehicleGpsModelList.stream().filter(tmsVehicleGpsModel ->
                    tmsVehicleGpsModel.getShipbillId().equals(tmsVehicleGpsModel.getRealShipbillId())).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(tmsVehicleGpsModelList)) {
                return BeanUtil.toBean(tmsVehicleGpsModelList.get(0), TmsVehicleGpsDTO.class);
            } else {
                throw new BizException("车辆定位不存在");
            }
        }
    }

    /**
     * 车辆轨迹
     * @param vo
     * @return
     */
    @Override
    public List<TmsVehicleGpsDTO> getTrack(InTransitQueryVO vo) {
        checkCarAndPhoneNumber(vo);
        checkDateParam(vo);
        Criteria crt = Criteria.forClass(TmsVehicleGpsModel.class);
        Restriction r1 = StrUtil.isBlank(vo.getCarNumber()) ? null : Restrictions.eq("vehiclePlateNumber", vo.getCarNumber());
        Restriction r2 = StrUtil.isBlank(vo.getMobilePhone()) ? null : Restrictions.eq("driverPhoneNumber", vo.getMobilePhone());
        Restriction r3 = Restrictions.ge("createtime", vo.getStartDate());
        Restriction r4 = Restrictions.le("createtime", vo.getEndDate());
        crt.setRestriction(Restrictions.and(r1, r2, r3, r4));
        crt.setOrder(Order.newInstance().asc("updatetime", "createtime"));
        List<TmsVehicleGpsModel> tmsVehicleGpsModelList = tmsVehicleGpsMapper.findByCriteria(crt);
        List<TmsVehicleGpsDTO> tmsVehicleGpsDTOList = Lists.newArrayList();
        if (CollectionUtil.isNotEmpty(tmsVehicleGpsModelList)) {
            List<TmsVehicleGpsDTO> list = tmsVehicleGpsModelList.stream().filter(tmsVehicleGpsModel ->
                    tmsVehicleGpsModel.getShipbillId().equals(tmsVehicleGpsModel.getRealShipbillId())).map(tmsVehicleGpsModel ->
                    BeanUtil.toBean(tmsVehicleGpsModel, TmsVehicleGpsDTO.class)).collect(Collectors.toList());
            //按经纬度分组聚合
            Map<BigDecimal, Map<BigDecimal, List<TmsVehicleGpsDTO>>> latMap =
                    list.stream().collect(Collectors.groupingBy(TmsVehicleGpsDTO::getLatitude, Collectors.groupingBy(TmsVehicleGpsDTO::getLongitude)));
            latMap.forEach((key, value) -> value.forEach((key1, value1) -> {
                TmsVehicleGpsDTO dto = value1.get(0);
                dto.setShipbillId(value1.stream().map(TmsVehicleGpsDTO::getShipbillId).distinct().collect(Collectors.joining(",")));
                dto.setShipbillNo(value1.stream().map(TmsVehicleGpsDTO::getShipbillNo).distinct().collect(Collectors.joining(",")));
                dto.setLoadingBillId(value1.stream().map(TmsVehicleGpsDTO::getLoadingBillId).distinct().collect(Collectors.joining(",")));
                dto.setLoadingBillNo(value1.stream().map(TmsVehicleGpsDTO::getLoadingBillNo).distinct().collect(Collectors.joining(",")));
                tmsVehicleGpsDTOList.add(dto);
            }));
        } else {
            throw new BizException("车辆轨迹不存在");
        }
        return tmsVehicleGpsDTOList.stream().sorted(Comparator.comparing(TmsVehicleGpsDTO::getUpdatetime)).collect(Collectors.toList());
    }

    /**
     * 根据gpsid查询运单派车单
     * @param gpsId
     * @return
     */
    @Override
    public LoadingAndShipBillHeaderDTO getLoadingAndShipBillByGpsId(String gpsId) {
        ToolKits.isParamNull(gpsId, "gpsId不能为空");
        TmsVehicleGpsModel tmsVehicleGpsModel = tmsVehicleGpsMapper.findById(gpsId, TmsVehicleGpsModel.class);
        ToolKits.isParamNull(tmsVehicleGpsModel, "gps记录不存在");
        LoadingAndShipBillHeaderDTO loadingAndShipBillHeaderDTO = new LoadingAndShipBillHeaderDTO();
        if (StrUtil.isNotBlank(tmsVehicleGpsModel.getLoadingBillId())) {
            TmsLoadingBillHeaderModel tmsLoadingBillHeaderModel = tmsLoadingBillHeaderMapper.findById(tmsVehicleGpsModel.getLoadingBillId(), TmsLoadingBillHeaderModel.class);
            if (Objects.nonNull(tmsLoadingBillHeaderModel)) {
                loadingAndShipBillHeaderDTO.setLoadingBill(translateLoadingBillHeaderPageDTO(getLoadingBillDicData(),
                        BeanUtil.toBean(tmsLoadingBillHeaderModel, LoadingBillHeaderPageDTO.class)));
            }
        }
        if (StrUtil.isNotBlank(tmsVehicleGpsModel.getShipbillId())) {
            TmsShipbillHeaderModel tmsShipbillHeaderModel = tmsShipbillHeaderMapper.findById(tmsVehicleGpsModel.getShipbillId(), TmsShipbillHeaderModel.class);
            if (Objects.nonNull(tmsShipbillHeaderModel)) {
                loadingAndShipBillHeaderDTO.setShipBill(translateShipBillHeaderPageDTO(getShipBillDicData(),
                        BeanUtil.toBean(tmsShipbillHeaderModel, ShipbillHeaderPageDTO.class)));
            }
        }
        return loadingAndShipBillHeaderDTO;
    }

    /**
     * 运单定位
     * @param shipBillId
     * @return
     */
    @Override
    public TmsVehicleGpsDTO getPositionByShipBillId(String shipBillId) {
        checkShipBillAndReturn(shipBillId);
        List<TmsVehicleGpsDTO> tmsVehicleGpsDTOList = getGpsByShipBillId(shipBillId);
        if (CollectionUtil.isEmpty(tmsVehicleGpsDTOList)) {
            throw new BizException(shipBillId + "运单定位不存在");
        }
        return tmsVehicleGpsDTOList.get(tmsVehicleGpsDTOList.size() - 1);
    }

    /**
     * 运单轨迹
     * @param shipBillId
     * @return
     */
    @Override
    public InTransitTrackDTO getTrackByShipBillId(String shipBillId) {
        TmsShipbillHeaderModel model = checkShipBillAndReturn(shipBillId);
        List<TmsVehicleGpsDTO> tmsVehicleGpsDTOList = getGpsByShipBillId(shipBillId);
        if (CollectionUtil.isEmpty(tmsVehicleGpsDTOList)) {
            throw new BizException(shipBillId + "运单轨迹不存在");
        }
        InTransitTrackDTO inTransitTrackDTO = new InTransitTrackDTO();
        inTransitTrackDTO.setStatus(model.getStatus());
        if (model.getStatus() > DataDictionaryConstant.SHIPBILL_STATUS_SD) {
            inTransitTrackDTO.setDesc("终点");
        } else {
            inTransitTrackDTO.setDesc("在途");
        }
        inTransitTrackDTO.setTmsVehicleGpsDTOList(tmsVehicleGpsDTOList);
        inTransitTrackDTO.setDeviceGpsDTOList(convert(tmsVehicleGpsDTOList));
        return inTransitTrackDTO;
    }

    /**
     * 派车单定位
     * @param loadingBillId
     * @return
     */
    @Override
    public TmsVehicleGpsDTO getPositionByLoadingBillId(String loadingBillId) {
        checkLoadingBillAndReturn(loadingBillId);
        List<TmsVehicleGpsDTO> tmsVehicleGpsDTOList = getGpsByLoadingBillId(loadingBillId);
        if (CollectionUtil.isEmpty(tmsVehicleGpsDTOList)) {
            throw new BizException(loadingBillId + "派车单定位不存在");
        }
        return tmsVehicleGpsDTOList.get(tmsVehicleGpsDTOList.size() - 1);
    }

    /**
     * 派车单轨迹
     * @param loadingBillId
     * @return
     */
    @Override
    public InTransitTrackDTO getTrackByLoadingBillId(String loadingBillId) {
        TmsLoadingBillHeaderModel model = checkLoadingBillAndReturn(loadingBillId);
        List<TmsVehicleGpsDTO> tmsVehicleGpsDTOList = getGpsByLoadingBillId(loadingBillId);
        if (CollectionUtil.isEmpty(tmsVehicleGpsDTOList)) {
            throw new BizException(loadingBillId + "派车单轨迹不存在");
        }
        InTransitTrackDTO inTransitTrackDTO = new InTransitTrackDTO();
        inTransitTrackDTO.setStatus(model.getStatus());
        if (model.getStatus() >= DataDictionaryConstant.LOADING_BILL_STATUS_SD) {
            inTransitTrackDTO.setDesc("终点");
        } else {
            inTransitTrackDTO.setDesc("在途");
        }
        inTransitTrackDTO.setTmsVehicleGpsDTOList(tmsVehicleGpsDTOList);
        inTransitTrackDTO.setDeviceGpsDTOList(convert(tmsVehicleGpsDTOList));
        return inTransitTrackDTO;
    }

    /**
     * 派车单分页
     * @param vo
     * @return
     */
    @Override
    List<LoadingBillHeaderPageDTO> pageLoadingBillByPositionType(InTransitQueryVO vo) {
        return tmsLoadingBillHeaderMapper.getInTransitLoadingBill(vo);
    }

    /**
     * 运单分页
     * @param vo
     * @return
     */
    @Override
    List<ShipbillHeaderPageDTO> pageShipBillByPositionType(InTransitQueryVO vo) {
        return tmsShipbillHeaderMapper.getInTransitShipBill(vo);
    }

    /**
     * 根据运单获取gps数据
     * @param shipBillId
     * @return
     */
    private List<TmsVehicleGpsDTO> getGpsByShipBillId(String shipBillId) {
        List<TmsVehicleGpsDTO> tmsVehicleGpsDTOList = Lists.newArrayList();
        Criteria crt = Criteria.forClass(TmsVehicleGpsModel.class);
        TmsVehicleGpsModel tmsVehicleGpsModel = new TmsVehicleGpsModel();
        crt.restrictionBuilder().eq(tmsVehicleGpsModel::getShipbillId, shipBillId).build();
        crt.orderAscBy(tmsVehicleGpsModel::getUpdatetime, tmsVehicleGpsModel::getCreatetime);
        List<TmsVehicleGpsModel> tmsVehicleGpsModelList = tmsVehicleGpsMapper.findByCriteria(crt);
        if (CollectionUtil.isNotEmpty(tmsVehicleGpsModelList)) {
            tmsVehicleGpsDTOList = tmsVehicleGpsModelList.stream().map(model ->
                    BeanUtil.toBean(model, TmsVehicleGpsDTO.class)).collect(Collectors.toList());
        }
        return tmsVehicleGpsDTOList;
    }

    /**
     * 根据派车单获取gps数据
     * @param loadingBillId
     * @return
     */
    private List<TmsVehicleGpsDTO> getGpsByLoadingBillId(String loadingBillId) {
        List<TmsVehicleGpsDTO> tmsVehicleGpsDTOList = Lists.newArrayList();
        Criteria crt = Criteria.forClass(TmsVehicleGpsModel.class);
        TmsVehicleGpsModel tmsVehicleGpsModel = new TmsVehicleGpsModel();
        crt.restrictionBuilder().eq(tmsVehicleGpsModel::getLoadingBillId, loadingBillId).build();
        crt.orderAscBy(tmsVehicleGpsModel::getUpdatetime, tmsVehicleGpsModel::getCreatetime);
        List<TmsVehicleGpsModel> tmsVehicleGpsModelList = tmsVehicleGpsMapper.findByCriteria(crt);
        if (CollectionUtil.isNotEmpty(tmsVehicleGpsModelList)) {
            tmsVehicleGpsDTOList = tmsVehicleGpsModelList.stream().map(model ->
                    BeanUtil.toBean(model, TmsVehicleGpsDTO.class)).collect(Collectors.toList());
        }
        return tmsVehicleGpsDTOList;
    }

    /**
     * convert
     * @param tmsVehicleGpsDTOList
     * @return
     */
    private List<DeviceGpsDTO> convert(List<TmsVehicleGpsDTO> tmsVehicleGpsDTOList) {
        return tmsVehicleGpsDTOList.stream().map(tmsVehicleGpsDTO -> {
            DeviceGpsDTO deviceGpsDTO = BeanUtil.copyProperties(tmsVehicleGpsDTO, DeviceGpsDTO.class);
            deviceGpsDTO.setGpsDate(tmsVehicleGpsDTO.getCreatetime());
            return deviceGpsDTO;
        }).collect(Collectors.toList());
    }

}
