package com.tofly.gpsboot.controller.monitor;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tofly.api.DepartmentClient;
import com.tofly.api.UserClent;
import com.tofly.common.core.entity.ResultRespone;
import com.tofly.common.core.util.DateUtil;
import com.tofly.common.oauth.auth.ToflyUser;
import com.tofly.common.oauth.util.SecurityUtils;
import com.tofly.es.CarGpsUpload;
import com.tofly.es.dto.EsCarGpsUploadQueryDto;
import com.tofly.gpsboot.mapper.es.GpsUploadRepository;
import com.tofly.gpsboot.service.car.CarBaseinfoService;
import com.tofly.gpsboot.service.car.CarService;
import com.tofly.gpsboot.service.car.CarUserService;
import com.tofly.gpsboot.service.es.ICarGpsUploadService;
import com.tofly.gpsboot.util.DateTimeUtil;
import com.tofly.gpsboot.util.EsSaveInfoUtil;
import com.tofly.pojo.Department;
import com.tofly.pojo.car.CarBaseinfo;
import com.tofly.pojo.monitor.dto.MonitorDto;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@AllArgsConstructor
@RequestMapping("/monitorCenter")
@Api(tags = "监控中心")
public class MonitorCenterController {

    private final CarService carService;
    private final CarUserService carUserService;
    private final UserClent userClent;
    private final GpsUploadRepository gpsUploadRepository;
    private final EsSaveInfoUtil esSaveInfoUtil;
    private ElasticsearchTemplate elasticsearchTemplate;
    private final CarBaseinfoService carBaseinfoService;
    private final ICarGpsUploadService iCarGpsUploadService;
    private final DepartmentClient departmentClient;

    @GetMapping("/userData")
    @ApiOperation(value = "人员")
    public ResultRespone<ToflyUser> getuserMonitorPage(@ModelAttribute MonitorDto monitorDto) {
        //查询人员
        return ResultRespone.success(SecurityUtils.getUser());

    }


//    @GetMapping("/carMonitor" )
//    @ApiOperation(value = "分页查询")
//    public ResultRespone<Page<CarVo>> getCarPage(Page page, @ModelAttribute MonitorDto monitorDto) {
//      final   Date staDate ,endDate ;
//        if(!StringUtils.isNotBlank(monitorDto.getDate())){
//            monitorDto.setDate(DateUtil.getDateTimeFormat(new Date()));
//        }
//                // 格式化传入时间
//                LocalDateTime localDateTime = DateTimeUtil.fromString2LocalDateTime(monitorDto.getDate(), DateTimeUtil.FULL_FORMAT);
//                // 获取指定开始/结束时间
//                assert localDateTime != null;
//                staDate = DateTimeUtil.convertLDTToDate(DateTimeUtil.getAssignTodayBeginTime(localDateTime));
//                endDate = DateTimeUtil.convertLDTToDate(DateTimeUtil.getAssignTodayEndTime(localDateTime));
//                //查找车辆信息
//
//
//        List<Long> carIds=null;
//        //查看在传入时间段绑定了用户的车辆
//            carIds = carUserService.list(Wrappers.<CarUser>lambdaQuery()
//                    .eq(null!=monitorDto.getUserId(),CarUser::getUserId, monitorDto.getUserId())
//                    .between(StringUtils.isNotBlank(monitorDto.getDate()), CarUser::getBeginDate, staDate, endDate).orderByDesc(CarUser::getId)
//            ).stream().map(CarUser::getCarId).collect(Collectors.toList());
//
//        Page page1 = carService.page(page, Wrappers.<Car>lambdaQuery()
//                .eq(monitorDto.getDepartmentId() != null, Car::getDepartment, monitorDto.getDepartmentId())
//              //  .in(carIds != null && carIds.size() > 0, Car::getId, carIds)
//        );
//
//
//        List<Car> records = page1.getRecords();
//        List<CarVo> carVoList = new ArrayList<>();
//        records.forEach(car->{
//            CarVo carVo = JSONObject.parseObject(JSON.toJSONString(car),CarVo.class);
//
//
//
//
//            List<Long> userIds = carUserService.list(Wrappers.<CarUser>lambdaQuery()
//                    .eq(null!=monitorDto.getUserId(),CarUser::getUserId, monitorDto.getUserId())
//                    .eq(CarUser::getCarId,car.getId())
//                    .between(StringUtils.isNotBlank(monitorDto.getDate()), CarUser::getBeginDate, staDate, endDate).orderByDesc(CarUser::getId)
//            ).stream().map(CarUser::getUserId).collect(Collectors.toList());
//            //查询es
//            if(userIds!=null &&userIds.size()>0){
//                UserGpsSearchDto dto = new UserGpsSearchDto();
//                dto.setStartDate(staDate);
//                dto.setEndDate(endDate);
//                dto.setUserId(userIds.get(0));
//                Page page2 = new Page();
//                QueryBuilder[] queryBuilders = EsQueryUtil.getGpsLst(page2, dto);
//                GpsUpload gpsUpload = new GpsUpload();
//                page2.setSize(1);
//                Page allPage = gpsUploadRepository.getAllPage(gpsUpload, page2,
//                        esSaveInfoUtil.DyMonth(gpsUploadRepository.getIndex()), elasticsearchTemplate, queryBuilders);
//                List<GpsUpload> records1 = allPage.getRecords();
//                if(records1!=null && records1.size()>0 ){
//                    GpsUpload gpsUpload1 = records1.get(0);
//                    BigDecimal locationLatitude = gpsUpload1.getLocationLatitude();
//                    BigDecimal locationLongitude = gpsUpload1.getLocationLongitude();
//                    carVo.setLat(locationLatitude.doubleValue());
//                    carVo.setLng(locationLongitude.doubleValue());
//                }
//
//            }
//
//            List<UserViewVo> userViewVos=new ArrayList<>();
//            userIds.forEach(userId->{
//                User result = userClent.getById(userId).getResult();
//                UserViewVo userViewVo = new UserViewVo();
//                userViewVo.setIsLatest(Boolean.TRUE);
//                userViewVo.setWorknumber(result.getWorknumber());
//                userViewVo.setPhone(result.getPhone());
//                userViewVo.setId(result.getId());
//                userViewVo.setUserName(result.getRealName());
//                userViewVos.add(userViewVo);
//            });
//            carVo.setCarUser(userViewVos);
//            carVoList.add(carVo);
//        });
//        page1.setRecords(carVoList);
//    return  ResultRespone.success(page1);
//    }

    @GetMapping("/carMonitor")
    @ApiOperation(value = "分页查询")
    public ResultRespone<Page<CarBaseinfo>> getCarPage(Page page, @ModelAttribute MonitorDto monitorDto) {
        final Date startDate, endDate;
        if (!StringUtils.isNotBlank(monitorDto.getDate())) {
            monitorDto.setDate(DateUtil.getDateTimeFormat(new Date()));
        }
        if (org.apache.commons.lang3.StringUtils.isNotBlank(monitorDto.getStartDate())
                && org.apache.commons.lang3.StringUtils.isNotBlank(monitorDto.getEndDate())) {
            startDate = cn.hutool.core.date.DateUtil.parse(monitorDto.getStartDate(), "yyyy-MM-dd HH:mm:ss");
            endDate = cn.hutool.core.date.DateUtil.parse(monitorDto.getEndDate(), "yyyy-MM-dd HH:mm:ss");
        } else {
            // 格式化传入时间
            LocalDateTime localDateTime = DateTimeUtil.fromString2LocalDateTime(monitorDto.getDate(), DateTimeUtil.FULL_FORMAT);
            // 获取指定开始/结束时间
            assert localDateTime != null;
            startDate = DateTimeUtil.convertLDTToDate(DateTimeUtil.getAssignTodayBeginTime(localDateTime));
            endDate = DateTimeUtil.convertLDTToDate(DateTimeUtil.getAssignTodayEndTime(localDateTime));
        }

        List<Long> deptIdList = new ArrayList<>();
        if (org.apache.commons.lang3.StringUtils.isNotBlank(monitorDto.getDepartmentId())) {
            List<Long> queryDeptId = Arrays.stream(monitorDto.getDepartmentId().split(",")).map(Long::parseLong).collect(Collectors.toList());
            queryDeptId.forEach(deptId ->
                    deptIdList.addAll(departmentClient.getDepartmentPage(deptId, "1").getResult()
                    .stream().map(Department::getId).collect(Collectors.toList())));
        }

        List<String> commonCars = carBaseinfoService.getCommonCarInfo();
        Page<CarBaseinfo> page1 = carBaseinfoService.page(page, Wrappers.<CarBaseinfo>lambdaQuery()
                .eq(monitorDto.getCarId() != null, CarBaseinfo::getId, monitorDto.getCarId())
                .eq(monitorDto.getUserId() != null, CarBaseinfo::getManager, monitorDto.getUserId())
                .and(wrapper -> wrapper.in(CollUtil.isNotEmpty(deptIdList), CarBaseinfo::getDepartmentId, deptIdList)
                        .or()
                        .in(CollUtil.isNotEmpty(commonCars), CarBaseinfo::getCarNumber, commonCars)));
        List<CarBaseinfo> records = page1.getRecords();
        records.forEach(car -> {
            //查询es
            EsCarGpsUploadQueryDto dto = new EsCarGpsUploadQueryDto();
            dto.setStartTime(startDate);
            dto.setEndTime(endDate);
            dto.setCarId(car.getId());
            List<CarGpsUpload> carGpsUploads = iCarGpsUploadService.getGpsCarList(dto);
            car.setCarGpsUploads(carGpsUploads);
        });
        page1.setRecords(records);
        return ResultRespone.success(page1);
    }

}
