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

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.domain.Person;
import com.github.pagehelper.Page;
import com.github.pagehelper.util.StringUtil;
import com.jpsoft.shinestar.config.OSSConfig;
import com.jpsoft.shinestar.config.WxConfig;
import com.jpsoft.shinestar.modules.base.entity.*;
import com.jpsoft.shinestar.modules.base.service.*;
import com.jpsoft.shinestar.modules.business.dto.*;
import com.jpsoft.shinestar.modules.business.entity.GuestFellow;
import com.jpsoft.shinestar.modules.business.entity.GuestInfoRecord;
import com.jpsoft.shinestar.modules.business.service.GuestFellowService;
import com.jpsoft.shinestar.modules.business.service.GuestInfoRecordService;
import com.jpsoft.shinestar.modules.common.dto.MessageResult;
import com.jpsoft.shinestar.modules.common.dto.Sort;
import com.jpsoft.shinestar.modules.common.utils.JwtUtil2;
import com.jpsoft.shinestar.modules.common.utils.PojoUtils;
import com.jpsoft.shinestar.modules.common.utils.StringUtils;
import com.jpsoft.shinestar.modules.common.utils.WechatMessageUtil;
import com.jpsoft.shinestar.modules.pacs.dto.PacsMsgResult;
import com.jpsoft.shinestar.modules.pacs.dto.PacsResult;
import com.jpsoft.shinestar.modules.pacs.service.IGuardService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
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.beans.factory.annotation.Value;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/mobile/guestInfoRecordApi")
@Slf4j
public class GuestInfoRecordApiController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private GuestInfoRecordService guestInfoRecordService;

    @Autowired
    private CompanyDeviceRelationService companyDeviceRelationService;

    @Autowired
    private PersonInfoService personInfoService;

    @Autowired
    private DeviceInfoService deviceInfoService;

    @Autowired
    private CompanyInfoService companyInfoService;

    @Autowired
    private GuestFellowService guestFellowService;

    @Autowired
    private IGuardService guardService;

    @Autowired
    private PunchLocationService punchLocationService;
    @Autowired
    private PersonDeviceRelationService personDeviceRelationService;

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

    @ApiOperation(value="邀请访客")
    @PostMapping("add")
    public MessageResult<GuestInfoRecord> add(@RequestBody GuestRecordAddDTO guestRecordAddDTO,String token,@RequestAttribute String subject){
        MessageResult<GuestInfoRecord> msgResult = new MessageResult<>();

        try {
            GuestInfoRecord guestInfoRecord = new GuestInfoRecord();

            guestInfoRecord.setId(UUID.randomUUID().toString());
            guestInfoRecord.setName(guestRecordAddDTO.getName());
            guestInfoRecord.setMobilePhone(guestRecordAddDTO.getMobilePhone());
            guestInfoRecord.setUnit(guestRecordAddDTO.getUnit());
            guestInfoRecord.setVisitReasons(guestRecordAddDTO.getVisitReasons());
            guestInfoRecord.setVisitDate(guestRecordAddDTO.getVisitDate());
            guestInfoRecord.setExpirationTime(guestRecordAddDTO.getExpirationTime());
            guestInfoRecord.setIsUpPhoto(guestRecordAddDTO.getIsUpPhoto());
            guestInfoRecord.setIssueDevice(guestRecordAddDTO.getIssueDevice());
            guestInfoRecord.setDelFlag(false);
            guestInfoRecord.setCreateBy(subject);
            guestInfoRecord.setCreateTime(new Date());
            guestInfoRecord.setStatus(0);
            guestInfoRecord.setIntervieweeId(Long.parseLong(subject));

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

            guestInfoRecord.setCompanyId(personInfo.getCompanyId());

            int affectCount = guestInfoRecordService.insert(guestInfoRecord);

            JSONObject verifyCodeJSON = new JSONObject();
            verifyCodeJSON.put("name","");
            //域名取配置
            verifyCodeJSON.put("url","");

           // SMSUtil.send(personInfo.getPhone(), "SMS_49390047", verifyCodeJSON.toString());

            if (affectCount > 0) {
                msgResult.setResult(true);
                msgResult.setData(guestInfoRecord);
            } 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("get/{id}")
    public MessageResult<Map> get(@PathVariable("id") String id,String token){
        MessageResult<Map> msgResult = new MessageResult<>();

        try {
            GuestInfoRecord guestInfoRecord = guestInfoRecordService.get(id);

            if (guestInfoRecord != null) {

                Map<String,Object> map=new HashMap<>();
                map.put("info",guestInfoRecord);
                if(guestInfoRecord.getIntervieweeId()!=null){
                    map.put("person",personInfoService.get(guestInfoRecord.getIntervieweeId()));
                }
                map.put("list",guestFellowService.getList(id));
                map.put("isNoToday",DateUtil.isSameDay(guestInfoRecord.getVisitDate(), new Date()));


                msgResult.setResult(true);
                msgResult.setData(map);
            } 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("detail/{id}")
    public MessageResult<GuestRecordDetailDTO> detail(@PathVariable("id") String id ){
        MessageResult<GuestRecordDetailDTO> msgResult = new MessageResult<>();

        try {
            GuestInfoRecord guestInfoRecord = guestInfoRecordService.get(id);

            if (guestInfoRecord != null) {

                GuestRecordDetailDTO guestRecordDetailDTO = new GuestRecordDetailDTO();

                PersonInfo personInfo = personInfoService.get(guestInfoRecord.getIntervieweeId());

                if(personInfo!=null) {
                    guestRecordDetailDTO.setIntervieweeName(personInfo.getName());
                    guestRecordDetailDTO.setIntervieweePhone(personInfo.getPhone());

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

                    guestRecordDetailDTO.setIntervieweeUnit(companyInfo.getName());
                }

                guestRecordDetailDTO.setName(guestInfoRecord.getName());
                guestRecordDetailDTO.setMobilePhone(guestInfoRecord.getMobilePhone());
                guestRecordDetailDTO.setIdCard(guestInfoRecord.getIdCard());
                guestRecordDetailDTO.setUnit(guestInfoRecord.getUnit());
                guestRecordDetailDTO.setVisitReasons(guestInfoRecord.getVisitReasons());
                guestRecordDetailDTO.setVisitDate(guestInfoRecord.getVisitDate());
                guestRecordDetailDTO.setNumberPlate(guestInfoRecord.getNumberPlate());
                guestRecordDetailDTO.setIsUpPhoto(guestInfoRecord.getIsUpPhoto());
                guestRecordDetailDTO.setStatus(guestInfoRecord.getStatus());
                guestRecordDetailDTO.setExpirationTime(guestInfoRecord.getExpirationTime());

                msgResult.setResult(true);
                msgResult.setData(guestRecordDetailDTO);
            } 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<GuestInfoRecord> update(@RequestBody GuestRecordUpdateDTO mod){
        MessageResult<GuestInfoRecord> msgResult = new MessageResult<>();

        try {
            GuestInfoRecord guestInfoRecord = guestInfoRecordService.get(mod.getId());

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");

            if(guestInfoRecord.getStatus()==0){

                guestInfoRecord.setIdCard(mod.getIdCard());
                guestInfoRecord.setPhoto(mod.getPhoto());
                guestInfoRecord.setNumberPlate(mod.getNumberPlate());
                guestInfoRecord.setStatus(1);
                guestInfoRecord.setConfirmationTime(new Date());


                //照片下发设备
                boolean isUpPhoto = guestInfoRecord.getIsUpPhoto();

                String issueDevice = guestInfoRecord.getIssueDevice();

                String[] deviceIdList = issueDevice.split(",");

                if(isUpPhoto){
                    String photo = guestInfoRecord.getPhoto();
                    CompanyInfo companyInfo = companyInfoService.findByName("访客公司");

                    PersonInfo personInfo = new PersonInfo();
                    personInfo.setCompanyId(companyInfo.getId());
                    personInfo.setName(guestInfoRecord.getName());
                    personInfo.setIdCard(guestInfoRecord.getIdCard());
                    personInfo.setPhone(guestInfoRecord.getMobilePhone());
                    personInfo.setFaceImageUrl(photo);
                    personInfo.setDelFlag(false);
                    personInfo.setCreateTime(new Date());
                    personInfo.setWorkStatus("1");
                    personInfo.setGuestEnabled(true);
                    personInfoService.insert(personInfo);

                    if (org.apache.commons.lang3.StringUtils.isEmpty(personInfo.getFaceImageUrl())){

                    }else{
                            for (String deviceId : deviceIdList) {
                                //照片上传到下发设备
                                PacsResult pacsResult = guardService.addPersonToDevice(personInfo.getId(), deviceId);

                                PersonDeviceRelation personDeviceRelation = new PersonDeviceRelation();
                                personDeviceRelation.setId(UUID.randomUUID().toString());
                                personDeviceRelation.setDeviceId(deviceId);
                                personDeviceRelation.setPersonId(personInfo.getId());
                                personDeviceRelation.setDelFlag(false);
                                personDeviceRelation.setIsBound(true);
                                personDeviceRelation.setIsWrite(pacsResult.isSuccess());
                                personDeviceRelation.setCreateTime(new Date());
                                personDeviceRelationService.insert(personDeviceRelation);
                            }
                    }
                    guestInfoRecord.setPersonId(personInfo.getId());
                }
                guestInfoRecordService.update(guestInfoRecord);

                if(mod.getList()!=null){
                    for(GuestFellowDTO guestFellowDTO :mod.getList()){
                        GuestFellow guestFellow = new GuestFellow();

                        guestFellow.setId(UUID.randomUUID().toString());
                        guestFellow.setName(guestFellowDTO.getName());
                        guestFellow.setMobilePhone(guestFellowDTO.getMobilePhone());
                        guestFellow.setIdCard(guestFellowDTO.getIdCard());
                        guestFellow.setPhoto(guestFellowDTO.getPhoto());
                        guestFellow.setGuestInfoRecordId(guestInfoRecord.getId());
                        guestFellow.setDelFlag(false);
                        guestFellow.setCreateBy("-1");
                        guestFellow.setCreateTime(new Date());
                        guestFellowService.insert(guestFellow);
                    }
                }

                //过期时间
             //   String expirationTimeStr = guestInfoRecord.getExpirationTime();

               // Date expirationTime = sdf.parse(expirationTimeStr);
                Date expirationTime= guestInfoRecord.getExpirationTime();
                Date now = new Date();

                Long milliseconds = expirationTime.getTime() - now.getTime();

                logger.warn("当前时间：{},消息延迟毫秒数: {}", DateTime.now().toString("yyyy-MM-dd HH:mm"), milliseconds);

                //延时队列,超过过期时间，删除访客信息和设备人脸信息
                rabbitTemplate.convertAndSend("removePersonGuestExchange", "removePersonGuest", guestInfoRecord.getId(), (message) -> {
                    //延时单位毫秒
                    message.getMessageProperties().setHeader("x-delay", milliseconds);
                    return message;
                });

                msgResult.setResult(true);
                msgResult.setData(null);
            }  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("out")
    public MessageResult<GuestRecordDetailDTO> out(@RequestBody GuestRecordOutDTO mod ,String token,@RequestAttribute String subject){
        MessageResult<GuestRecordDetailDTO> msgResult = new MessageResult<>();

        try {
            GuestInfoRecord guestInfoRecord = guestInfoRecordService.get(mod.getId());

            if (guestInfoRecord != null) {

                if(StringUtils.isNotEmpty(mod.getComeInTime())){
                    Date time = DateUtil.parse(mod.getComeInTime());
                    guestInfoRecord.setComeInTime(time);
                    if(mod.getTemperature()!=null){
                        guestInfoRecord.setTemperature(mod.getTemperature());

                    }
                }
                if(StringUtils.isNotEmpty(mod.getOutTime())){
                    Date time = DateUtil.parse(mod.getOutTime());
                    guestInfoRecord.setOutTime(time);
                    if(mod.getTemperatureBack()!=null){
                        guestInfoRecord.setTemperatureBack(mod.getTemperatureBack());
                    }
                }
                guestInfoRecord.setUpdateBy(subject);
                guestInfoRecordService.update(guestInfoRecord);
                msgResult.setResult(true);
                msgResult.setData(null);
            } 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<Object> pageList(
        String token,
        @RequestParam(value = "pageIndex", defaultValue = "1") int pageIndex,
        @RequestParam(value = "pageSize", defaultValue = "20") int pageSize,
        @RequestAttribute String subject){

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

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

        try {

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

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

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

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

            Page<GuestRecordDTO> pageDto = new Page<>();

            for (GuestInfoRecord guestInfoRecord : page) {
                GuestRecordDTO guestRecordDTO = new GuestRecordDTO();

                guestRecordDTO.setId(guestInfoRecord.getId());

                guestRecordDTO.setVisitDate(guestInfoRecord.getVisitDate());

                guestRecordDTO.setName(guestInfoRecord.getName());

                guestRecordDTO.setUnit(guestInfoRecord.getUnit());

                guestRecordDTO.setVisitReasons(guestInfoRecord.getVisitReasons());

                guestRecordDTO.setStatus(guestInfoRecord.getStatus());

                guestRecordDTO.setStatusN(guestInfoRecord.getStatusN());

                pageDto.add(guestRecordDTO);
            }

            pageDto.setPageSize(page.getPageSize());
            pageDto.setTotal(page.getTotal());
            pageDto.setPageNum(page.getPageNum());


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

        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            msgResult.setResult(false);
        }


        return msgResult;
    }

    @ApiOperation(value="列表(访客自己列表，免登陆)")
    @RequestMapping(value = "currentPageList",method = RequestMethod.POST)
    public MessageResult<Object> currentPageList(
            String token,String openId,
            @RequestParam(value = "pageIndex", defaultValue = "1") int pageIndex,
            @RequestParam(value = "pageSize", defaultValue = "20") int pageSize
           ){

        //当前用户ID

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

        try {

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

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

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

            Page<GuestRecordDTO> pageDto = new Page<>();

            for (GuestInfoRecord guestInfoRecord : page) {
                PersonInfo info =personInfoService.get(guestInfoRecord.getIntervieweeId());
                CompanyInfo companyInfo=companyInfoService.get(info.getCompanyId());
                GuestRecordDTO guestRecordDTO = new GuestRecordDTO();

                guestRecordDTO.setId(guestInfoRecord.getId());

                guestRecordDTO.setVisitDate(guestInfoRecord.getVisitDate());

                guestRecordDTO.setName(info.getName());

                guestRecordDTO.setUnit(companyInfo.getName());

                guestRecordDTO.setVisitReasons(guestInfoRecord.getVisitReasons());

                guestRecordDTO.setStatus(guestInfoRecord.getStatus());

                guestRecordDTO.setStatusN(guestInfoRecord.getStatusN());

                pageDto.add(guestRecordDTO);
            }

            pageDto.setPageSize(page.getPageSize());
            pageDto.setTotal(page.getTotal());
            pageDto.setPageNum(page.getPageNum());


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

        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            msgResult.setResult(false);
        }


        return msgResult;
    }


    @ApiOperation(value="扫码通行 -登记查询(免登陆)")
    @RequestMapping(value = "getInfo",method = RequestMethod.POST)
    public MessageResult<GuestInfoRecord> getInfo(
            String openId,
            String qrcode,
            String id ){

        //当前用户ID
        MessageResult<GuestInfoRecord> msgResult = new MessageResult<>();

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



            GuestInfoRecord retInfo=null;

            if(StringUtils.isNotEmpty(id)){
                retInfo=guestInfoRecordService.get(id);
            }else{
                PunchLocation punchLocation = punchLocationService.get(qrcode);
                if (punchLocation == null){
                    msgResult.setMessage("访客点不存在");
                    msgResult.setResult(false);
                    return msgResult;
                }
                if (!punchLocation.getIsEnable()){
                    msgResult.setMessage("访客点未启用");
                    msgResult.setResult(false);
                    return msgResult;
                }
                //查询最近的一条
                GuestInfoRecord  info =guestInfoRecordService.findByOpenId(openId);
                retInfo=new GuestInfoRecord();
                retInfo.setStatus(0);

                if(info!=null){
                    retInfo=new GuestInfoRecord();
                    retInfo.setName(info.getName());
                    retInfo.setMobilePhone(info.getMobilePhone());
                    retInfo.setIdCard(info.getIdCard());
                    retInfo.setUnit(info.getUnit());
                    retInfo.setOpenId(openId);
                    retInfo.setStatus(1);
                    retInfo.setDelFlag(false);
                }
                retInfo.setCompanyId(punchLocation.getCompanyId());
            }


            map.put("data",retInfo);
            msgResult.setData(retInfo);
            msgResult.setResult(true);

        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            msgResult.setResult(false);
        }


        return msgResult;
    }
    @Autowired
    private WxConfig wxConfig;

    @ApiOperation(value="扫码通行 - save")
    @PostMapping("save")
    public MessageResult<GuestInfoRecord> save(@RequestBody GuestInfoRecord save){
        MessageResult<GuestInfoRecord> msgResult = new MessageResult<>();

        try {
            Boolean insert=true;

            if(save.getId()==null){

                save.setId(UUID.randomUUID().toString());

            }else{
                insert=false;
            }

            if(insert){
                PersonInfo  info =personInfoService.findByNameAndPhone(save.getIntervieweeName(),save.getIntervieweePhone());
                if(info==null){
                    msgResult.setMessage("未找到受访人，请核实受访者名称或手机号码");
                    msgResult.setResult(false);
                    return msgResult;
                }
                save.setIntervieweeId(info.getId());
                save.setDelFlag(false);

                guestInfoRecordService.insert(save);
                new Thread(()->{

                    try{
                       // String accessToken = JwtUtil2.createToken(jwtSecret, info.getId() + "", DateTime.now().plusHours(6).toDate());
                        WechatMessageUtil.sendEvenMessage(info.getOpenId(), "有一条新的访客信息待审核", info.getName(),
                                save.getId().substring(0, 5), "前往处理",wxConfig.getPortalUrl().replace("business","home")+"guest/approval?id="+save.getId(),
                                wxConfig.getAppId(), wxConfig.getAppSecret());

                    }catch (Exception ex){
                        log.error(ex.getMessage(),ex);
                    }
                }).start();
            }else{
                guestInfoRecordService.update(save);
            }
            msgResult.setData(save);
            msgResult.setResult(true);
         }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

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

        return msgResult;
    }

    @ApiOperation(value="扫码通行 - save")
    @PostMapping("approval")
    public MessageResult<GuestInfoRecord> approval(String id,String status, String token,@RequestAttribute String subject){
        MessageResult<GuestInfoRecord> msgResult = new MessageResult<>();

        try {
            GuestInfoRecord info=  guestInfoRecordService.get(id);
            info.setStatus(Integer.valueOf(status));
            info.setConfirmationTime(new Date());
            info.setUpdateTime(new Date());
            guestInfoRecordService.update(info);

            new Thread(()->{

                try{
                    // String accessToken = JwtUtil2.createToken(jwtSecret, info.getId() + "", DateTime.now().plusHours(6).toDate());
                    WechatMessageUtil.sendEvenMessage(info.getOpenId(), "您的访客申请已经处理，结果为"+("1".equals(status)?"[通过]":"[拒绝]"), info.getIntervieweeName(),
                            info.getId().substring(0, 5), "前往处理",wxConfig.getPortalUrl()+"guest/current/info?currentId="+info.getId(),
                            wxConfig.getAppId(), wxConfig.getAppSecret());

                }catch (Exception ex){
                    log.error(ex.getMessage(),ex);
                }
            }).start();

            msgResult.setData(info);
            msgResult.setResult(true);
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

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

        return msgResult;
    }

    private static boolean isThisTime(long time,String pattern) {
        Date date = new Date(time);
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        String param = sdf.format(date);//参数时间
        String now = sdf.format(new Date());//当前时间
        if(param.equals(now)){
            return true;
        }
        return false;
    }
    @ApiOperation(value="获取设备列表")
    @RequestMapping(value = "deviceList",method = RequestMethod.POST)
    public MessageResult<Object> deviceList(String token,@RequestAttribute String subject){
        MessageResult<Object> msgResult = new MessageResult<>();

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

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

            List<PersonDeviceRelation> personDeviceRelationList = personDeviceRelationService.findByPersonId(Long.parseLong(subject));

            for (PersonDeviceRelation personDeviceRelation:personDeviceRelationList) {
                DeviceInfo deviceInfo = deviceInfoService.get(personDeviceRelation.getDeviceId());
                if(!deviceInfo.getDelFlag()) {
                    Map<String, Object> map = new HashMap<>();

                    map.put("id", deviceInfo.getId());
                    map.put("name", deviceInfo.getAliasName());
                    map.put("isOnline",deviceInfo.getIsOnline());

                    list.add(map);
                }
            }

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

        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            msgResult.setResult(false);
        }

        return msgResult;
    }


    @ApiOperation(value="出入记录")
    @RequestMapping(value = "accessRecords",method = RequestMethod.POST)
    public MessageResult<Map<String,Object>> accessRecords(
            String token,String queryDate,String isToDay,
             @RequestParam(value = "pageIndex", defaultValue = "1") int pageIndex,
            @RequestParam(value = "pageSize", defaultValue = "20") int pageSize,
            @RequestAttribute String subject) {

        MessageResult<Map<String,Object>> msgResult = new MessageResult<>();

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

            Map<String, Object> searchParams = new HashMap<>();
            if(queryDate!=null){
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date query = sdf.parse(queryDate);
                Date endDate = new DateTime(query).plusDays(1).toDate();
                String end = sdf.format(endDate);
                searchParams.put("startDate",queryDate);
                searchParams.put("endDate",end);
            }

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

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

            List<CompanyInfo> companyList = companyInfoService.findByRelationCompanyId(personInfo.getCompanyId());

            List<String> companyListId = new ArrayList<>();

            for (CompanyInfo companyInfo:companyList) {
                List<CompanyInfo> companyInfos = companyInfoService.findAllCompanyByCode("%"+companyInfo.getId()+"%");
                for (CompanyInfo item:companyInfos) {
                    companyListId.add(item.getId());
                }
            }

            searchParams.put("companyIdList",companyListId);

/*          List<CompanyInfo> companyInfoList = companyInfoService.findByCompanyCodeAndType(personInfo.getCompanyId(),"3");

            List<String> companyIdList = new ArrayList<>();

            //是否存在园区
            if(companyInfoList.size()>0){
                CompanyInfo companyInfo = companyInfoList.get(0);
                List<CompanyInfo> companyList = companyInfoService.findByParentId(companyInfo.getId());
                for (CompanyInfo item:companyList) {
                    companyIdList.add(item.getId());
                }
            }
            else{
                //不存在，直接查询公司
                CompanyInfo companyInfo = companyInfoService.get(personInfo.getCompanyId());
                companyIdList.add(companyInfo.getId());
            }*/

            searchParams.put("guest","1"); // 只查询非待确认的  前端需求

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

            Page<AccessRecordsDTO> pageDto = new Page<>();

            for (GuestInfoRecord guestInfoRecord : page) {
                AccessRecordsDTO accessRecordsDTO = new AccessRecordsDTO();

                accessRecordsDTO.setId(guestInfoRecord.getId());

                accessRecordsDTO.setVisitDate(guestInfoRecord.getVisitDate());

                accessRecordsDTO.setName(guestInfoRecord.getName());

                accessRecordsDTO.setUnit(guestInfoRecord.getUnit());

                accessRecordsDTO.setComeInTime(guestInfoRecord.getComeInTime());

                accessRecordsDTO.setOutTime(guestInfoRecord.getOutTime());

                int num = guestFellowService.findByGuestInfoRecordId(guestInfoRecord.getId());

                accessRecordsDTO.setNum(num);

                pageDto.add(accessRecordsDTO);
            }

            if("1".equals(isToDay)){
                Map num = guestInfoRecordService.getScanNum(searchParams);
                returnMap.put("num",num);
            }
            pageDto.setPageSize(page.getPageSize());
            pageDto.setTotal(page.getTotal());
            pageDto.setPageNum(page.getPageNum());

            returnMap.put("list",PojoUtils.pageWrapper(pageDto));

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

        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            msgResult.setResult(false);
        }


        return msgResult;
    }


    @ApiOperation(value="手机开门列表")
    @RequestMapping(value = "openByMobilePhoneList",method = RequestMethod.POST)
    public MessageResult<Object> openByMobilePhoneList(String token,@RequestAttribute String subject){
        MessageResult<Object> msgResult = new MessageResult<>();

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

            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
            Date now = sdf.parse(sdf.format(new Date()));

            List<PersonDeviceRelation> personDeviceRelationList = personDeviceRelationService.findByPersonId(Long.parseLong(subject));

            for (PersonDeviceRelation personDeviceRelation:personDeviceRelationList) {
                if(personDeviceRelation.getRemoteOpen()!=null) {
                    if (personDeviceRelation.getRemoteOpen()) {
                        Map<String, Object> map = new HashMap<>();
                        DeviceInfo device = deviceInfoService.get(personDeviceRelation.getDeviceId());
                        map.put("id", device.getId());
                        map.put("name", device.getAliasName());
                        map.put("isOnline", device.getIsOnline());
                        map.put("remoteOpenStartTime",device.getRemoteOpenStartTime());
                        map.put("remoteOpenEndTime",device.getRemoteOpenEndTime());

                        Boolean isOpen = true;

                        if(StringUtils.isNotEmpty(device.getRemoteOpenStartTime())&&StringUtils.isNotEmpty(device.getRemoteOpenEndTime())){
                            Date remoteOpenStartTime = sdf.parse(device.getRemoteOpenStartTime());
                            Date remoteOpenEndTime = sdf.parse(device.getRemoteOpenEndTime());

                            isOpen = belongCalendar(now, remoteOpenStartTime, remoteOpenEndTime);
                        }
                        map.put("isOpen",isOpen);

                        list.add(map);
                    }
                }
            }

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

        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            msgResult.setResult(false);
        }

        return msgResult;
    }


    @ApiOperation(value="手机开门")
    @RequestMapping(value = "openByMobilePhone",method = RequestMethod.POST)
    public MessageResult<Object> openByMobilePhone(String id,String token,@RequestAttribute String subject){
        MessageResult<Object> msgResult = new MessageResult<>();

        PacsMsgResult pacsMsgResult = new PacsMsgResult();

        try{
            DeviceInfo deviceInfo = deviceInfoService.get(id);

            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
            Date now = sdf.parse(sdf.format(new Date()));

            Boolean isOpen = true;

            if(StringUtils.isNotEmpty(deviceInfo.getRemoteOpenStartTime())&&StringUtils.isNotEmpty(deviceInfo.getRemoteOpenEndTime())){
                Date remoteOpenStartTime = sdf.parse(deviceInfo.getRemoteOpenStartTime());
                Date remoteOpenEndTime = sdf.parse(deviceInfo.getRemoteOpenEndTime());

                isOpen = belongCalendar(now, remoteOpenStartTime, remoteOpenEndTime);
            }

            if(isOpen){
                pacsMsgResult = guardService.remoteOpen(id);

                if(pacsMsgResult.isSuccess()){
                    msgResult.setResult(true);
                }
                else{
                    msgResult.setResult(false);
                }

                msgResult.setMessage(pacsMsgResult.getMsg());
                msgResult.setData(pacsMsgResult.getAliasName());
            }
            else{
                msgResult.setResult(false);
                msgResult.setMessage("开门失败，当前不在远程开门时间范围内！");
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);

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

        return msgResult;
    }

    /**
     * 判断时间是否在时间段内
     * @param nowTime
     * @param beginTime
     * @param endTime
     * @return
     */
    public static boolean belongCalendar(Date nowTime, Date beginTime, Date endTime) {
        return nowTime.getTime() >= beginTime.getTime() && nowTime.getTime() <= endTime.getTime();
    }

    public static void main(String[] args){
        Date now = new Date();

        long start = now.getTime();

        System.out.println(now.getTime());

        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println((new Date()).getTime() - start);
    }

}
