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

import cn.hutool.core.date.DateUtil;
import com.github.pagehelper.Page;
import com.jpsoft.shinestar.config.TemperatureConfig;
import com.jpsoft.shinestar.modules.base.dto.PersonInfoDTO;
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.DES3;
import com.jpsoft.shinestar.modules.common.utils.JwtUtil;
import com.jpsoft.shinestar.modules.common.utils.PojoUtils;
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.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.*;

/**
 * @author 墨鱼_mo
 * @date 2020-4-3 9:33
 * <p>
 * 手机端健康公示
 */
@Slf4j
@RestController
@RequestMapping("/mobile/healthShowApi")
public class HealthShowApiController {

    @Value("${jwt.secret}")
    private String jwtSecret;

    @Autowired
    private CompanyInfoService companyInfoService;

    @Autowired
    private PersonDeviceFilterLogService personDeviceFilterLogService;

    @Autowired
    private PersonInfoService personInfoService;

    @Autowired
    private PersonPopedomService personPopedomService;

    @Autowired
    private PersonDeviceLogService personDeviceLogService;

    @Autowired
    private CompanyDeviceRelationService companyDeviceRelationService;

    @Autowired
    private CheckNumCompanyService checkNumCompanyService;

    @Autowired
    private TotalCheckCompanyService totalCheckCompanyService;

    @Autowired
    private PersonCompanyService personCompanyService;
    @Autowired
    private TemperatureConfig temperatureConfig;
    @ApiOperation(value = "数字数据")
    @RequestMapping(value = "numData", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "令牌", paramType = "query", dataType = "form"),
            @ApiImplicitParam(name = "subject", value = "目标(不传)", paramType = "form")
    })
    public MessageResult<Map> numData(String token, @RequestAttribute String subject) {
        MessageResult<Map> msgResult = new MessageResult<>();

        List<CompanyInfo> list = new ArrayList<>();
        HashMap<String, Object> mapData = new HashMap<>();
        try {
            CompanyInfo companyInfo = companyInfoService.get(subject);

            //当companyInfo为空时，则不是通过微信端入口进入
            if (companyInfo == null) {
                PersonInfo personInfo = personInfoService.get(new Long(subject));
                if (personInfo == null) {
                    throw new Exception("参数异常");
                }

                //个人所在公司
                companyInfo = companyInfoService.get(personInfo.getCompanyId());

                list = companyInfoService.findAllCompanyByCode("%"+companyInfo.getId()+"%");

                //人员包含监管者权限,找出此人所关联的所有公司
                /*if (personInfo.getPopedom().contains("3")) {
                    List<PersonCompany> personCompanyList = personCompanyService.findByPersonId(personInfo.getId());
                    if (personCompanyList.size() > 0) {
                        for (PersonCompany personCompany : personCompanyList) {
                            CompanyInfo companyInfo1 = companyInfoService.get(personCompany.getCompanyId());
                            if (companyInfo1 != null) {
                                list.add(companyInfo1);
                            }
                        }
                    }

                    //如果人员关联的公司不包含自己所在的公司则加入
                    if (!list.contains(companyInfo)) {
                        list.add(companyInfo);
                    }

                }*/


            } else {
             //   list = companyInfoService.findByCompanyCode(companyInfo.getCode() + "%", null);
                list = companyInfoService.findAllCompanyByCode("%"+companyInfo.getId()+"%");
            }


            if (list.size() > 0) {


                List<String> deviceNoList = new ArrayList<>();
                //默认添加一个不存在的设备，以防止公司无设备时返回错误
                deviceNoList.add("1");
                for (CompanyInfo companyInfo1 : list) {
                    List<DeviceInfo> deviceInfoList = companyDeviceRelationService.findDeviceByCompanyId(companyInfo1.getId());
                    for (DeviceInfo deviceInfo : deviceInfoList) {
                        if (!deviceInfo.getDelFlag() && !deviceNoList.contains(deviceInfo.getDeviceNo())) {
                            deviceNoList.add(deviceInfo.getDeviceNo());
                        }
                    }
                }
                Integer personNum = Math.toIntExact(personInfoService.countByCompanyList(list));
                Integer checkedPersonNum = personDeviceFilterLogService.getDayCheckedPersonNumByCompanyList(DateUtil.beginOfDay(new Date()), DateUtil.endOfDay(new Date()), list, null);

                //已测访客数
                Integer checkedVisitorNum = 0;
                if (deviceNoList.size() > 0) {
                    checkedVisitorNum = personDeviceLogService.getDayCheckedVistorNumByDeviceNoList(DateUtil.beginOfDay(new Date()), DateUtil.endOfDay(new Date()), deviceNoList);
                }

                //已测员工人次
                Integer checkPersonTotal = personDeviceLogService.getDayCheckedPersonTotalByCompanyList(DateUtil.beginOfDay(new Date()), DateUtil.endOfDay(new Date()), list, null);


              //  Integer num = checkNumCompanyService.getDayCheckNumByCompanyList(DateUtil.format(new Date(), "yyyy-MM-dd"), list);
              //  Integer totalNum = totalCheckCompanyService.getTotalCheckNum(list);
              //  Integer dayCheckNum = num == null ? 0 : num;

                //当日累计检测数
                //   Integer totalCheckNum = totalNum == null ? dayCheckNum : totalNum + dayCheckNum;
                Integer totalCheckNum = checkPersonTotal + checkedVisitorNum;

                Integer num1 = personDeviceLogService.getDayAbnormalNumByDeviceNoList(DateUtil.beginOfDay(new Date()), new Date(), deviceNoList);
                Integer num2 = personDeviceFilterLogService.getDayAbnormalNumByCompanyList(DateUtil.beginOfDay(new Date()), new Date(), list);
                Integer totalNum2 = totalCheckCompanyService.getTotalAbnormalNumByCompanyList(list);
                Integer dayAbnormalNum = num1+num2;
                Integer totalAbnormalNum =  totalNum2 + dayAbnormalNum;

           //     Integer normalDaysNum = totalCheckCompanyService.findMinNormalDayByCompanyList(list);
                Integer normalDays = 0;
                Date totalCheckCompany = totalCheckCompanyService.findMaxAbnormalTimeByCompanyList(list);
                if (totalCheckCompany == null){
                    normalDays = totalCheckCompanyService.findMaxNormalDayByCompanyList(list);
                }
                else {
                    Long today = DateUtil.beginOfDay(new Date()).getTime();
                    Long abnormalDay = totalCheckCompany.getTime();
                    normalDays = Math.toIntExact((today - abnormalDay) / (1000 * 60 * 60 * 24))-1;
                }


                mapData.put("checkedPersonNum", checkedPersonNum);
                mapData.put("personNum", personNum);
                mapData.put("checkedVisitorNum", checkedVisitorNum);
                mapData.put("totalCheckNum", totalCheckNum);
                mapData.put("dayAbnormalNum", dayAbnormalNum);
                mapData.put("totalAbnormalNum", totalAbnormalNum);
                mapData.put("normalDays", normalDays<0?0:normalDays);

            }
            msgResult.setMessage("查询成功");
            msgResult.setResult(true);
            msgResult.setData(mapData);


        } catch (Exception e) {
            log.error(e.getMessage(), e);
            msgResult.setResult(false);
            msgResult.setMessage(e.getMessage());
        }


        return msgResult;
    }

    @ApiOperation(value = "图片数据")
    @RequestMapping(value = "picData", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "令牌", paramType = "query", dataType = "form"),
            @ApiImplicitParam(name = "subject", value = "目标(不传)", paramType = "form"),
            @ApiImplicitParam(name = "type", value = "员工/访客(person/visitor)", required = true, paramType = "form", dataType = "String"),
            @ApiImplicitParam(name = "filter", value = "全部/正常/异常(0,1,2)[访客记录]", required = true, paramType = "form", dataType = "String"),

    })
    public MessageResult<Map> picData(
            @RequestParam(value = "type", defaultValue = "all") String type,
            @RequestParam(value = "pageIndex", defaultValue = "1") int pageIndex,
            @RequestParam(value = "pageSize", defaultValue = "12") int pageSize,
            @RequestParam(value = "filter", defaultValue = "0") String filter,

            String token, @RequestAttribute String subject) {
        MessageResult<Map> msgResult = new MessageResult<>();

        List<CompanyInfo> companyList = new ArrayList<>();
        HashMap<String, Object> mapData = new HashMap<>();


        try {
            CompanyInfo companyInfo = companyInfoService.get(subject);

            if (companyInfo == null) {
                PersonInfo personInfo = personInfoService.get(new Long(subject));
                if (personInfo == null) {
                    throw new Exception("参数异常");
                }

                //个人所在公司
                CompanyInfo company = companyInfoService.get(personInfo.getCompanyId());

                companyList = companyInfoService.findAllCompanyByCode("%"+company.getId()+"%");

                /*if (personInfo.getPopedom().contains("3")) {
                    List<PersonCompany> personCompanyList = personCompanyService.findByPersonId(personInfo.getId());
                    if (personCompanyList.size() > 0) {
                        for (PersonCompany personCompany : personCompanyList) {
                            CompanyInfo companyInfo1 = companyInfoService.get(personCompany.getCompanyId());
                            if (companyInfo1 != null) {
                                companyList.add(companyInfo1);
                            }
                        }
                    }

                    //如果人员关联的公司不包含自己所在的公司则加入
                    if (!companyList.contains(company)) {
                        companyList.add(company);
                    }
                }*/


            } else {
                companyList = companyInfoService.findByCompanyCode(companyInfo.getCode() + "%", null);
            }

            if (companyList.size() > 0) {
                List<String> deviceNoList = new ArrayList<>();

                //默认添加一个不存在的设备，以防止公司无设备时返回错误
                deviceNoList.add("1");
                for (CompanyInfo companyInfo1 : companyList) {
                    List<DeviceInfo> deviceInfoList = companyDeviceRelationService.findDeviceByCompanyId(companyInfo1.getId());
                    for (DeviceInfo deviceInfo : deviceInfoList) {
                        if (!deviceNoList.contains(deviceInfo.getDeviceNo())) {
                            deviceNoList.add(deviceInfo.getDeviceNo());
                        }
                    }
                }

                Page<PersonDeviceLog> personDeviceLogList = new Page<>();

                if ("all".equals(type)) {
                    personDeviceLogList = personDeviceLogService.findAllPersonLogByCompanyListAndDeviceNoList(DateUtil.beginOfDay(new Date()), DateUtil.endOfDay(new Date()),
                            companyList,deviceNoList, pageIndex, pageSize);
                } else if ("person".equals(type)) {
                    personDeviceLogList = personDeviceLogService.findLastPersonLogByCompanyList(DateUtil.beginOfDay(new Date()), DateUtil.endOfDay(new Date()), companyList, pageIndex, pageSize);
                } else if ("visitor".equals(type)) {
                    if (deviceNoList.size() > 0) {
                       // TemperatureConfig.max
                        BigDecimal max=null;
                        if(!"0".equals(filter)){
                            max= temperatureConfig.getMax();
                        }
                        personDeviceLogList = personDeviceLogService.findVisitorLogByDeviceNoList(DateUtil.beginOfDay(new Date()), DateUtil.endOfDay(new Date()), deviceNoList, pageIndex, pageSize,filter,max);
                    }
                }

                msgResult.setData(PojoUtils.pageWrapper(personDeviceLogList));

            } else {
                msgResult.setData(mapData);
            }

            msgResult.setMessage("查询成功");
            msgResult.setResult(true);

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            msgResult.setResult(false);
            msgResult.setMessage(e.getMessage());
        }


        return msgResult;
    }

    @ApiOperation(value = "学校数字数据")
    @RequestMapping(value = "numDataForSchool", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "令牌", paramType = "query", dataType = "form"),
            @ApiImplicitParam(name = "subject", value = "目标(不传)", paramType = "form")
    })
    public MessageResult<Map> numDataForSchool(String token, @RequestAttribute String subject) {
        MessageResult<Map> msgResult = new MessageResult<>();
        List<CompanyInfo> list = new ArrayList<>();
        HashMap<String, Object> mapData = new HashMap<>();

        try {
            CompanyInfo companyInfo = companyInfoService.get(subject);
            if (companyInfo == null) {
                PersonInfo personInfo = personInfoService.get(new Long(subject));
                if (personInfo == null) {
                    throw new Exception("参数异常");
                }

                //个人所在公司
                 companyInfo = companyInfoService.get(personInfo.getCompanyId());
                if (personInfo.getPopedom().contains("3")) {
                    List<PersonCompany> personCompanyList = personCompanyService.findByPersonId(personInfo.getId());
                    if (personCompanyList.size() > 0) {
                        for (PersonCompany personCompany : personCompanyList) {
                            CompanyInfo companyInfo1 = companyInfoService.get(personCompany.getCompanyId());
                            if (companyInfo1 != null) {
                                list.add(companyInfo1);
                            }
                        }
                    }

                    //如果人员关联的公司不包含自己所在的公司则加入
                    if (!list.contains(companyInfo)) {
                        list.add(companyInfo);
                    }
                }

            } else {
                list = companyInfoService.findByCompanyCode(companyInfo.getCode() + "%", null);
            }

            //      List<CompanyInfo> list = companyInfoService.findByCompanyCode(companyInfo.getCode() + "%", null);

            if (list.size() > 0) {


                List<String> deviceNoList = new ArrayList<>();
                //默认添加一个不存在的设备，以防止公司无设备时返回错误
                deviceNoList.add("1");
                for (CompanyInfo companyInfo1 : list) {
                    List<DeviceInfo> deviceInfoList = companyDeviceRelationService.findDeviceByCompanyId(companyInfo1.getId());
                    for (DeviceInfo deviceInfo : deviceInfoList) {
                        if (!deviceNoList.contains(deviceInfo.getDeviceNo())) {
                            deviceNoList.add(deviceInfo.getDeviceNo());
                        }
                    }
                }
                //应测教职工数
                Integer teacherNum = Math.toIntExact(personInfoService.countByCompanyListAndPopedom("teacher", list));
                //应测学生数
                Integer studentNum = Math.toIntExact(personInfoService.countByCompanyListAndPopedom("student", list));
                //访客人次
                Integer visitorNum = 0;
                if (deviceNoList.size() > 0) {
                    visitorNum = personDeviceLogService.getDayCheckedVistorNumByDeviceNoList(DateUtil.beginOfDay(new Date()), DateUtil.endOfDay(new Date()), deviceNoList);
                }


                //已测教职工数
                Integer checkedTeacherNum = personDeviceFilterLogService.getDayCheckedPersonNumByCompanyList(DateUtil.beginOfDay(new Date()), DateUtil.endOfDay(new Date()), list, "%2%");
                Integer checkedTeacherAndStudentNum = personDeviceFilterLogService.getDayCheckedPersonNumByCompanyList(DateUtil.beginOfDay(new Date()), DateUtil.endOfDay(new Date()), list, "%1%");

                //已测学生数
                Integer checkedStudentNum = checkedTeacherAndStudentNum - checkedTeacherNum;

                Integer num = checkNumCompanyService.getDayCheckNumByCompanyList(DateUtil.format(new Date(), "yyyy-MM-dd"), list);
                Integer totalNum = totalCheckCompanyService.getTotalCheckNum(list);
                Integer dayCheckNum = num == null ? 0 : num;
                Integer totalCheckNum = totalNum == null ? dayCheckNum : totalNum + dayCheckNum;


                Integer num1 = personDeviceLogService.getDayAbnormalNumByDeviceNoList(DateUtil.beginOfDay(new Date()), new Date(), deviceNoList);
                Integer num2 = personDeviceFilterLogService.getDayAbnormalNumByCompanyList(DateUtil.beginOfDay(new Date()), new Date(), list);
                Integer totalNum2 = totalCheckCompanyService.getTotalAbnormalNumByCompanyList(list);
                Integer dayAbnormalNum = num1+num2;
                Integer totalAbnormalNum =  totalNum2 + dayAbnormalNum;


                /*Integer normalDaysNum = totalCheckCompanyService.findMinNormalDayByCompanyList(list);
                //连续无异常天数
                Integer normalDays = normalDaysNum == null ? 0 : normalDaysNum;*/

                Integer normalDays = 0;
                Date totalCheckCompany = totalCheckCompanyService.findMaxAbnormalTimeByCompanyList(list);
                if (totalCheckCompany == null){
                    normalDays = totalCheckCompanyService.findMaxNormalDayByCompanyList(list);
                }
                else {
                    Long today = DateUtil.beginOfDay(new Date()).getTime();
                    Long abnormalDay = totalCheckCompany.getTime();
                    normalDays = Math.toIntExact((today - abnormalDay) / (1000 * 60 * 60 * 24))-1;
                }


                mapData.put("teacherNum", teacherNum);
                mapData.put("studentNum", studentNum);
                mapData.put("visitorNum",visitorNum);
                mapData.put("checkedTeacherNum", checkedTeacherNum);
                mapData.put("checkedStudentNum", checkedStudentNum);
                mapData.put("dayAbnormalNum", dayAbnormalNum);
                mapData.put("totalAbnormalNum", totalAbnormalNum);
                mapData.put("normalDays", normalDays<0?0:normalDays);
                msgResult.setData(mapData);


            } else {
                msgResult.setData(mapData);
            }

            msgResult.setMessage("查询成功");
            msgResult.setResult(true);
            msgResult.setData(mapData);


        } catch (Exception e) {
            log.error(e.getMessage(), e);
            msgResult.setResult(false);
            msgResult.setMessage(e.getMessage());
        }


        return msgResult;
    }

    @ApiOperation(value = "学校图片数据")
    @RequestMapping(value = "picDataForSchool", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "令牌", paramType = "query", dataType = "form"),
            @ApiImplicitParam(name = "subject", value = "目标(不传)", paramType = "form"),
            @ApiImplicitParam(name = "type", value = "老师/学生/访客(teacher/student/visitor)", required = true, paramType = "form", dataType = "String"),

    })
    public MessageResult<Map> picDataForSchool(
            @RequestParam(value = "type", defaultValue = "all") String type,
            @RequestParam(value = "pageIndex", defaultValue = "1") int pageIndex,
            @RequestParam(value = "pageSize", defaultValue = "12") int pageSize,
            String token, @RequestAttribute String subject) {
        MessageResult<Map> msgResult = new MessageResult<>();
        List<CompanyInfo> list = new ArrayList<>();
        HashMap<String, Object> mapData = new HashMap<>();

        try {
            CompanyInfo companyInfo = companyInfoService.get(subject);
            if (companyInfo == null) {
                //       throw new Exception("学校不存在");
                PersonInfo personInfo = personInfoService.get(new Long(subject));
                if (personInfo == null) {
                    throw new Exception("参数异常");
                }

                //个人所在公司
                CompanyInfo company = companyInfoService.get(personInfo.getCompanyId());
                if (personInfo.getPopedom().contains("3")) {
                    List<PersonCompany> personCompanyList = personCompanyService.findByPersonId(personInfo.getId());
                    if (personCompanyList.size() > 0) {
                        for (PersonCompany personCompany : personCompanyList) {
                            CompanyInfo companyInfo1 = companyInfoService.get(personCompany.getCompanyId());
                            if (companyInfo1 != null) {
                                list.add(companyInfo1);
                            }
                        }
                    }

                    //如果人员关联的公司不包含自己所在的公司则加入
                    if (!list.contains(company)) {
                        list.add(company);
                    }
                }

            } else {
                list = companyInfoService.findByCompanyCode(companyInfo.getCode() + "%", null);
            }
            //    List<CompanyInfo> list = companyInfoService.findByCompanyCode(companyInfo.getCode() + "%", null);
            if (list.size() > 0) {


                List<String> deviceNoList = new ArrayList<>();
                //默认添加一个不存在的设备，以防止公司无设备时返回错误
                deviceNoList.add("1");
                for (CompanyInfo companyInfo1 : list) {
                    List<DeviceInfo> deviceInfoList = companyDeviceRelationService.findDeviceByCompanyId(companyInfo1.getId());
                    for (DeviceInfo deviceInfo : deviceInfoList) {
                        if (!deviceNoList.contains(deviceInfo.getDeviceNo())) {
                            deviceNoList.add(deviceInfo.getDeviceNo());
                        }
                    }
                }
                Page<PersonDeviceLog> personDeviceLogList = new Page<>();
                if ("all".equals(type)) {
                    personDeviceLogList = personDeviceLogService.findAllPersonLogByCompanyListAndDeviceNoList(DateUtil.beginOfDay(new Date()), DateUtil.endOfDay(new Date()), list,deviceNoList, pageIndex, pageSize);
                } else if ("teacher".equals(type)) {
                    personDeviceLogList = personDeviceLogService.findLastTeacherLogByCompanyList(DateUtil.beginOfDay(new Date()), DateUtil.endOfDay(new Date()), list, pageIndex, pageSize);
                } else if ("student".equals(type)) {
                    personDeviceLogList = personDeviceLogService.findLastStudentLogByCompanyList(DateUtil.beginOfDay(new Date()), DateUtil.endOfDay(new Date()), list, pageIndex, pageSize);

                }
                else if ("visitor".equals(type)) {
                    if (deviceNoList.size() > 0) {
                        personDeviceLogList = personDeviceLogService.findVisitorLogByDeviceNoList(DateUtil.beginOfDay(new Date()), DateUtil.endOfDay(new Date()), deviceNoList, pageIndex, pageSize);
                    }
                }
                msgResult.setData(PojoUtils.pageWrapper(personDeviceLogList));

            } else {
                msgResult.setData(mapData);
            }
            msgResult.setMessage("查询成功");
            msgResult.setResult(true);


        } catch (Exception e) {
            log.error(e.getMessage(), e);
            msgResult.setResult(false);
            msgResult.setMessage(e.getMessage());
        }


        return msgResult;
    }

    @GetMapping("/getCompanyToken")
    @ApiOperation(value = "根据公司id获取token")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "companyInfoId", paramType = "query", required = true, value = "公司id")
    })
    public MessageResult<Map> getCompanyToken(String companyInfoId, @ApiIgnore HttpSession session) {
        MessageResult<Map> messageResult = new MessageResult<>();

        try {
            CompanyInfo companyInfo = companyInfoService.get(companyInfoId);

            DES3 des3 = new DES3();


            if (companyInfo != null) {

                //生成token
                String token = JwtUtil.createToken(jwtSecret, companyInfoId, DateTime.now().plusHours(6).toDate());

                session.setAttribute("companyToken", token);

                HashMap map = new HashMap();
                map.put("token", token);
                map.put("companyName", companyInfo.getName());
                messageResult.setResult(true);
                messageResult.setData(map);
            } else {
                messageResult.setResult(false);
                messageResult.setMessage("公司不存在！");
            }

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

        return messageResult;
    }

    @GetMapping("healthyCodeStat")
    @ApiOperation(value="健康码统计")
    public MessageResult<List> healthyCodeStat(String token,String companyId,
                                               @RequestParam(defaultValue = "1") String popedom){
        MessageResult<List> messageResult = new MessageResult<>();

        try {
            //todo 填写具体代码
            Map<String,Object> searchParams = new HashMap<>();

            CompanyInfo companyInfo = companyInfoService.get(companyId);

            searchParams.put("companyCode", companyInfo.getCode() + "%");
//            searchParams.put("popedom", popedom);

            List<Map> data = personInfoService.groupByHealthyCode(searchParams);

            //健康码颜色 00绿码 01黄码 10红码 11灰码
            Map<String,Long> healthyCodeMap = new HashMap<>();

            String[] codeArr = new String[]{"00","01","10","11"};

            for (String code : codeArr) {
                healthyCodeMap.put(code, 0L);
            }

            for (Map map : data) {
                String healthyCode = String.valueOf(map.get("healthyCode"));
                Long total = Long.valueOf(map.get("total").toString());

                if (map.get("healthyCode")==null){
                    //健康码为空都算灰码
                    healthyCodeMap.put("11", healthyCodeMap.get("11") + total);
                }
                else{
                    healthyCodeMap.put(healthyCode,total);
                }
            }

            List<Map> mapList = new ArrayList<>();

            for (String code : healthyCodeMap.keySet()) {
                if (StringUtils.isNotEmpty(code)) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("healthyCode", code);
                    map.put("total", healthyCodeMap.get(code));
                    mapList.add(map);
                }
            }

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

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

        return messageResult;
    }

    @PostMapping("healthyCodeStatList")
    @ApiOperation(value="健康码统计列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "令牌", paramType = "query", dataType = "form"),
            @ApiImplicitParam(name = "subject", value = "目标(不传)", paramType = "form"),
            @ApiImplicitParam(name = "name", value = "姓名", required = false, paramType = "form", dataType = "String"),
            @ApiImplicitParam(name = "healthyCode", value = "健康码（00：绿码，01：黄码，10：红码。11：灰码）", required = true, paramType = "form", dataType = "String"),

    })
    public MessageResult<Map> healthyCodeStatList(String token, @RequestAttribute String subject,@RequestParam(value = "pageIndex", defaultValue = "1") int pageIndex,
@RequestParam(value = "pageSize", defaultValue = "10") int pageSize,String name,String healthyCode){
        MessageResult<Map> messageResult = new MessageResult<>();

        try {
            //todo 填写具体代码
            Map<String,Object> searchParams = new HashMap<>();

            PersonInfo personInfo = personInfoService.get(Long.valueOf(subject));
            PersonPopedom personPopedom = personPopedomService.get(personInfo.getPopedom());


            CompanyInfo companyInfo = companyInfoService.get(personPopedom.getCompanyId());

            List<PersonInfoDTO> list = new ArrayList<>();

            List<CompanyInfo> companyInfoList = companyInfoService.findAllCompanyByCode(companyInfo.getCode() + "%");




            searchParams.put("companyList", companyInfoList);
            if (StringUtils.isNotBlank(healthyCode)){
                if ("11".equals(healthyCode)){
                    searchParams.put("nullHealthyCode",healthyCode);
                }else {
                    searchParams.put("healthyCode",healthyCode);
                }

            }
            if (StringUtils.isNotBlank(name)){
                searchParams.put("name","%"+ name +"%");
            }
            List<Sort> sortList = new ArrayList<>();
            sortList.add(new Sort("a.person_id","asc"));

            Page<PersonPopedom> page = personPopedomService.pageSearch2(searchParams,pageIndex,pageSize,true,sortList);
            List<PersonPopedom> personPopedomList = page.getResult();
            if (personPopedomList.size()>0){
                for (PersonPopedom personPopedom1 : personPopedomList){
                    PersonInfoDTO personInfoDTO = new PersonInfoDTO();
                    PersonInfo personInfo1 = personInfoService.get(personPopedom1.getPersonId());
                    BeanUtils.copyProperties(personInfo1,personInfoDTO);
                    list.add(personInfoDTO);
                }
            }





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

            pageMap.put("recordsTotal", page.getTotal());
            pageMap.put("recordsFiltered", page.getTotal());
            pageMap.put("totalPage", page.getPages());
            pageMap.put("pageNumber", page.getPageNum());
            pageMap.put("pageSize", page.getPageSize());
            pageMap.put("data", list);

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

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

        return messageResult;
    }

}
