package com.jpsoft.shinestar.modules.mobile.controller;

import cn.hutool.core.date.DateUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.util.StringUtil;
import com.jpsoft.shinestar.config.RedisConfig;
import com.jpsoft.shinestar.config.TemperatureConfig;
import com.jpsoft.shinestar.modules.base.dto.PersonDeviceFilterLogDTO;
import com.jpsoft.shinestar.modules.base.dto.PersonDeviceLogDTO;
import com.jpsoft.shinestar.modules.base.entity.*;
import com.jpsoft.shinestar.modules.base.service.*;
import com.jpsoft.shinestar.modules.common.dto.MessageResult;
import com.jpsoft.shinestar.modules.common.dto.Sort;
import com.jpsoft.shinestar.modules.common.utils.PojoUtils;
import com.jpsoft.shinestar.modules.common.utils.StringUtils;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/mobile/personDeviceLogApi")
public class PersonDeviceLogApiController {
    @Autowired
    private PersonInfoService personInfoService;

    @Autowired
    private PersonDeviceRelationService personDeviceRelationService;

    @Autowired
    private PersonDeviceLogService personDeviceLogService;

    @Autowired
    private PersonDeviceFilterLogService personDeviceFilterLogService;

    @Autowired
    private CompanyInfoService companyInfoService;

    @Autowired
    private DeviceInfoService deviceInfoService;

    @Autowired
    private AlarmConfigService alarmConfigService;

    @Autowired
    private TemperatureConfig temperatureConfig;

    @Autowired
    private ValueOperations<String, Object> valueOperations;

    @Autowired
    private PersonCompanyService personCompanyService;

    @PostMapping("queryTemperatureRawRecordList")
    @ApiOperation(value="根据实时数据查看企业人员温度数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name="queryDate",value = "查询日期",required = true,paramType = "form"),
            @ApiImplicitParam(name="companyId",value = "单位编号",paramType = "form"),
            @ApiImplicitParam(name="token",value = "令牌",required = true,paramType = "form"),
            @ApiImplicitParam(name="subject",value = "目标(不传)",paramType = "form")
    })
    public MessageResult<Map> queryTemperatureRawRecordList(
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date queryDate,
            String companyId,
            String token,
            @RequestParam(value="pageIndex",defaultValue="1") int pageIndex,
            @RequestParam(value="pageSize",defaultValue="20") int pageSize,
            @RequestAttribute String subject){
        Page<Map> recordPageList = new Page<>();

        MessageResult<Map> messageResult = new MessageResult<>();

        try {
            Map<String, Object> personSearchParam = new HashMap<>();

            if (StringUtils.isNotEmpty(companyId) && companyInfoService.exist(companyId)) {
                personSearchParam.put("companyId", companyId);
            }
            else{
                PersonInfo admin = personInfoService.get(Long.valueOf(subject));
                personSearchParam.put("companyId", admin.getCompanyId());
            }

            List<Sort> sortList1 = new ArrayList<>();
            sortList1.add(new Sort("id_","asc"));

            Page<PersonInfo> personPageList = personInfoService.pageSearch(personSearchParam,pageIndex,pageSize,true,sortList1);

            DateTime startTime = new DateTime(queryDate);

            for (PersonInfo person : personPageList) {
                Map<String, Object> recordMap = new HashMap<>();

                recordMap.put("name", person.getName());
                recordMap.put("faceImageUrl", person.getFaceImageUrl());

                Map<String, Object> searchParams = new HashMap<>();

                searchParams.put("personId", person.getId());
                searchParams.put("beginTime", startTime.toDate());
                searchParams.put("endTime", startTime.plusDays(1).toDate());

                List<Sort> sortList = new ArrayList<>();
                sortList.add(new Sort("record_time", "asc"));

                Page<PersonDeviceLog> page = personDeviceLogService.simplePageSearch(searchParams, 1, 100, false, sortList);

                Map<Integer, List> hourMap = new TreeMap<>();

                //收集每个人每小时的测量温度
                for (PersonDeviceLog personDeviceLog : page) {
                    DateTime recordTime = new DateTime(personDeviceLog.getRecordTime());

                    int hour = recordTime.getHourOfDay();

                    if (hourMap.containsKey(hour)) {
                        hourMap.get(hour).add(personDeviceLog);
                    } else {
                        List<PersonDeviceLog> logList = new ArrayList<>();
                        logList.add(personDeviceLog);
                        hourMap.put(hour, logList);
                    }
                }

                //每个小时取一条温度数据小于37的即可，如果没有则取最低的
                BigDecimal stdLower = temperatureConfig.getMin();
                BigDecimal stdUpper = temperatureConfig.getMax();

                Map<Integer, PersonDeviceLog> hourFilterMap = new TreeMap<>();

                for (Integer hour : hourMap.keySet()) {
                    List<PersonDeviceLog> logList = hourMap.get(hour);

                    List<PersonDeviceLog> filterList = logList.stream()
                            //查询是否有36度至37度
                            .filter((log) -> {
                                if (log.getTemperature().compareTo(stdLower) >= 0
                                        && log.getTemperature().compareTo(stdUpper) <= 0) {
                                    return true;
                                } else {
                                    return false;
                                }
                            })
                            //体温由低到高排列
                            .sorted(Comparator.comparing(PersonDeviceLog::getTemperature)).collect(Collectors.toList());

                    if (filterList.size() > 0) {
                        hourFilterMap.put(hour, filterList.get(0));
                    } else {
                        //如果不存在，则取最低的一条
                        Optional<PersonDeviceLog> optional = logList.stream()
                                .sorted(Comparator.comparing(PersonDeviceLog::getTemperature)).findFirst();

                        if (optional.isPresent()) {
                            hourFilterMap.put(hour, optional.get());
                        }
                    }
                }

                SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");

                List<Map> personDeviceLogs = hourFilterMap.keySet().stream()
                        .map((key) -> hourFilterMap.get(key))
                        .filter((log)->log.getTemperature().compareTo(BigDecimal.ZERO)>0)
                        .sorted(Comparator.comparing(PersonDeviceLog::getRecordTime))
                        .map((log)->{
                            Map<String,Object> map = new HashMap<>();
                            //日志编号
                            map.put("id",log.getId());
                            map.put("temperature",log.getTemperature());
                            map.put("recordTime",sdf.format(log.getRecordTime()));

                            return map;
                        })
                        .collect(Collectors.toList());

                recordMap.put("list", personDeviceLogs);

                recordPageList.add(recordMap);
            }

            recordPageList.setTotal(personPageList.getTotal());
            recordPageList.setPages(personPageList.getPages());
            recordPageList.setPageNum(personPageList.getPageNum());
            recordPageList.setPageSize(personPageList.getPageSize());

            messageResult.setResult(true);
            messageResult.setData(PojoUtils.pageWrapper(recordPageList));
        }
        catch (Exception ex){
            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }

        return messageResult;
    }


    @PostMapping("queryTemperatureRecordListByEnt")
    @ApiOperation(value="根据过滤后考勤记录统计单位员工温度数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name="queryDate",value = "查询日期",required = true,paramType = "form"),
            @ApiImplicitParam(name="companyId",value = "单位编号",paramType = "form"),
            @ApiImplicitParam(name="filter",value = "是否过滤（1-显示异常数据,0-显示全部)",paramType = "form"),
            @ApiImplicitParam(name="token",value = "令牌",required = true,paramType = "form"),
            @ApiImplicitParam(name="subject",value = "目标(不传)",paramType = "form")
    })
    public MessageResult<Map> queryTemperatureRecordListByEnt(
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date queryDate,
            String companyId,
            String token,
            String filter,
            @RequestParam(value="pageIndex",defaultValue="1") int pageIndex,
            @RequestParam(value="pageSize",defaultValue="20") int pageSize,
            @RequestAttribute String subject){
        Page<Map> recordPageList = new Page<>();

        MessageResult<Map> messageResult = new MessageResult<>();

        try {
            Map<String, Object> personSearchParam = new HashMap<>();

            PersonInfo personInfo = personInfoService.get(Long.valueOf(subject));

            if(StringUtils.isEmpty(companyId)){
                companyId = personInfo.getCompanyId();
            }

            CompanyInfo companyInfo = companyInfoService.get(companyId);

            if (companyInfo!=null){
                personSearchParam.put("companyCode", companyInfo.getCode() + "%");
            }

            if (StringUtils.isNotEmpty(filter) && "1".equals(filter)){
                personSearchParam.put("abnormalDate",queryDate);
                personSearchParam.put("temperatureMax",temperatureConfig.getMax());
            }

            List<Sort> sortList1 = new ArrayList<>();
            sortList1.add(new Sort("id_","asc"));

            Page<PersonInfo> personPageList = personInfoService.pageSearch(personSearchParam,pageIndex,pageSize,true,sortList1);

            DateTime startTime = new DateTime(queryDate);

            for (PersonInfo person : personPageList) {
                Map<String, Object> recordMap = new HashMap<>();

                recordMap.put("name", person.getName());
                recordMap.put("faceImageUrl", person.getFaceImageUrl());

                Map<String, Object> searchParams = new HashMap<>();

                searchParams.put("personId", person.getId());
                searchParams.put("beginTime", startTime.toDate());
                searchParams.put("endTime", startTime.plusDays(1).toDate());

                if (StringUtils.isNotEmpty(filter) && "1".equals(filter)){
                    searchParams.put("fever",true);
                    searchParams.put("temperatureMax",temperatureConfig.getMax());
                }

                List<Sort> sortList = new ArrayList<>();
                sortList.add(new Sort("record_time", "asc"));

                Page<PersonDeviceFilterLog> page = personDeviceFilterLogService.pageSearch(searchParams,1,24,false,sortList);

                SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");

                List<Map> personDeviceLogs = page.stream()
                        .filter((log)->log.getTemperature().compareTo(BigDecimal.ZERO)>0)
                        .map((log)->{
                            Map<String,Object> map = new HashMap<>();
                            //日志编号
                            map.put("id",log.getId());
                            map.put("temperature",log.getTemperature());
                            map.put("recordTime",sdf.format(log.getRecordTime()));

                            return map;
                        })
                        .collect(Collectors.toList());

                recordMap.put("list", personDeviceLogs);

                recordPageList.add(recordMap);
            }

            recordPageList.setTotal(personPageList.getTotal());
            recordPageList.setPages(personPageList.getPages());
            recordPageList.setPageNum(personPageList.getPageNum());
            recordPageList.setPageSize(personPageList.getPageSize());

            Map<String,Object> dataMap = PojoUtils.pageWrapper(recordPageList);

            //增加当天打卡人数统计
            long detectedNum = 0;

            if (companyInfo!=null) {
                detectedNum = personDeviceFilterLogService.countDetectedByCompanyCode(companyInfo.getCode(), startTime.toDate(), startTime.plusDays(1).toDate());
            }

            dataMap.put("detectedNum",detectedNum);

            messageResult.setResult(true);
            messageResult.setData(dataMap);
        }
        catch (Exception ex){
            log.error(ex.getMessage(),ex);
            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }

        return messageResult;
    }

    @PostMapping("queryAbnormalTemperatureRecordList")
    @ApiOperation(value="根据时间查询异常测温记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name="queryDate",value = "查询日期",required = true,paramType = "form"),
            @ApiImplicitParam(name="companyId",value = "单位编号",paramType = "form"),
            @ApiImplicitParam(name="token",value = "令牌",required = true,paramType = "form"),
            @ApiImplicitParam(name="subject",value = "目标(不传)",paramType = "form")
    })
    public MessageResult<Map> queryAbnormalTemperatureRecordList(
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date queryDate,
            String companyId,
            String token,
            @RequestParam(value="pageIndex",defaultValue="1") int pageIndex,
            @RequestParam(value="pageSize",defaultValue="20") int pageSize,
            @RequestAttribute String subject){
        Page<Map> recordPageList = new Page<>();

        MessageResult<Map> messageResult = new MessageResult<>();

        try {
            Map<String, Object> personSearchParam = new HashMap<>();

            if (StringUtils.isEmpty(companyId)) {
                PersonInfo admin = personInfoService.get(Long.valueOf(subject));

                Map<String,Object> companyMap = (Map<String,Object>)valueOperations.get(RedisConfig.PERSON_SELECT_COMPANY + admin.getId());
                companyId = companyMap.get("id").toString();
            }
            DateTime startTime = new DateTime(queryDate);

            personSearchParam.put("companyId", companyId);
            personSearchParam.put("temperatureMax", temperatureConfig.getMax());
            personSearchParam.put("beginTime", DateUtil.beginOfDay(queryDate));
            personSearchParam.put("endTime",DateUtil.endOfDay(queryDate));
        //    if (StringUtils.isNotEmpty(filter) && "1".equals(filter)){
           //     personSearchParam.put("abnormalDate",queryDate);
                personSearchParam.put("fever",true);
         //   }

            List<Sort> sortList1 = new ArrayList<>();
            sortList1.add(new Sort("a.record_time","desc"));
            Page<PersonDeviceFilterLog> page = personDeviceFilterLogService.pageSearch(personSearchParam,pageIndex,pageSize,true,sortList1);


        //    Page<PersonInfo> personPageList = personInfoService.pageSearch(personSearchParam,pageIndex,pageSize,true,sortList1);



           /* for (PersonInfo person : personPageList) {
                Map<String, Object> recordMap = new HashMap<>();

                recordMap.put("name", person.getName());
                recordMap.put("faceImageUrl", person.getFaceImageUrl());

                Map<String, Object> searchParams = new HashMap<>();

                searchParams.put("personId", person.getId());
                searchParams.put("beginTime", startTime.toDate());
                searchParams.put("endTime", startTime.plusDays(1).toDate());

                if (StringUtils.isNotEmpty(filter) && "1".equals(filter)){
                    searchParams.put("fever",true);
                    searchParams.put("temperatureMax",temperatureConfig.getMax());
                }

                List<Sort> sortList = new ArrayList<>();
                sortList.add(new Sort("record_time", "asc"));

                Page<PersonDeviceFilterLog> page = personDeviceFilterLogService.pageSearch(searchParams,1,24,false,sortList);

                SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");

                List<Map> personDeviceLogs = page.stream()
                        .filter((log)->log.getTemperature().compareTo(BigDecimal.ZERO)>0)
                        .map((log)->{
                            Map<String,Object> map = new HashMap<>();
                            //日志编号
                            map.put("id",log.getId());
                            map.put("temperature",log.getTemperature());
                            map.put("recordTime",sdf.format(log.getRecordTime()));

                            return map;
                        })
                        .collect(Collectors.toList());

                recordMap.put("list", personDeviceLogs);

                recordPageList.add(recordMap);
            }*/

            recordPageList.setTotal(page.getTotal());
            recordPageList.setPages(page.getPages());
            recordPageList.setPageNum(page.getPageNum());
            recordPageList.setPageSize(page.getPageSize());

            Map<String,Object> dataMap = PojoUtils.pageWrapper(page);

           /* //增加当天打卡人数统计
            Integer detectedNum = personDeviceFilterLogService.countDetectedByCompanyId(companyId,startTime.toDate(),startTime.plusDays(1).toDate());
            dataMap.put("detectedNum",detectedNum);*/

            messageResult.setResult(true);
            messageResult.setData(dataMap);
        }
        catch (Exception ex){
            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }

        return messageResult;
    }


    @PostMapping("queryCompanyList")
    @ApiOperation(value="查询单位列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name="token",value = "令牌",required = true,paramType = "form"),
            @ApiImplicitParam(name="subject",value = "目标(不传)",paramType = "form")
    })
    public MessageResult<Map> queryCompanyList(String token,@RequestAttribute String subject){
        MessageResult<Map> messageResult = new MessageResult<>();

        Map<String,Object> dataMap = new HashMap<>();

        try {
            PersonInfo personInfo = personInfoService.get(Long.valueOf(subject));
            CompanyInfo companyInfo = companyInfoService.get(personInfo.getCompanyId());

            String companyCode = null;

            if (personInfo.getAllowViewLocal()!=null && personInfo.getAllowViewLocal()){
                companyCode = companyInfo.getCode() + "%";
            }

            List<CompanyInfo> companyList = companyInfoService.findByCompanyCode(companyCode, personInfo.getId());

            List<Map> mapList = companyList.stream().map((company)->{
                Map<String,Object> map = new HashMap<>();

                map.put("id",company.getId());
                map.put("code",company.getCode());
                map.put("name", company.getName());

                return map;

            }).collect(Collectors.toList());

            DateTime beginTime =DateTime.now().withTimeAtStartOfDay();
            DateTime endTime = beginTime.plusDays(1);
            long sumPersonNum = 0;
            long sumDetectedNum = 0;

            for (Map map : mapList) {
                String companyId = (String)map.get("id");
                String code = (String)map.get("code");

                //单位
                long personNum = personInfoService.countByCompanyId(companyId);
                sumPersonNum += personNum;

                //当日已测人数
                long detectedNum = personDeviceLogService.countByAttendance(code + "%",beginTime.toDate(),endTime.toDate());
                sumDetectedNum += detectedNum;

                map.put("personNum",personNum);
                map.put("detectedNum",detectedNum);
            }

            //增加汇总
            dataMap.put("list",mapList);
            dataMap.put("sumPersonNum",sumPersonNum);
            dataMap.put("sumDetectedNum",sumDetectedNum);

            messageResult.setData(dataMap);
            messageResult.setResult(true);
        }
        catch (Exception ex){
            messageResult.setMessage(ex.getMessage());
            messageResult.setResult(false);

            log.error(ex.getMessage(),ex);
        }

        return messageResult;
    }


    @PostMapping("listByPersonIdFourteenDays")
    @ApiOperation(value="查询个人用户14天内的日志台账")
    @ApiImplicitParams({
            @ApiImplicitParam(name="token",value = "令牌",required = true,paramType = "form"),
            @ApiImplicitParam(name="subject",value = "目标(不传)",paramType = "form")
    })
    public MessageResult<List> listByPersonIdFourteenDays(String token,@RequestAttribute String subject){
        MessageResult<List> messageResult = new MessageResult<>();

        try {
            Date now = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String endDate = sdf.format(now);
            Calendar rightNow = Calendar.getInstance();
            rightNow.setTime(now);
            rightNow.add(Calendar.DATE, -14);
            Date dt1 = rightNow.getTime();
            String startDate = sdf.format(dt1);

            PersonInfo person = personInfoService.get(Long.valueOf(subject));

            List<PersonDeviceFilterLog> personDeviceLogList = personDeviceFilterLogService.findByPersonAndDate(person.getId(),startDate,endDate);

            messageResult.setData(personDeviceLogList);
            messageResult.setResult(true);
        }
        catch (Exception ex){
            messageResult.setMessage(ex.getMessage());
            messageResult.setResult(false);
        }

        return messageResult;
    }


    @ApiOperation(value="移动端台账日志列表")
    @RequestMapping(value = "pageList",method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="token",value = "令牌",required = true,paramType = "form"),
            @ApiImplicitParam(name="subject",value = "目标(不传)",paramType = "form"),
            @ApiImplicitParam(name="startTime",value = "开始时间",required = true,paramType = "form"),
            @ApiImplicitParam(name="endTime",value = "结束时间",required = true,paramType = "form"),
            @ApiImplicitParam(name="fever",value = "0/1(正常/异常)",required = false,paramType = "form"),
            @ApiImplicitParam(name="personId",value = "用户id",required = false,paramType = "form"),
    })

    public MessageResult<Map> pageList(
            String token,
            @RequestParam(value="pageIndex",defaultValue="1") int pageIndex,
            @RequestParam(value="pageSize",defaultValue="20") int pageSize,
            @RequestAttribute String subject,String startTime,String endTime,String fever,String personId){

        //当前用户ID
        System.out.println(subject);

        MessageResult<Map> msgResult = new MessageResult<>();

        Map<String,Object> searchParams = new HashMap<>();

        List<Sort> sortList = new ArrayList<>();
        sortList.add(new Sort("a.record_time","desc"));

        PersonInfo person = personInfoService.get(Long.valueOf(subject));
        Long id = person.getId();
        if (org.apache.commons.lang3.StringUtils.isNotBlank(personId)){
            id = Long.valueOf(personId);
        }

        if (StringUtils.isNotBlank(fever) && "1".equals(fever)){
            searchParams.put("fever",true);
        }
        if (StringUtils.isNotBlank(fever) && "0".equals(fever)){
            searchParams.put("fever",false);
        }

        searchParams.put("personId",id);
        searchParams.put("temperatureMax",temperatureConfig.getMax());
        searchParams.put("beginTime",DateUtil.beginOfDay(DateUtil.parse(startTime)));
        searchParams.put("endTime",DateUtil.endOfDay(DateUtil.parse(endTime)));

        Page<PersonDeviceFilterLog> page = personDeviceFilterLogService.pageSearch(searchParams,pageIndex,pageSize,true,sortList);

        msgResult.setResult(true);
        msgResult.setData(PojoUtils.pageWrapper(page));

        return msgResult;
    }

    @ApiOperation(value="体温台账饼图统计")
    @RequestMapping(value = "temperaturePieChart",method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="startTime",value = "开始时间(格式：yyyy-MM-dd)",paramType = "form"),
            @ApiImplicitParam(name="endTime",value = "截止时间(格式：yyyy-MM-dd)",paramType = "form"),
            @ApiImplicitParam(name="token",value = "令牌",required = true,paramType = "form"),
            @ApiImplicitParam(name="subject",value = "目标(不传)",paramType = "form")
    })
    public MessageResult<List<Map>> temperaturePieChart(
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date startTime,
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date endTime,
            String token, @RequestAttribute String subject){
        MessageResult<List<Map>> msgResult = new MessageResult<>();
        List<Map> listMap = new ArrayList<>();
        try{
            PersonInfo personInfo = personInfoService.get(Long.valueOf(subject));
            CompanyInfo companyInfo = companyInfoService.get(personInfo.getCompanyId());

            if (startTime==null){
                startTime = DateTime.now().plusDays(-14).toDate();
            }

            if (endTime==null){
                endTime = DateTime.now().plusDays(1).toDate();
            }
            else{
                endTime = new DateTime(endTime).plusDays(1).toDate();
            }

            long normalCount = personDeviceFilterLogService.countByTimeRangeAndCompanyCode(companyInfo.getCode() + "%",personInfo.getId(),
                    1,temperatureConfig.getMax(),startTime,endTime);

            long abnormalCount = personDeviceFilterLogService.countByTimeRangeAndCompanyCode(companyInfo.getCode() + "%",personInfo.getId(),
                    -1,temperatureConfig.getMax(),startTime,endTime);

            List<PersonCompany> personCompanyList = personCompanyService.findByPersonId(personInfo.getId());

            long undetectedCount = personDeviceFilterLogService.countUndetectedByCompanyCode(companyInfo.getCode() + "%",personCompanyList,
                    startTime,endTime);

            Map<String,Object> map1 = new HashMap();

            map1.put("name","体温正常");
            map1.put("value",normalCount);

            listMap.add(map1);

            Map<String,Object> map2 = new HashMap();

            map2.put("name","体温异常");
            map2.put("value",abnormalCount);

            listMap.add(map2);

            Map<String,Object> map3 = new HashMap();

            map3.put("name","未测量体温");
            map3.put("value",undetectedCount);

            listMap.add(map3);

            msgResult.setResult(true);
            msgResult.setData(listMap);
        }
        catch (Exception ex){
            msgResult.setMessage(ex.getMessage());
            msgResult.setResult(false);
        }

        return msgResult;
    }


    @ApiOperation(value="体温台账统计")
    @RequestMapping(value = "temperatureStatistics",method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="startTime",value = "开始时间(格式：yyyy-MM-dd)",paramType = "form"),
            @ApiImplicitParam(name="endTime",value = "截止时间(格式：yyyy-MM-dd)",paramType = "form"),
            @ApiImplicitParam(name="token",value = "令牌",required = true,paramType = "form"),
            @ApiImplicitParam(name="subject",value = "目标(不传)",paramType = "form")
    })
    public MessageResult<List<Map>> temperatureStatistics(
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date startTime,
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date endTime,
            String token, @RequestAttribute String subject){
        MessageResult<List<Map>> msgResult = new MessageResult<>();
        List<Map> listMap = new ArrayList<>();

        try{
            PersonInfo personInfo = personInfoService.get(Long.valueOf(subject));
            CompanyInfo companyInfo = companyInfoService.get(personInfo.getCompanyId());

            if (startTime==null){
                startTime = DateTime.now().plusDays(-14).toDate();
            }

            if (endTime==null){
                endTime = DateTime.now().plusDays(1).toDate();
            }
            else{
                endTime = new DateTime(endTime).plusDays(1).toDate();
            }

            long detected = personDeviceFilterLogService.countByTimeRangeAndCompanyCode(companyInfo.getCode() + "%",personInfo.getId(),
                    0,temperatureConfig.getMax(),startTime,endTime);

            Map map = new HashMap();
            map.put("detected",detected);

            long companyCount = companyInfoService.countByCompanyCode(companyInfo.getCode() + "%",personInfo.getId());
            map.put("companyCount",companyCount);

            long personCount = personInfoService.countByCompanyCode(companyInfo.getCode() + "%",personInfo.getId());
            map.put("personCount",personCount);

            listMap.add(map);

            msgResult.setResult(true);
            msgResult.setData(listMap);

        }
        catch (Exception ex){
            msgResult.setMessage(ex.getMessage());
            msgResult.setResult(false);
        }

        return msgResult;
    }


    @ApiOperation(value="异常统计")
    @RequestMapping(value = "unusualStatistics",method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="startTime",value = "开始时间(格式：yyyy-MM-dd)",paramType = "form"),
            @ApiImplicitParam(name="endTime",value = "截止时间(格式：yyyy-MM-dd)",paramType = "form"),
            @ApiImplicitParam(name="token",value = "令牌",required = true,paramType = "form"),
            @ApiImplicitParam(name="subject",value = "目标(不传)",paramType = "form")
    })
    public MessageResult<Map<String, Object>> unusualStatistics(
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date startTime,
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date endTime,
            String token, @RequestAttribute String subject) {
        MessageResult<Map<String, Object>> msgResult = new MessageResult<>();

        Map<String, Object> map = new HashMap<>();

        try{
            PersonInfo personInfo = personInfoService.get(Long.valueOf(subject));
            CompanyInfo companyInfo = companyInfoService.get(personInfo.getCompanyId());

            String startDate = "";
            String endDate = "";

            //37度以上为异常体温
            BigDecimal standard = temperatureConfig.getMax();

            if (startTime==null){
                startTime = DateTime.now().plusDays(-14).toDate();
            }

            if (endTime==null){
                endTime = DateTime.now().plusDays(1).toDate();
            }
            else{
                endTime = new DateTime(endTime).plusDays(1).toDate();
            }

            List<Map<String, Object>> mapList = personDeviceFilterLogService.unusualStatistics(companyInfo.getCode() + "%",personInfo.getId(),standard,startTime,endTime);
            List<Map<String, Object>> list = new ArrayList<>();

            int companyTotalCount = 0;
            int personTotalCount = 0;

            for (Map<String, Object> curMap:mapList) {
                if(curMap.get("name")!=null){
                    list.add(curMap);
                    companyTotalCount++;

                    if(curMap.get("personCount")!=null){
                        String personCountStr = curMap.get("personCount").toString();
                        if(StringUtil.isNotEmpty(personCountStr)){
                            personTotalCount = personTotalCount + Integer.parseInt(personCountStr);
                        }
                    }
                }
            }

            List<PersonCompany> personCompanyList = personCompanyService.findByPersonId(personInfo.getId());
            List<String> companyIds = personCompanyList.stream().map(PersonCompany::getCompanyId).collect(Collectors.toList());
            List<CompanyInfo> companyInfoList = companyInfoService.findByCompanyCode(companyInfo.getCode(),null);
            if (companyInfoList.size()>0){
                for (CompanyInfo companyInfo1:companyInfoList){
                    if (!companyIds.contains(companyInfo1.getId())){
                        companyIds.add(companyInfo1.getId());
                    }
                }
            }




            long detectedCount = personDeviceFilterLogService.countDetectedByCompanyIds(companyIds,startTime,endTime);
            long peronNumCompany = personInfoService.countByCompanyIds(companyIds);

            long undetectedCount = peronNumCompany - detectedCount;




       //     long undetectedCount = personDeviceFilterLogService.countUndetectedByCompanyCode(companyInfo.getCode() + "%",personCompanyList,startTime,endTime);

            map.put("companyTotalCount",companyTotalCount);
            map.put("personTotalCount",personTotalCount);
            map.put("undetectedCount",undetectedCount);

            map.put("list",list);

            msgResult.setResult(true);
            msgResult.setData(map);
        }
        catch (Exception ex){
            msgResult.setMessage(ex.getMessage());
            msgResult.setResult(false);

            log.error(ex.getMessage(),ex);
        }

        return msgResult;
    }


    @ApiOperation(value="未测温人员列表")
    @RequestMapping(value = "undetectedPersonList",method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="startTime",value = "开始时间(格式：yyyy-MM-dd)",paramType = "form"),
            @ApiImplicitParam(name="endTime",value = "截止时间(格式：yyyy-MM-dd)",paramType = "form"),
            @ApiImplicitParam(name="token",value = "令牌",required = true,paramType = "form"),
            @ApiImplicitParam(name="subject",value = "目标(不传)",paramType = "form")
    })
    public MessageResult<Map> undetectedPersonList(
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date startTime,
            @DateTimeFormat(pattern = "yyyy-MM-dd") Date endTime,
            @RequestParam(value="pageIndex",defaultValue="1") int pageIndex,
            @RequestParam(value="pageSize",defaultValue="20") int pageSize,
            String token,
            @RequestAttribute String subject){
        MessageResult<Map> msgResult = new MessageResult<>();

        try {
            PersonInfo personInfo = personInfoService.get(Long.valueOf(subject));
            CompanyInfo companyInfo = companyInfoService.get(personInfo.getCompanyId());

            if (startTime==null){
                startTime = DateTime.now().plusDays(-14).toDate();
            }

            if (endTime==null){
                endTime = DateTime.now().plusDays(1).toDate();
            }
            else{
                endTime = new DateTime(endTime).plusDays(1).toDate();
            }

            Map<String,Object> searchParams = new HashMap<>();
    //        searchParams.put("companyCode",companyInfo.getCode() + "%");
//            searchParams.put("personId",personInfo.getId());

            List<PersonCompany> personCompanyList = personCompanyService.findByPersonId(personInfo.getId());

            List<String> companyIds = personCompanyList.stream().map(PersonCompany::getCompanyId).collect(Collectors.toList());
            List<CompanyInfo> companyInfoList = companyInfoService.findByCompanyCode(companyInfo.getCode(),null);
            if (companyInfoList.size()>0){
                for (CompanyInfo companyInfo1:companyInfoList){
                    if (!companyIds.contains(companyInfo1.getId())){
                        companyIds.add(companyInfo1.getId());
                    }
                }
            }



        //    searchParams.put("personCompanyList",personCompanyList);
            searchParams.put("startTime",startTime);
            searchParams.put("endTime",endTime);
            searchParams.put("companyIds",companyIds);

       //     Page<PersonInfo> page = personDeviceFilterLogService.findUndetectedPersonList(searchParams,pageIndex,pageSize,true);
            Page<PersonInfo> page = personDeviceFilterLogService.findUndetectedPersonListByCompanyIds(searchParams,pageIndex,pageSize,true);

            msgResult.setResult(true);
            msgResult.setData(PojoUtils.pageWrapper(page));
        }
        catch (Exception e) {
            log.error(e.getMessage(),e);
            msgResult.setResult(false);
            msgResult.setMessage(e.getMessage());
        }

        return msgResult;
    }


    @ApiOperation(value="获取设备列表")
    @RequestMapping(value = "getDeviceList",method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="token",value = "令牌",required = true,paramType = "form"),
            @ApiImplicitParam(name="subject",value = "目标(不传)",paramType = "form")
    })
    public MessageResult<List<DeviceInfo>> getDeviceList(String token, @RequestAttribute String subject) {
        MessageResult<List<DeviceInfo>> msgResult = new MessageResult<>();

        try{
            PersonInfo person = personInfoService.get(Long.valueOf(subject));

          //  String companyId = person.getCompanyId();

         //   List<DeviceInfo> DeviceInfoList = deviceInfoService.findByCompanyId(companyId);

            List<DeviceInfo> DeviceInfoList = new ArrayList<>();
            List<PersonDeviceRelation> personDeviceRelations = personDeviceRelationService.findByPersonId(person.getId());
            if (personDeviceRelations.size()>0){
                for (PersonDeviceRelation personDeviceRelation : personDeviceRelations){
                    DeviceInfo deviceInfo = deviceInfoService.get(personDeviceRelation.getDeviceId());
                    DeviceInfoList.add(deviceInfo);
                }
            }

            msgResult.setResult(true);
            msgResult.setData(DeviceInfoList);
        }
        catch (Exception ex){
            msgResult.setMessage(ex.getMessage());
            msgResult.setResult(false);
        }

        return msgResult;
    }

    @ApiOperation(value="体温记录")
    @RequestMapping(value = "detail",method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="token",value = "令牌",required = true,paramType = "form"),
            @ApiImplicitParam(name="id",value = "编号",paramType = "form")
    })
    public MessageResult<Object> detail(String id, String token){
        MessageResult<Object> msgResult = new MessageResult<>();

        try {
            PersonDeviceLog personDeviceLog = personDeviceLogService.get(id);

            PersonDeviceLogDTO personDeviceLogDTO = new PersonDeviceLogDTO();

            if (personDeviceLog != null) {
                PojoUtils.map(personDeviceLog, personDeviceLogDTO);

                DeviceInfo deviceInfo = deviceInfoService.getByDeviceNo(personDeviceLog.getDeviceNo());
                PersonInfo personInfo = personInfoService.get(Long.valueOf(personDeviceLog.getPersonId()));

                if (deviceInfo != null) {
                    personDeviceLogDTO.setDeviceName(deviceInfo.getAliasName());
                }

                if (personInfo != null) {
                    personDeviceLogDTO.setPersonName(personInfo.getName());
                }

                if(personDeviceLog.getTemperature().compareTo(temperatureConfig.getMax())>0){
                    personDeviceLogDTO.setFever(true);
                }else {
                    personDeviceLogDTO.setFever(false);
                }

                msgResult.setResult(true);
                msgResult.setData(personDeviceLogDTO);
            }
            else{
                PersonDeviceFilterLog personDeviceFilterLog = personDeviceFilterLogService.get(Long.valueOf(id));

                if(personDeviceFilterLog!=null){
                    PersonDeviceFilterLogDTO personDeviceFilterLogDTO = new PersonDeviceFilterLogDTO();

                    PojoUtils.map(personDeviceFilterLog, personDeviceFilterLogDTO);

                    DeviceInfo deviceInfo = deviceInfoService.getByDeviceNo(personDeviceFilterLog.getDeviceNo());
                    PersonInfo personInfo = personInfoService.get(Long.valueOf(personDeviceFilterLog.getPersonId()));

                    if(deviceInfo != null) {
                        personDeviceFilterLogDTO.setDeviceName(deviceInfo.getAliasName());
                    }

                    if(personInfo != null) {
                        personDeviceFilterLogDTO.setPersonName(personInfo.getName());
                    }

                    if(personDeviceFilterLog.getTemperature().compareTo(temperatureConfig.getMax())>0){
                        personDeviceFilterLogDTO.setFever(true);
                    }else {
                        personDeviceFilterLogDTO.setFever(false);
                    }

                    msgResult.setResult(true);
                    msgResult.setData(personDeviceFilterLogDTO);
                }
                else {
                    msgResult.setResult(false);
                    msgResult.setMessage("数据库不存在该记录!");
                }
            }
        }
        catch(Exception ex){
            log.error(ex.getMessage(),ex);

            msgResult.setResult(false);
            msgResult.setMessage(ex.getMessage());
        }

        return msgResult;
    }
}
