package com.tofly.gpsboot.controller.es;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tofly.common.core.entity.ResultRespone;
import com.tofly.common.log.annotation.ToFlyAppLog;
import com.tofly.es.PdaDeviceUpload;
import com.tofly.es.dto.EsQueryDto;
import com.tofly.es.vo.TerminalMonitoringVo;
import com.tofly.gpsboot.common.Constant;
import com.tofly.gpsboot.common.system.NewWorkTypeEnum;
import com.tofly.gpsboot.common.system.WorkStateEnum;
import com.tofly.gpsboot.service.comm.IDisposeDateService;
import com.tofly.gpsboot.service.es.IPdaDeviceService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author tuonbed
 * @date 2020/5/6  15:38
 */
@RestController
@RequestMapping("/pda")
@Api(tags="ES存储移动设备信息")
@Slf4j
public class PdaDeviceUploadController {

    @Autowired
    private IPdaDeviceService iPdaDeviceService;

    @Autowired
    private IDisposeDateService disposeDateService;

    @ApiOperation(value = "新增移动设备信息")
    @PostMapping
    public ResultRespone<Boolean> save(@RequestBody @Validated PdaDeviceUpload pdaDeviceUpload) {
       return ResultRespone.success(iPdaDeviceService.savePdaDeviceInfo(pdaDeviceUpload));
    }


    @ToFlyAppLog(title="修改移动设备信息" )
    @ApiOperation(value = "修改移动设备信息")
    @PutMapping
    public ResultRespone<Boolean> update(@RequestBody PdaDeviceUpload pdaDeviceUpload) {
        return ResultRespone.success(iPdaDeviceService.updatePdaDeviceInfo(pdaDeviceUpload));
    }


    @ApiOperation(value = "根据ID获取移动设备信息")
    @GetMapping("/findone")
    public ResultRespone<PdaDeviceUpload> get(String id){
        return ResultRespone.success(iPdaDeviceService.getByIdPdaDeviceInfo(id));
    }


    /**
     * 通过id删除GPS信息表
     * @param id id
     * @return ResultRespone
     */
    @ToFlyAppLog(title="通过id删除移动设备信息" )
    @ApiOperation(value = "通过id删除移动设备信息表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "String")
    })
    @DeleteMapping("/{id}" )
    public ResultRespone<Boolean> removeById(@PathVariable String id) {
        return ResultRespone.success(iPdaDeviceService.removeByIdPdaDeviceInfo(id));
    }


    @ApiOperation(value = "分页获取移动设备信息")
    @GetMapping("/page")
    public ResultRespone<Page<List<PdaDeviceUpload>>> get(Page page, @ModelAttribute EsQueryDto dto){
        Page<List<PdaDeviceUpload>> pageGpsInfo = iPdaDeviceService.getPageGpsInfo(page, dto);
        return ResultRespone.success(pageGpsInfo);
    }

    @ApiOperation(value = "获取所有index的移动设备信息")
    @GetMapping("/getAllPage")
    public ResultRespone<Page<List<PdaDeviceUpload>>> getAllPage(Page page, @ModelAttribute EsQueryDto dto){
        return ResultRespone.success(iPdaDeviceService.getAllPage(page,dto));
    }


    @ApiOperation(value = "获取所有index的移动设备信息（非分页）")
    @GetMapping("/getAll")
    public ResultRespone<List<PdaDeviceUpload>> getAllpage(@ModelAttribute EsQueryDto dto){
        return ResultRespone.success(iPdaDeviceService.getAll(dto));
    }

    @ApiOperation(value = "终端监控查询")
    @GetMapping("/terminalMonitoringQuery")
    public ResultRespone<TerminalMonitoringVo> terminalMonitoringQuery(Page page, @ModelAttribute EsQueryDto dto) {
        TerminalMonitoringVo vo = new TerminalMonitoringVo();
        // 判断参数是否传入 部门ID 或 用户id
        Long userId = dto.getUserId();
        Long deptId = dto.getDeptId();
        String userIds = disposeDateService.getDeptUsers(userId, deptId);
        dto.setUserIds(userIds);
        // 按照人员分组
        // 统计 工作状态 上班 下班
        // 统计 定位状态 GPS定位 wifi定位 基站定位
        Map<String, Long> map = new HashMap<>(12);
        // 统计当前时间用户下对应的最新定位网络的类型个数
        if(StringUtils.isEmpty(userIds)){
            ResultRespone.success(vo);
        }
        List<Long> longList = Arrays.stream(userIds.split(Constant.CSV)).map(s -> Long.parseLong(s.trim()))
                .collect(Collectors.toList());
        List<PdaDeviceUpload> nowUserInfoList = iPdaDeviceService.getNowUserInfoList(longList, dto.getStartDate(), dto.getEndDate());
        if (null != nowUserInfoList && nowUserInfoList.size() > 0) {
            // 分组定位网络类型
            Map<String, Long> collect = nowUserInfoList.stream().collect(Collectors.groupingBy(p -> NewWorkTypeEnum.getCodeForValue(p.getNetwork()).trim(), Collectors.counting()));
            // 分组工作状态
            Map<String, Long> longMap = nowUserInfoList.stream().collect(Collectors.groupingBy(p -> WorkStateEnum.getCodeForValue(p.getWorkState()).trim(), Collectors.counting()));
            map.putAll(collect);
            map.putAll(longMap);

        }

        Page<List<PdaDeviceUpload>> pageGpsInfo = iPdaDeviceService.getPageGpsInfo(page, dto);
        vo.setMap(map);
        vo.setPagePdaInfo(pageGpsInfo);
        return ResultRespone.success(vo);
    }


}
