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

import cn.hutool.core.date.DateUtil;
import com.github.pagehelper.Page;
import com.jpsoft.shinestar.config.OSSConfig;
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.business.dto.HealthyReportNoticeDTO;
import com.jpsoft.shinestar.modules.common.dto.MessageResult;
import com.jpsoft.shinestar.modules.common.utils.OSSUtil;
import com.jpsoft.shinestar.modules.common.utils.PojoUtils;
import com.jpsoft.shinestar.modules.sys.entity.User;
import com.jpsoft.shinestar.modules.sys.service.DataDictionaryService;
import com.jpsoft.shinestar.modules.sys.service.UserService;
import com.jpsoft.shinestar.modules.common.dto.Sort;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.RegionUtil;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/base/personHealthLedger")
@Api(description = "personHealthLedger")
public class PersonHealthLedgerController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private PersonHealthLedgerService personHealthLedgerService;
    @Autowired
    private PersonInfoService personInfoService;
    @Autowired
    private PersonDeviceFilterLogService personDeviceFilterLogService;
    @Autowired
    private CompanyInfoService companyInfoService;
    @Autowired
    private UserService userService;
    @Autowired
    private DataDictionaryService dataDictionaryService;
    @Autowired
    private OSSConfig ossConfig;
    @Autowired
    private TemperatureConfig temperatureConfig;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private CompanySuperviseService companySuperviseService;

    @ApiOperation(value="创建空记录")
    @GetMapping("create")
    public MessageResult<PersonHealthLedger> create(){
        MessageResult<PersonHealthLedger> msgResult = new MessageResult<>();

        PersonHealthLedger personHealthLedger = new PersonHealthLedger();

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

        return msgResult;
    }
    
    @ApiOperation(value="添加信息")
    @PostMapping("add")
    public MessageResult<PersonHealthLedger> add(@RequestBody PersonHealthLedger personHealthLedger,@RequestAttribute String subject){
        MessageResult<PersonHealthLedger> msgResult = new MessageResult<>();

        try {
            personHealthLedger.setId(UUID.randomUUID().toString());
            personHealthLedger.setDelFlag(false);
            personHealthLedger.setCreateBy(subject);
            personHealthLedger.setCreateTime(new Date());
            
            int affectCount = personHealthLedgerService.insert(personHealthLedger);

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(personHealthLedger);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("数据库添加失败");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

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

        return msgResult;
    }

    @ApiOperation(value="获取信息")
    @GetMapping("edit/{id}")
    public MessageResult<PersonHealthLedger> edit(@PathVariable("id") String id){
        MessageResult<PersonHealthLedger> msgResult = new MessageResult<>();

        try {
            PersonHealthLedger personHealthLedger = personHealthLedgerService.get(id);

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

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

        return msgResult;
    }

    @ApiOperation(value="更新用户")
    @PostMapping("update")
    public MessageResult<PersonHealthLedger> update(@RequestBody PersonHealthLedger personHealthLedger,@RequestAttribute String subject){
        MessageResult<PersonHealthLedger> msgResult = new MessageResult<>();

        try {
            personHealthLedger.setUpdateBy(subject);
            personHealthLedger.setUpdateTime(new Date());
            
            int affectCount = personHealthLedgerService.update(personHealthLedger);

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(personHealthLedger);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("数据库更新失败");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

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

        return msgResult;
    }

	@ApiOperation(value="删除")
    @PostMapping("delete/{id}")
    public MessageResult<Integer> delete(@PathVariable("id") String id,@RequestAttribute String subject){
        MessageResult<Integer> msgResult = new MessageResult<>();

        try {
            PersonHealthLedger personHealthLedger = personHealthLedgerService.get(id);
            personHealthLedger.setDelFlag(true);
            personHealthLedger.setUpdateBy(subject);
            personHealthLedger.setUpdateTime(new Date());

            int affectCount = personHealthLedgerService.update(personHealthLedger);

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(affectCount);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("删除失败");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

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

        return msgResult;
    }


    @ApiOperation(value="批量删除")
    @PostMapping("batchDelete")
    public MessageResult<Integer> batchDelete(@RequestBody List<String> idList,@RequestAttribute String subject){
        MessageResult<Integer> msgResult = new MessageResult<>();

        try {
            int affectCount = 0;

            for (String id : idList) {
                PersonHealthLedger personHealthLedger = personHealthLedgerService.get(id);
                personHealthLedger.setDelFlag(true);
                personHealthLedger.setUpdateBy(subject);
                personHealthLedger.setUpdateTime(new Date());

                affectCount += personHealthLedgerService.update(personHealthLedger);
            }

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(affectCount);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("删除失败");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

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

        return msgResult;
    }

    @ApiOperation(value="列表")
    @RequestMapping(value = "pageList",method = RequestMethod.POST)
    public MessageResult<Map> pageList(
            @RequestParam(value="personName",defaultValue="") String personName,
            @RequestParam(value="companyId",defaultValue="") String companyId,
            @RequestParam(value="healthStatus",defaultValue="") String healthStatus,
            @RequestParam(value="subordinate",defaultValue="false")  Boolean subordinate,
            @DateTimeFormat(pattern = "yyyy-MM-dd")String queryTime,
            @RequestParam(value="pageIndex",defaultValue="1") int pageIndex,
            @RequestParam(value="pageSize",defaultValue="20") int pageSize,
            @RequestAttribute String subject){

        //当前用户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("b.sort_no","asc"));
        sortList.add(new Sort("a.id_","asc"));

        if (StringUtils.isNotEmpty(personName)) {
            searchParams.put("name","%" + personName + "%");
        }

        if (StringUtils.isNotEmpty(healthStatus)) {
            searchParams.put("healthStatus",healthStatus);
        }

        try {
            if (StringUtils.isNotEmpty(queryTime)) {

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date startTime = sdf.parse(queryTime);
                Date endTime = new DateTime(startTime).plusDays(1).toDate();

                searchParams.put("startTime",startTime);
                searchParams.put("endTime",endTime);
            }
        }catch (Exception e){

        }

        //当前用户ID
        if (StringUtils.isEmpty(companyId)){
            User user = userService.get(subject);
            CompanyInfo companyInfo = companyInfoService.get(user.getCompanyId());
            if (!userService.hasRole(subject,"SYSADMIN")) {
                searchParams.put("companyCode", companyInfo.getCode() + "%");
            }
        }
        else{
            CompanyInfo companyInfo = companyInfoService.get(companyId);
            if(subordinate){
                searchParams.put("companyCode", companyInfo.getCode() + "%");
            }
            else {
                searchParams.put("companyCode", companyInfo.getCode());
            }
        }

        searchParams.put("status", "1");//审批状态通过

        //先查人员
        Page<PersonInfo> personInfoPage = personInfoService.pageSearch(searchParams,pageIndex,pageSize,true,sortList);
        Page<PersonInfoDTO> pageDTO = PojoUtils.convertPage(personInfoPage, PersonInfoDTO.class);
        //再查健康报告
        for(PersonInfoDTO personInfoDTO : pageDTO){
            List<PersonHealthLedger> phlList = personHealthLedgerService.findByTimeAndPersonId(queryTime,personInfoDTO.getId(),null,null,null);
            if(phlList.size() > 0){
                PersonHealthLedger phl = phlList.get(0);
                String healthStatusN = dataDictionaryService.findNameByCatalogNameAndValue("健康情况",phl.getHealthStatus());
                phl.setHealthStatusN(healthStatusN);

                String familyStatusN = dataDictionaryService.findNameByCatalogNameAndValue("健康情况",phl.getFamilyStatus());
                phl.setFamilyStatusN(familyStatusN);

                personInfoDTO.setIsUpHealth(true);
                personInfoDTO.setPersonHealthLedger(phl);
            }else{
                personInfoDTO.setIsUpHealth(false);
            }
        }

//        Page<PersonHealthLedger> page = personHealthLedgerService.pageSearch(searchParams,pageIndex,pageSize,true,sortList);
//        for(PersonHealthLedger phl : page.getResult()){
//            PersonInfo personInfo = personInfoService.get(phl.getPersonId());
//            phl.setPersonInfo(personInfo);
//
//            String healthStatusN = dataDictionaryService.findNameByCatalogNameAndValue("健康情况",phl.getHealthStatus());
//            phl.setHealthStatusN(healthStatusN);
//
//            String familyStatusN = dataDictionaryService.findNameByCatalogNameAndValue("健康情况",phl.getFamilyStatus());
//            phl.setFamilyStatusN(familyStatusN);
//        }

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

        return msgResult;
    }

    @ApiOperation(value="列表")
    @RequestMapping(value = "pageListNew",method = RequestMethod.POST)
    public MessageResult<Map> pageListNew(
            @RequestParam(value="personName",defaultValue="") String personName,
            @RequestParam(value="companyId",defaultValue="") String companyId,
            @RequestParam(value="subordinate",defaultValue="false")  Boolean subordinate,
            @DateTimeFormat(pattern = "yyyy-MM-dd")String queryTime,
            @RequestParam(value="address",defaultValue="") String address,
            @RequestParam(value="fever",defaultValue="")  Boolean fever,
            @RequestParam(value="isReport",defaultValue="")  String isReport,
            @RequestParam(value="pageIndex",defaultValue="1") int pageIndex,
            @RequestParam(value="pageSize",defaultValue="20") int pageSize,
            @RequestAttribute String subject){

        //当前用户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("b.sort_no","asc"));
        sortList.add(new Sort("a.id_","asc"));

        if (StringUtils.isNotEmpty(personName)) {
            searchParams.put("name","%" + personName + "%");
        }

        //当前用户ID
        if (StringUtils.isEmpty(companyId)){
            User user = userService.get(subject);
            CompanyInfo companyInfo = companyInfoService.get(user.getCompanyId());
            if (!userService.hasRole(subject,"SYSADMIN")) {
                searchParams.put("companyCode", companyInfo.getCode() + "%");
            }
        }
        else{
            CompanyInfo companyInfo = companyInfoService.get(companyId);
            if(subordinate){
                searchParams.put("companyCode", companyInfo.getCode() + "%");
            }
            else {
                searchParams.put("companyCode", companyInfo.getCode());
            }
        }

        if (StringUtils.isNotEmpty(queryTime)) {
            searchParams.put("queryTime",queryTime);
        }

        String addressOut = null;
        String addressIn = null;
        String temperature = null;
        if(StringUtils.isNotEmpty(address)){
            isReport = "1";
            if("0".equals(address)){
                addressIn = "%荆州市%";
                searchParams.put("addressIn",addressIn);
            }
            if("1".equals(address)){
                addressOut = "%荆州市%";
                addressIn = "%湖北省%";
                searchParams.put("addressOut",addressOut);
                searchParams.put("addressIn",addressIn);
            }
            if("2".equals(address)){
                addressOut = "%湖北省%";
                searchParams.put("addressOut",addressOut);
            }
        }

        if(fever){
            isReport = "1";
            temperature = temperatureConfig.getMax().toString();
            searchParams.put("temperature",temperature);
        }

        searchParams.put("isReport",isReport);

        Page<PersonInfo> personInfoPage = personInfoService.pageSearchNew(searchParams,pageIndex,pageSize,true,sortList);
        Page<PersonInfoDTO> pageDTO = PojoUtils.convertPage(personInfoPage, PersonInfoDTO.class);
        for(PersonInfoDTO personInfoDTO : pageDTO.getResult()){
            List<PersonHealthLedger> phlList = personHealthLedgerService.findByTimeAndPersonId(queryTime,personInfoDTO.getId(),addressOut,addressIn,temperature);
            if(phlList.size() > 0){
                PersonHealthLedger phl = phlList.get(0);
                String healthStatusN = dataDictionaryService.findNameByCatalogNameAndValue("健康情况",phl.getHealthStatus());
                phl.setHealthStatusN(healthStatusN);

                String familyStatusN = dataDictionaryService.findNameByCatalogNameAndValue("健康情况",phl.getFamilyStatus());
                phl.setFamilyStatusN(familyStatusN);

                personInfoDTO.setIsUpHealth(true);
                personInfoDTO.setPersonHealthLedger(phl);
            }else{
                personInfoDTO.setIsUpHealth(false);
            }
        }

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

        return msgResult;
    }

    @ApiOperation(value="导出考勤报表")
    @RequestMapping(value = "exportXls",method = RequestMethod.POST)
    public MessageResult<String> exportXls(
            @RequestParam(value="personName",defaultValue="") String personName,
            @RequestParam(value="companyId",defaultValue="") String companyId,
            @RequestParam(value="subordinate",defaultValue="false")  Boolean subordinate,
            @DateTimeFormat(pattern = "yyyy-MM-dd")String queryTime,
            @RequestAttribute String subject) throws Exception {
        MessageResult<String> msgResult = new MessageResult<>();

        try {
            List<Sort> sortList = new ArrayList<>();
            sortList.add(new Sort("b.sort_no","asc"));
            sortList.add(new Sort("a.id_","asc"));

            Map<String,Object> searchParams = new HashMap<>();
            if (StringUtils.isNotEmpty(personName)) {
                searchParams.put("name","%" + personName + "%");
            }

//            if (StringUtils.isNotEmpty(healthStatus)) {
//                searchParams.put("healthStatus",healthStatus);
//            }

            if (StringUtils.isNotEmpty(queryTime)) {
                //searchParams.put("queryTime",queryTime);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date startTime = sdf.parse(queryTime);
                Date endTime = new DateTime(startTime).plusDays(1).toDate();

                searchParams.put("startTime",startTime);
                searchParams.put("endTime",endTime);
            }
            CompanyInfo companyInfo = null;
            //当前用户ID
            if (StringUtils.isEmpty(companyId)){
                User user = userService.get(subject);
                companyInfo = companyInfoService.get(user.getCompanyId());
                if (!userService.hasRole(subject,"SYSADMIN")) {
                    searchParams.put("companyCode", companyInfo.getCode() + "%");
                }
            }
            else{
                companyInfo = companyInfoService.get(companyId);
                if(subordinate){
                    searchParams.put("companyCode", companyInfo.getCode() + "%");
                }
                else {
                    searchParams.put("companyCode", companyInfo.getCode());
                }
            }

            String[] companyCodes = companyInfo.getCode().split(",");
            String schoolTitle = companyInfo.getName();

            //学生比老师少一列
            int num = 0;
            String xlsPath = "static/personHealthLedger.xlsx";

            searchParams.put("status", "1");//审批状态通过

            //先查人员
            Page<PersonInfo> personInfoPage = personInfoService.pageSearch(searchParams,1,100000,false,sortList);
            Page<PersonInfoDTO> pageDTO = PojoUtils.convertPage(personInfoPage, PersonInfoDTO.class);

            //Page<PersonHealthLedger> personHealthLedgerList = personHealthLedgerService.pageSearch(searchParams,1,100000,true,sortList);
            ClassPathResource resource = new ClassPathResource(xlsPath);

            Workbook wb = WorkbookFactory.create(resource.getInputStream());

            Sheet sheet = wb.getSheetAt(0);

            Row row1 = sheet.getRow(0);
            Row row2 = sheet.getRow(1);

            String title = row1.getCell(0).getStringCellValue();
            String subTitle = row2.getCell(0).getStringCellValue();

            row1.getCell(0).setCellValue(String.format(title, schoolTitle));

            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");//注意月份是MM
            Date queryDate = simpleDateFormat.parse(queryTime);
            SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy年MM月dd日");//注意月份是MM
            String dateTime = sdf2.format(queryDate);
            if(num < 1) {
                row2.getCell(0).setCellValue(String.format(subTitle, companyInfo.getName(), dateTime));
            }else{
                row2.getCell(0).setCellValue(String.format(subTitle, dateTime));
            }

            int startRowIndex = 3;

            for (int i = 0; i < pageDTO.size(); i++) {
                Row row = sheet.createRow(startRowIndex + i);
                PersonInfoDTO personInfoDTO = pageDTO.get(i);
                List<PersonHealthLedger> phlList = personHealthLedgerService.findByTimeAndPersonId(queryTime,personInfoDTO.getId(),null,null,null);

                Boolean isUpHealth = false;
                String healthStatusN = "";
                String familyStatusN = "";
                PersonHealthLedger phl = null;

                String name = (String) personInfoDTO.getName();
                String _className = personInfoDTO.getCompanyName();
                String _temperature = "";
                String _healthStatusN = "未提交";
                String _familyStatus = "";
                String _isTouch = "";
                String _isGoto = "";
                String _address = "";
                String remark = "";

                if(phlList.size() > 0){
                    phl = phlList.get(0);
                    healthStatusN = dataDictionaryService.findNameByCatalogNameAndValue("健康情况",phl.getHealthStatus());

                    familyStatusN = dataDictionaryService.findNameByCatalogNameAndValue("健康情况",phl.getFamilyStatus());

                    //学生姓名 自身状况 家庭健康情况 假期是否曾前往重点疫区 是否接触重点疫区高危人员 备注

                    _healthStatusN = (String) healthStatusN;
                    _temperature = phl.getTemperature().toString();
                    _familyStatus = (String) familyStatusN;
                    _isTouch = phl.getIsTouch()  ? "是":"否";
                    _isGoto = phl.getIsGoto()  ? "是":"否";
                    _address = phl.getAddress();
                    remark = (String) phl.getRemark();
                    isUpHealth = true;
                }else{
                    isUpHealth = false;
                }


                //学生姓名 自身状况 家庭健康情况 假期是否曾前往重点疫区 是否接触重点疫区高危人员 备注
                row.createCell(0).setCellValue(name);

                if(num < 1) {
                    row.createCell(1).setCellValue(_className);
                }

                row.createCell(2 - num).setCellValue(_healthStatusN);

                row.createCell(3 - num).setCellValue(_temperature);

                row.createCell(4 - num).setCellValue(_familyStatus);

                row.createCell(5 - num).setCellValue(_isGoto);

                row.createCell(6 - num).setCellValue(_isTouch);

                row.createCell(7 - num).setCellValue(_address);

                row.createCell(8 - num).setCellValue(remark);

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

            CellStyle cellStyle1 = createCellStyle(wb);

            for (int i = 0; i < pageDTO.size(); i++) {
                Row row = sheet.getRow(startRowIndex + i);

                if (row != null) {
                    for (int j = 0; j < row.getLastCellNum(); j++) {
                        if (row.getCell(j) != null) {
                            row.getCell(j).setCellStyle(cellStyle1);
                        }
                    }
                }
            }

            //todo 将wb保存到oss
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            wb.write(output);

            byte[] buffer = output.toByteArray();
            ByteArrayInputStream input = new ByteArrayInputStream(buffer);

            String fileName = "健康打卡情况.xlsx";

            String downloadUrl = OSSUtil.upload(ossConfig, "personHealthLedger", fileName, input);

            wb.write(output);
            wb.close();
            output.close();

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

        return msgResult;
    }

    private CellStyle createCellStyle(Workbook wb){
        CellStyle cellStyle = wb.createCellStyle();

        cellStyle.setBorderTop(BorderStyle.THIN);
        cellStyle.setBorderBottom(BorderStyle.THIN);
        cellStyle.setBorderLeft(BorderStyle.THIN);
        cellStyle.setBorderRight(BorderStyle.THIN);
        cellStyle.setWrapText(true);
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);

        return cellStyle;
    }


    @ApiOperation(value="列表-测温和上报")
    @RequestMapping(value = "pageListAll",method = RequestMethod.POST)
    public MessageResult<Map> pageListAll(
            @RequestParam(value="personName",defaultValue="") String personName,
            @RequestParam(value="companyId",defaultValue="") String companyId,
            @RequestParam(value="healthStatus",defaultValue="") String healthStatus,
            @RequestParam(value="subordinate",defaultValue="false")  Boolean subordinate,
            @DateTimeFormat(pattern = "yyyy-MM-dd")String queryTime,
            @RequestParam(value="pageIndex",defaultValue="1") int pageIndex,
            @RequestParam(value="pageSize",defaultValue="20") int pageSize,
            @RequestAttribute String subject){

        //当前用户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("b.sort_no","asc"));
        sortList.add(new Sort("a.id_","asc"));

        if (StringUtils.isNotEmpty(personName)) {
            searchParams.put("name","%" + personName + "%");
        }

        if (StringUtils.isNotEmpty(healthStatus)) {
            searchParams.put("healthStatus",healthStatus);
        }
        try {
            if (StringUtils.isNotEmpty(queryTime)) {
                //searchParams.put("queryTime",queryTime);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date startTime = sdf.parse(queryTime);
                Date endTime = new DateTime(startTime).plusDays(1).toDate();

                searchParams.put("startTime",startTime);
                searchParams.put("endTime",endTime);
            }
        }catch (Exception e){

        }


        //当前用户ID
        if (StringUtils.isEmpty(companyId)){
            User user = userService.get(subject);
            CompanyInfo companyInfo = companyInfoService.get(user.getCompanyId());
            if (!userService.hasRole(subject,"SYSADMIN")) {
                searchParams.put("companyCode", companyInfo.getCode() + "%");
            }
        }
        else{
            CompanyInfo companyInfo = companyInfoService.get(companyId);
            if(subordinate){
                searchParams.put("companyCode", companyInfo.getCode() + "%");
            }
            else {
                searchParams.put("companyCode", companyInfo.getCode());
            }
        }

        searchParams.put("status", "1");//审批状态通过

        //先查人员
        Page<PersonInfo> personInfoPage = personInfoService.pageSearch(searchParams,pageIndex,pageSize,true,sortList);
        Page<PersonInfoDTO> pageDTO = PojoUtils.convertPage(personInfoPage, PersonInfoDTO.class);
        //再查健康报告
        for(PersonInfoDTO personInfoDTO : pageDTO){
            List<PersonHealthLedger> phlList = personHealthLedgerService.findByTimeAndPersonId(queryTime,personInfoDTO.getId(),null,null,null);
            if(phlList.size() > 0){
                PersonHealthLedger phl = phlList.get(0);
                String healthStatusN = dataDictionaryService.findNameByCatalogNameAndValue("健康情况",phl.getHealthStatus());
                phl.setHealthStatusN(healthStatusN);

                String familyStatusN = dataDictionaryService.findNameByCatalogNameAndValue("健康情况",phl.getFamilyStatus());
                phl.setFamilyStatusN(familyStatusN);

                personInfoDTO.setIsUpHealth(true);
                personInfoDTO.setPersonHealthLedger(phl);
            }else{
                //查体温上报
                List<PersonDeviceFilterLog> pdflList = personDeviceFilterLogService.findByTimeAndPersonId(queryTime,personInfoDTO.getId());
                if(pdflList.size() > 0){
                    PersonDeviceFilterLog pdfl = pdflList.get(0);
                    PersonHealthLedger phl = new PersonHealthLedger();

                    phl.setTemperature(pdfl.getTemperature());
                    phl.setCreateTime(pdfl.getCreateTime());
                    phl.setHealthStatusN("设备测温");
                    personInfoDTO.setIsUpHealth(true);
                    personInfoDTO.setPersonHealthLedger(phl);
                }else{
                    personInfoDTO.setIsUpHealth(false);
                }
            }
        }

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

        return msgResult;
    }

    @ApiOperation(value="导出考勤报表-测温和上报")
    @RequestMapping(value = "exportXlsAll",method = RequestMethod.POST)
    public MessageResult<String> exportXlsAll(
            @RequestParam(value="personName",defaultValue="") String personName,
            @RequestParam(value="companyId",defaultValue="") String companyId,
            @RequestParam(value="subordinate",defaultValue="false")  Boolean subordinate,
            @DateTimeFormat(pattern = "yyyy-MM-dd")String queryTime,
            @RequestAttribute String subject) throws Exception {
        MessageResult<String> msgResult = new MessageResult<>();

        try {
            List<Sort> sortList = new ArrayList<>();
            sortList.add(new Sort("b.sort_no","asc"));
            sortList.add(new Sort("a.id_","asc"));

            Map<String,Object> searchParams = new HashMap<>();
            if (StringUtils.isNotEmpty(personName)) {
                searchParams.put("name","%" + personName + "%");
            }

//            if (StringUtils.isNotEmpty(healthStatus)) {
//                searchParams.put("healthStatus",healthStatus);
//            }

            if (StringUtils.isNotEmpty(queryTime)) {
                //searchParams.put("queryTime",queryTime);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date startTime = sdf.parse(queryTime);
                Date endTime = new DateTime(startTime).plusDays(1).toDate();

                searchParams.put("startTime",startTime);
                searchParams.put("endTime",endTime);
            }
            CompanyInfo companyInfo = null;
            //当前用户ID
            if (StringUtils.isEmpty(companyId)){
                User user = userService.get(subject);
                companyInfo = companyInfoService.get(user.getCompanyId());
                if (!userService.hasRole(subject,"SYSADMIN")) {
                    searchParams.put("companyCode", companyInfo.getCode() + "%");
                }
            }
            else{
                companyInfo = companyInfoService.get(companyId);
                if(subordinate){
                    searchParams.put("companyCode", companyInfo.getCode() + "%");
                }
                else {
                    searchParams.put("companyCode", companyInfo.getCode());
                }
            }

            String[] companyCodes = companyInfo.getCode().split(",");
            String schoolTitle = companyInfo.getName();


            //学生比老师少一列
            int num = 0;
            String xlsPath = "static/personHealthLedger.xlsx";
            searchParams.put("status", "1");//审批状态通过

            //先查人员
            Page<PersonInfo> personInfoPage = personInfoService.pageSearch(searchParams,1,100000,false,sortList);
            Page<PersonInfoDTO> pageDTO = PojoUtils.convertPage(personInfoPage, PersonInfoDTO.class);

            //Page<PersonHealthLedger> personHealthLedgerList = personHealthLedgerService.pageSearch(searchParams,1,100000,true,sortList);
            ClassPathResource resource = new ClassPathResource(xlsPath);

            Workbook wb = WorkbookFactory.create(resource.getInputStream());

            Sheet sheet = wb.getSheetAt(0);

            Row row1 = sheet.getRow(0);
            Row row2 = sheet.getRow(1);

            String title = row1.getCell(0).getStringCellValue();
            String subTitle = row2.getCell(0).getStringCellValue();

            row1.getCell(0).setCellValue(String.format(title, schoolTitle));

            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");//注意月份是MM
            Date queryDate = simpleDateFormat.parse(queryTime);
            SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy年MM月dd日");//注意月份是MM
            String dateTime = sdf2.format(queryDate);
            if(num < 1) {
                row2.getCell(0).setCellValue(String.format(subTitle, companyInfo.getName(), dateTime));
            }else{
                row2.getCell(0).setCellValue(String.format(subTitle, dateTime));
            }

            int startRowIndex = 3;

            for (int i = 0; i < pageDTO.size(); i++) {
                Row row = sheet.createRow(startRowIndex + i);
                PersonInfoDTO personInfoDTO = pageDTO.get(i);
                List<PersonHealthLedger> phlList = personHealthLedgerService.findByTimeAndPersonId(queryTime,personInfoDTO.getId(),null,null,null);

                Boolean isUpHealth = false;
                String healthStatusN = "";
                String familyStatusN = "";
                PersonHealthLedger phl = null;

                String name = (String) personInfoDTO.getName();
                String _className = personInfoDTO.getCompanyName();
                String _temperature = "";
                String _healthStatusN = "未提交";
                String _familyStatus = "";
                String _isTouch = "";
                String _isGoto = "";
                String _address = "";
                String remark = "";

                if(phlList.size() > 0){
                    phl = phlList.get(0);
                    healthStatusN = dataDictionaryService.findNameByCatalogNameAndValue("健康情况",phl.getHealthStatus());

                    familyStatusN = dataDictionaryService.findNameByCatalogNameAndValue("健康情况",phl.getFamilyStatus());

                    //学生姓名 自身状况 家庭健康情况 假期是否曾前往重点疫区 是否接触重点疫区高危人员 备注

                    _healthStatusN = (String) healthStatusN;
                    _temperature = phl.getTemperature().toString();
                    _familyStatus = (String) familyStatusN;
                    _isTouch = phl.getIsTouch()  ? "是":"否";
                    _isGoto = phl.getIsGoto()  ? "是":"否";
                    _address = phl.getAddress();
                    remark = (String) phl.getRemark();
                    isUpHealth = true;
                }else{
                    //查体温上报
                    List<PersonDeviceFilterLog> pdflList = personDeviceFilterLogService.findByTimeAndPersonId(queryTime,personInfoDTO.getId());
                    if(pdflList.size() > 0){
                        PersonDeviceFilterLog pdfl = pdflList.get(0);
                        _temperature = pdfl.getTemperature().toString();
                        _healthStatusN = "设备测温";
                        isUpHealth = true;
                    }else{
                        isUpHealth = false;
                    }
                }


                //学生姓名 自身状况 家庭健康情况 假期是否曾前往重点疫区 是否接触重点疫区高危人员 备注
                row.createCell(0).setCellValue(name);

                if(num < 1) {
                    row.createCell(1).setCellValue(_className);
                }

                row.createCell(2 - num).setCellValue(_healthStatusN);

                row.createCell(3 - num).setCellValue(_temperature);

                row.createCell(4 - num).setCellValue(_familyStatus);

                row.createCell(5 - num).setCellValue(_isGoto);

                row.createCell(6 - num).setCellValue(_isTouch);

                row.createCell(7 - num).setCellValue(_address);

                row.createCell(8 - num).setCellValue(remark);

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

            CellStyle cellStyle1 = createCellStyle(wb);

            for (int i = 0; i < pageDTO.size(); i++) {
                Row row = sheet.getRow(startRowIndex + i);

                if (row != null) {
                    for (int j = 0; j < row.getLastCellNum(); j++) {
                        if (row.getCell(j) != null) {
                            row.getCell(j).setCellStyle(cellStyle1);
                        }
                    }
                }
            }

            //todo 将wb保存到oss
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            wb.write(output);

            byte[] buffer = output.toByteArray();
            ByteArrayInputStream input = new ByteArrayInputStream(buffer);

            String fileName = "健康上报信息台账.xlsx";

            String downloadUrl = OSSUtil.upload(ossConfig, "personHealthLedger", fileName, input);

            wb.write(output);
            wb.close();
            output.close();

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

        return msgResult;
    }

    @ApiOperation(value="导出外出信息台账")
    @RequestMapping(value = "exportXlsWC",method = RequestMethod.POST)
    public MessageResult<String> exportXlsWC(
            @RequestParam(value="companyId",defaultValue="") String companyId,
            @RequestParam(value="subordinate",defaultValue="false")  Boolean subordinate,
            @DateTimeFormat(pattern = "yyyy-MM-dd")String queryTime,
            @RequestAttribute String subject) throws Exception {
        MessageResult<String> msgResult = new MessageResult<>();

        if (StringUtils.isEmpty(queryTime) || StringUtils.isEmpty(companyId)) {
            msgResult.setResult(false);
            msgResult.setMessage("请选择日期和所属班级！");
            return msgResult;
        }

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

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

            searchParams.put("queryTime",queryTime);
            CompanyInfo companyInfo = companyInfoService.get(companyId);
            if (subordinate) {
                searchParams.put("companyCode", companyInfo.getCode() + "%");
            } else {
                searchParams.put("companyCode", companyInfo.getCode());
            }
            searchParams.put("addressOut", "%荆州市%");

            Page<PersonHealthLedger> page = personHealthLedgerService.pageSearch(searchParams,1,1000,false,sortList);

            String xlsPath = "static/personHealthLedgerWC.xlsx";
            ClassPathResource resource = new ClassPathResource(xlsPath);
            Workbook wb = WorkbookFactory.create(resource.getInputStream());
            Sheet sheet = wb.getSheetAt(0);
            Row row1 = sheet.getRow(1);
            row1.getCell(0).setCellValue(companyInfo.getName());
            row1.getCell(3).setCellValue("日期："+queryTime);

            int rowNum = 3;
            for(PersonHealthLedger personHealthLedger : page.getResult()){
                Row rowItem = sheet.createRow(rowNum);
                PersonInfo personInfo = personInfoService.get(personHealthLedger.getPersonId());
                rowItem.createCell(0).setCellValue(personInfo.getCompanyName());
                rowItem.createCell(1).setCellValue(personInfo.getName());
                rowItem.createCell(2).setCellValue(personHealthLedger.getAddress());
                rowItem.createCell(3).setCellValue(personHealthLedger.getTemperature().toString());
                rowItem.createCell(4).setCellValue(personInfo.getPhone());

                rowNum++;
            }

            CellStyle cellStyle1 = createCellStyle(wb);

            for (int i = 3; i < rowNum; i++) {
                Row row = sheet.getRow(i);

                if (row != null) {
                    for (int j = 0; j < row.getLastCellNum(); j++) {
                        if (row.getCell(j) != null) {
                            row.getCell(j).setCellStyle(cellStyle1);
                        }
                    }
                }
            }

            //todo 将wb保存到oss
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            wb.write(output);

            byte[] buffer = output.toByteArray();
            ByteArrayInputStream input = new ByteArrayInputStream(buffer);

            String fileName = "外出信息台账.xlsx";

            String downloadUrl = OSSUtil.upload(ossConfig, "personHealthLedger", fileName, input);

            wb.write(output);
            wb.close();
            output.close();

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

        return msgResult;
    }

    @ApiOperation(value="导出体温异常信息台账")
    @RequestMapping(value = "exportXlsTWYC",method = RequestMethod.POST)
    public MessageResult<String> exportXlsTWYC(
            @RequestParam(value="companyId",defaultValue="") String companyId,
            @RequestParam(value="subordinate",defaultValue="false")  Boolean subordinate,
            @DateTimeFormat(pattern = "yyyy-MM-dd")String queryTime,
            @RequestAttribute String subject) throws Exception {
        MessageResult<String> msgResult = new MessageResult<>();

        if (StringUtils.isEmpty(queryTime) || StringUtils.isEmpty(companyId)) {
            msgResult.setResult(false);
            msgResult.setMessage("请选择日期和单位！");
            return msgResult;
        }

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

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

            searchParams.put("queryTime",queryTime);
            CompanyInfo companyInfo = companyInfoService.get(companyId);
            if (subordinate) {
                searchParams.put("companyCode", companyInfo.getCode() + "%");
            } else {
                searchParams.put("companyCode", companyInfo.getCode());
            }
            searchParams.put("temperature", temperatureConfig.getMax());

            Page<PersonHealthLedger> page = personHealthLedgerService.pageSearch(searchParams,1,1000,false,sortList);

            String xlsPath = "static/personHealthLedgerTWYC.xlsx";
            ClassPathResource resource = new ClassPathResource(xlsPath);
            Workbook wb = WorkbookFactory.create(resource.getInputStream());
            Sheet sheet = wb.getSheetAt(0);
            Row row1 = sheet.getRow(1);
            row1.getCell(0).setCellValue(companyInfo.getName());
            row1.getCell(2).setCellValue("日期："+queryTime);

            int rowNum = 3;
            for(PersonHealthLedger personHealthLedger : page.getResult()){
                Row rowItem = sheet.createRow(rowNum);
                PersonInfo personInfo = personInfoService.get(personHealthLedger.getPersonId());
                rowItem.createCell(0).setCellValue(personInfo.getCompanyName());
                rowItem.createCell(1).setCellValue(personInfo.getName());
                rowItem.createCell(2).setCellValue(personHealthLedger.getTemperature().toString());
                rowItem.createCell(3).setCellValue(personInfo.getPhone());

                rowNum++;
            }

            CellStyle cellStyle1 = createCellStyle(wb);

            for (int i = 3; i < rowNum; i++) {
                Row row = sheet.getRow(i);

                if (row != null) {
                    for (int j = 0; j < row.getLastCellNum(); j++) {
                        if (row.getCell(j) != null) {
                            row.getCell(j).setCellStyle(cellStyle1);
                        }
                    }
                }
            }

            //todo 将wb保存到oss
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            wb.write(output);

            byte[] buffer = output.toByteArray();
            ByteArrayInputStream input = new ByteArrayInputStream(buffer);

            String fileName = "体温异常信息台账.xlsx";

            String downloadUrl = OSSUtil.upload(ossConfig, "personHealthLedger", fileName, input);

            wb.write(output);
            wb.close();
            output.close();

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

        return msgResult;
    }

    @ApiOperation(value="导出症状异常信息台账")
    @RequestMapping(value = "exportXlsZZYC",method = RequestMethod.POST)
    public MessageResult<String> exportXlsZZYC(
            @RequestParam(value="companyId",defaultValue="") String companyId,
            @RequestParam(value="subordinate",defaultValue="false")  Boolean subordinate,
            @DateTimeFormat(pattern = "yyyy-MM-dd")String queryTime,
            @RequestAttribute String subject) throws Exception {
        MessageResult<String> msgResult = new MessageResult<>();

        if (StringUtils.isEmpty(queryTime) || StringUtils.isEmpty(companyId)) {
            msgResult.setResult(false);
            msgResult.setMessage("请选择日期和单位！");
            return msgResult;
        }

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

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

            searchParams.put("queryTime",queryTime);
            CompanyInfo companyInfo = companyInfoService.get(companyId);
            if (subordinate) {
                searchParams.put("companyCode", companyInfo.getCode() + "%");
            } else {
                searchParams.put("companyCode", companyInfo.getCode());
            }
            searchParams.put("healthStatusNot", "1");

            Page<PersonHealthLedger> page = personHealthLedgerService.pageSearch(searchParams,1,1000,false,sortList);

            String xlsPath = "static/personHealthLedgerZZYC.xlsx";
            ClassPathResource resource = new ClassPathResource(xlsPath);
            Workbook wb = WorkbookFactory.create(resource.getInputStream());
            Sheet sheet = wb.getSheetAt(0);
            Row row1 = sheet.getRow(1);
            row1.getCell(0).setCellValue(companyInfo.getName());
            row1.getCell(2).setCellValue("日期："+queryTime);

            int rowNum = 3;
            for(PersonHealthLedger personHealthLedger : page.getResult()){
                Row rowItem = sheet.createRow(rowNum);
                String healthStatusN = dataDictionaryService.findNameByCatalogNameAndValue("健康情况",personHealthLedger.getHealthStatus());
                PersonInfo personInfo = personInfoService.get(personHealthLedger.getPersonId());
                rowItem.createCell(0).setCellValue(personInfo.getCompanyName());
                rowItem.createCell(1).setCellValue(personInfo.getName());
                rowItem.createCell(2).setCellValue(healthStatusN);
                rowItem.createCell(3).setCellValue(personInfo.getPhone());

                rowNum++;
            }

            CellStyle cellStyle1 = createCellStyle(wb);

            for (int i = 3; i < rowNum; i++) {
                Row row = sheet.getRow(i);

                if (row != null) {
                    for (int j = 0; j < row.getLastCellNum(); j++) {
                        if (row.getCell(j) != null) {
                            row.getCell(j).setCellStyle(cellStyle1);
                        }
                    }
                }
            }

            //todo 将wb保存到oss
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            wb.write(output);

            byte[] buffer = output.toByteArray();
            ByteArrayInputStream input = new ByteArrayInputStream(buffer);

            String fileName = "症状异常信息台账.xlsx";

            String downloadUrl = OSSUtil.upload(ossConfig, "personHealthLedger", fileName, input);

            wb.write(output);
            wb.close();
            output.close();

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

        return msgResult;
    }

    @PostMapping("gpsHistoryList")
    public MessageResult<Map> gpsHistoryList(
            String personId,
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date startTime,
            @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date endTime,
            @RequestAttribute String subject){

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

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

        searchParams.put("GPS",true);

        if(personId != null) {
            searchParams.put("personId", personId);
        }

        if(startTime != null) {
            searchParams.put("startTime", startTime);
        }

        if(endTime != null) {
            searchParams.put("endTime", endTime);
        }

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

        Page<PersonHealthLedger> page = personHealthLedgerService.pageSearch(searchParams,1,20,true,sortList);

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

        return messageResult;
    }


    @ApiOperation(value = "导出健康信息明细表")
    @RequestMapping(value = "healthLedgerDateExportXls", method = RequestMethod.POST)
    public MessageResult<String> healthLedgerDateExportXls(
            String token,String classId,String timeRanges) {

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

        CompanyInfo companyInfo = companyInfoService.get(classId);

        Map<String,Object> searchParams = new HashMap<>();
        searchParams.put("code", companyInfo.getCode() + "%");

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

        List<PersonInfo> personInfoList = personInfoService.findByCompanyCode(searchParams,sortList);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        try {
            List<Map<String, Object>> list = new ArrayList<>();

            String[] timeRangeArray = timeRanges.split(",");

            Date startTime = sdf.parse(timeRangeArray[0]);
            Date endTime = sdf.parse(timeRangeArray[1]);

            List<String> betweenDays = getBetweenDays(startTime, endTime);

            for (PersonInfo personInfo : personInfoList) {

                Map<String,PersonHealthLedger> ledgerMap = new HashMap<>();

                Map<String,Object> map = new HashMap<>();
                CompanyInfo class_ = companyInfoService.get(personInfo.getCompanyId());
                if(class_!=null){
                    map.put("className",class_.getName());
                }

                map.put("personName",personInfo.getName());

                List<PersonHealthLedger> personHealthLedgerList = personHealthLedgerService.findByCreateTimeAndPersonId(personInfo.getId(),startTime,endTime);

                for (PersonHealthLedger personHealthLedger : personHealthLedgerList) {
                    ledgerMap.put(sdf.format(personHealthLedger.getCreateTime()), personHealthLedger);
                }

                for (String dateStr:betweenDays) {
                    BigDecimal temperature = null;
                    String healthStatusN = "";
                    String isGoOut = "无";
                    String address ="";

                    if (ledgerMap.containsKey(dateStr)) {
                        PersonHealthLedger personHealthLedger = ledgerMap.get(dateStr);

                        temperature = personHealthLedger.getTemperature();
                        healthStatusN = personHealthLedger.getHealthStatusN();
                        isGoOut = "无";

                        address = personHealthLedger.getAddress();
                        if (StringUtils.isNotEmpty(address)) {
                            if (!address.contains("荆州")) {
                                isGoOut = "外出";
                            }
                        }
                    }

                    map.put(dateStr + "-temperature", temperature);
                    map.put(dateStr + "-healthStatusN", healthStatusN);
                    map.put(dateStr + "-isGoOut", isGoOut);
                    map.put(dateStr + "-address", address);
                }

                list.add(map);
            }

            Workbook workbook = new HSSFWorkbook();

            Sheet sheet = workbook.createSheet();
            //表头
            Row rowTitle = sheet.createRow(0);
            Row rowTitle1 = sheet.createRow(1);

            List<String> headList = new ArrayList<>();
            headList.add("公司");
            headList.add("姓名");

            List<String> headList1 = new ArrayList<>();
            headList1.add("");
            headList1.add("");

            for (String startDateStr : betweenDays) {
                headList.add(startDateStr);

                headList1.add("体温");
                headList1.add("症状");
                headList1.add("外出情况");
            }

            CellStyle cellStyle = workbook.createCellStyle();
            cellStyle.setBorderBottom(BorderStyle.THIN);
            cellStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex());

            cellStyle.setBorderTop(BorderStyle.THIN);
            cellStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());

            cellStyle.setBorderLeft(BorderStyle.THIN);
            cellStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex());

            cellStyle.setBorderRight(BorderStyle.THIN);
            cellStyle.setRightBorderColor(IndexedColors.BLACK.getIndex());

            for (int i = 0; i < headList.size(); i++) {
                if (i >= 2) {
                    CellRangeAddress region = new CellRangeAddress(0, 0, i * 3 - 4, i * 3 - 2);
                    sheet.addMergedRegion(region);

                    Cell cell = rowTitle.createCell(i * 3 - 4);
                    cell.setCellValue(headList.get(i));

                    setRegionBorder(BorderStyle.THIN,region,sheet);
                }
                else {
                    Cell cell = rowTitle.createCell(i);
                    cell.setCellValue(headList.get(i));
                    cell.setCellStyle(cellStyle);
                }
            }

            for (int i = 0; i < headList1.size(); i++) {
                Cell cell = rowTitle1.createCell(i);
                cell.setCellValue(headList1.get(i));
                cell.setCellStyle(cellStyle);
            }

            CellRangeAddress region = new CellRangeAddress(0, 1, 0, 0);
            sheet.addMergedRegion(region);

            CellRangeAddress region2 = new CellRangeAddress(0, 1, 1, 1);
            sheet.addMergedRegion(region2);

            HSSFPatriarch p  = (HSSFPatriarch)sheet.createDrawingPatriarch();

            for (int i=0;i<list.size();i++){
                Map<String,Object> map = list.get(i);

                Row row = sheet.createRow(i+2);

                int colIndex = 0;
                Cell cell1 = row.createCell(colIndex++);
                cell1.setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(map.get("className"),""));
                cell1.setCellStyle(cellStyle);
                Cell cell2 = row.createCell(colIndex++);
                cell2.setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(map.get("personName"),""));
                cell2.setCellStyle(cellStyle);

                for (String startDateStr:betweenDays) {
                    Cell cell3 = row.createCell(colIndex++);
                    cell3.setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(map.get(startDateStr + "-temperature"),""));
                    cell3.setCellStyle(cellStyle);
                    Cell cell4 = row.createCell(colIndex++);
                    cell4.setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(map.get(startDateStr + "-healthStatusN"),""));
                    cell4.setCellStyle(cellStyle);
                    Cell cell5 = row.createCell(colIndex++);
                    cell5.setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(map.get(startDateStr + "-isGoOut"),""));
                    cell5.setCellStyle(cellStyle);

                    String address = (String)map.get(startDateStr + "-address");

                    if (StringUtils.isNotEmpty(address)) {
                        //前四个参数是坐标点,后四个参数是编辑和显示批注时的大小.
                        HSSFComment comment = p.createComment(new HSSFClientAnchor(0, 0, 0, 0, (short) 3, 3, (short) 5, 6));
                        comment.setString(new HSSFRichTextString(address));
                        //将批注添加到单元格对象中
                        cell5.setCellComment(comment);
                    }
                }

            }

            ByteArrayOutputStream output = new ByteArrayOutputStream();

            workbook.write(output);

            byte[] buffer = output.toByteArray();
            ByteArrayInputStream input = new ByteArrayInputStream(buffer);

            String downloadUrl = OSSUtil.upload(ossConfig, "healthLedgerDateExport", companyInfo.getName() +  "人员名单.xls", input);

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

        return msgResult;
    }

    public void setRegionBorder(BorderStyle border, CellRangeAddress region, Sheet sheet){
        RegionUtil.setBorderBottom(border,region,sheet);
        RegionUtil.setBorderLeft(border,region,sheet);
        RegionUtil.setBorderRight(border,region,sheet);
        RegionUtil.setBorderTop(border,region,sheet);
    }


    public List<String> getBetweenDays(Date startTime, Date endTime) throws ParseException {

        if (startTime == null || endTime == null) {
            return null;
        }
        List<String> result = new ArrayList<>();

        Calendar tempStart = Calendar.getInstance();
        tempStart.setTime(startTime);

        tempStart.add(Calendar.DAY_OF_YEAR, 1);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar tempEnd = Calendar.getInstance();
        tempEnd.setTime(endTime);
        result.add(sdf.format(startTime));
        while (tempStart.before(tempEnd)) {
            result.add(sdf.format(tempStart.getTime()));
            tempStart.add(Calendar.DAY_OF_YEAR, 1);
        }
        return result;
    }

    @GetMapping("notice")
    @ApiOperation(value="健康打卡通知")
    public MessageResult<String> notice(Long personId){
        MessageResult<String> messageResult = new MessageResult<>();

        try {
            PersonInfo personInfo = personInfoService.get(personId);

            HealthyReportNoticeDTO dto = new HealthyReportNoticeDTO();
            dto.setPersonId(personInfo.getId());
            dto.setOpenId(personInfo.getOpenId());
            dto.setCompanyName("测试单位");
            dto.setPopedom(personInfo.getPopedom());

            rabbitTemplate.convertAndSend("workerHealthyReportNoticeQueue", dto);

            //todo 填写具体代码
            messageResult.setData("发送成功");
            messageResult.setResult(true);
        }
        catch (Exception ex){
            logger.error(ex.getMessage(),ex);

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

        return messageResult;
    }


    @ApiOperation(value = "荆州开发区2021年春节期间企业人员情况明细表")
    @RequestMapping(value = "healthLedgerDateCompanyNumExportXls", method = RequestMethod.POST)
    public MessageResult<String> healthLedgerDateCompanyNumExportXls(String token) {

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

        List<Map<String, Object>> list = new ArrayList<>();

        try {

            List<CompanyInfo> companyInfoList = companyInfoService.findByType("1");

            String recordTime = DateUtil.format(new Date(), "yyyy-MM-dd");

            for (CompanyInfo companyInfo : companyInfoList) {
                Map<String, Object> map = new HashMap<>();
                CompanySupervise companySupervise = companySuperviseService.findByCompanyIdAndRecordDate(companyInfo.getId(), recordTime);
                if(companySupervise!=null) {
                    map.put("companyName", companyInfo.getName());
                    map.put("totalNum", companySupervise.getTotalNum());
                    map.put("atOutProvinceNum", companySupervise.getAtOutProvinceNum());
                    map.put("atProvinceNum", companySupervise.getAtProvinceNum());
                    list.add(map);
                }
            }

            Workbook workbook = new HSSFWorkbook();

            Sheet sheet = workbook.createSheet();
            //表头
            Row rowTitle = sheet.createRow(0);
            Row rowTitle1 = sheet.createRow(1);

            List<String> headList = new ArrayList<>();
            headList.add("序号");
            headList.add("企业名称");
            headList.add("人员情况");

            List<String> headList1 = new ArrayList<>();
            headList1.add("");
            headList1.add("");
            headList1.add("总人数（人）");
            headList1.add("外省员工就地过春节人数");
            headList1.add("省内员工就地过春节人数");

            CellStyle cellStyle = workbook.createCellStyle();
            cellStyle.setBorderBottom(BorderStyle.THIN);
            cellStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex());

            cellStyle.setBorderTop(BorderStyle.THIN);
            cellStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());

            cellStyle.setBorderLeft(BorderStyle.THIN);
            cellStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex());

            cellStyle.setBorderRight(BorderStyle.THIN);
            cellStyle.setRightBorderColor(IndexedColors.BLACK.getIndex());

            for (int i = 0; i < headList.size(); i++) {
                if (i >= 2) {
                    CellRangeAddress region = new CellRangeAddress(0, 0, i * 3 - 4, i * 3 - 2);
                    sheet.addMergedRegion(region);

                    Cell cell = rowTitle.createCell(i * 3 - 4);
                    cell.setCellValue(headList.get(i));

                    setRegionBorder(BorderStyle.THIN, region, sheet);
                } else {
                    Cell cell = rowTitle.createCell(i);
                    cell.setCellValue(headList.get(i));
                    cell.setCellStyle(cellStyle);
                }
            }

            for (int i = 0; i < headList1.size(); i++) {
                Cell cell = rowTitle1.createCell(i);
                cell.setCellValue(headList1.get(i));
                cell.setCellStyle(cellStyle);
            }

            CellRangeAddress region = new CellRangeAddress(0, 1, 0, 0);
            sheet.addMergedRegion(region);

            CellRangeAddress region2 = new CellRangeAddress(0, 1, 1, 1);
            sheet.addMergedRegion(region2);

            int totalCompanyNum=0;
            int totalAtOutProvinceNum=0;
            int totalAtProvinceNum=0;

            for (int i=0;i<list.size();i++){
                Map<String,Object> map = list.get(i);

                Row row = sheet.createRow(i+2);

                int colIndex = 0;
                Cell cell0 = row.createCell(colIndex++);
                cell0.setCellValue(i+1);
                cell0.setCellStyle(cellStyle);
                Cell cell1 = row.createCell(colIndex++);
                cell1.setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(map.get("companyName"),""));
                cell1.setCellStyle(cellStyle);
                Cell cell2 = row.createCell(colIndex++);
                cell2.setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(map.get("totalNum"),""));
                cell2.setCellStyle(cellStyle);
                Cell cell3 = row.createCell(colIndex++);
                cell3.setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(map.get("atOutProvinceNum"),""));
                cell3.setCellStyle(cellStyle);
                Cell cell4 = row.createCell(colIndex++);
                cell4.setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(map.get("atProvinceNum"),""));
                cell4.setCellStyle(cellStyle);

                if(map.get("totalNum")!=null){
                    String strTotalNum = map.get("totalNum").toString();
                    totalCompanyNum+=Integer.parseInt(strTotalNum);
                }
                if(map.get("atOutProvinceNum")!=null){
                    String strAtOutProvinceNum = map.get("atOutProvinceNum").toString();
                    totalAtOutProvinceNum+=Integer.parseInt(strAtOutProvinceNum);
                }
                if(map.get("atProvinceNum")!=null){
                    String strAtProvinceNum = map.get("atProvinceNum").toString();
                    totalAtProvinceNum+=Integer.parseInt(strAtProvinceNum);
                }
            }

            Row rowTotal = sheet.createRow(list.size()+2);

            Cell cell0 = rowTotal.createCell(0);
            cell0.setCellValue(list.size()+1);
            cell0.setCellStyle(cellStyle);

            Cell cell1 = rowTotal.createCell(1);
            cell1.setCellValue("合计（" + recordTime + "）");
            cell1.setCellStyle(cellStyle);

            Cell cell2 = rowTotal.createCell(2);
            cell2.setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(totalCompanyNum,""));
            cell2.setCellStyle(cellStyle);

            Cell cell3 = rowTotal.createCell(3);
            cell3.setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(totalAtOutProvinceNum,""));
            cell3.setCellStyle(cellStyle);

            Cell cell4 = rowTotal.createCell(4);
            cell4.setCellValue(com.jpsoft.shinestar.modules.common.utils.StringUtils.strValue(totalAtProvinceNum,""));
            cell4.setCellStyle(cellStyle);

            ByteArrayOutputStream output = new ByteArrayOutputStream();

            workbook.write(output);

            byte[] buffer = output.toByteArray();
            ByteArrayInputStream input = new ByteArrayInputStream(buffer);

            String downloadUrl = OSSUtil.upload(ossConfig, "healthLedgerDateCompanyNumExport", "春节期间企业人员情况明细表.xls", input);

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

        return msgResult;
    }
}
