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

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.NumberUtil;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.jpsoft.shinestar.config.OSSConfig;
import com.jpsoft.shinestar.config.RedisConfig;
import com.jpsoft.shinestar.config.WxConfig;
import com.jpsoft.shinestar.modules.baidu.service.BceFaceService;
import com.jpsoft.shinestar.modules.base.dto.*;
import com.jpsoft.shinestar.modules.base.entity.*;
import com.jpsoft.shinestar.modules.base.service.*;
import com.jpsoft.shinestar.modules.business.entity.RequestForLeaveInfo;
import com.jpsoft.shinestar.modules.business.service.RequestForLeaveInfoService;
import com.jpsoft.shinestar.modules.common.dto.MessageResult;
import com.jpsoft.shinestar.modules.common.dto.Sort;
import com.jpsoft.shinestar.modules.common.utils.*;
import com.jpsoft.shinestar.modules.pacs.service.IGuardService;
import com.jpsoft.shinestar.modules.pay.properties.WxPayProperties;
import com.jpsoft.shinestar.modules.sys.entity.SysLog;
import com.jpsoft.shinestar.modules.sys.entity.User;
import com.jpsoft.shinestar.modules.sys.service.SysLogService;
import com.jpsoft.shinestar.modules.sys.service.UserService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import java.io.ByteArrayInputStream;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/mobile/personInfoApi")
@Slf4j
public class PersonInfoApiController {
    @Value("${jwt.secret}")
    private String jwtSecret;

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private OSSConfig ossConfig;

    @Autowired
    private WorkShiftInfoService workShiftInfoService;

    @Autowired
    private RequestForLeaveInfoService requestForLeaveInfoService;

    @Autowired
    private RegionInfoService regionInfoService;

    @Autowired
    private DistrictInfoService districtInfoService;

    @Autowired
    private WorkPersonSchedulingService workPersonSchedulingService;

    @Autowired
    private BusinessOutService businessOutService;

    @Autowired
    private ReturnInfoService returnInfoService;

    @Autowired
    private WxConfig wxConfig;

    @Autowired
    private ProblemFeedbackService problemFeedbackService;

    @Autowired
    private WxPayProperties wxPayProperties;

    @Autowired
    private MedicationInfoService medicationInfoService;

    @Autowired
    private PersonInfoService personInfoService;
    @Autowired
    private CompanyStructureInfoService companyStructureInfoService;
    @Autowired
    private PersonDeviceRelationService personDeviceRelationService;

    @Autowired
    private ParkingInfoService parkingInfoService;

    @Autowired
    private MessageInfoService messageInfoService;

    @Autowired
    private ParkingApplyService parkingApplyService;

    @Autowired
    private IGuardService lapiService;

    @Autowired
    private ValueOperations<String, Object> valueOperations;

    @Autowired
    private UserService userService;

    @Autowired
    private ParkingWayService parkingWayService;

    @Autowired
    private CompanyInfoService companyInfoService;

    @Autowired
    private PersonCompanyService personCompanyService;

    @Autowired
    private PersonRoleIconService personRoleIconService;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    private PersonPopedomService personPopedomService;

    @Autowired
    private PersonRoleInfoService personRoleInfoService;

    @Autowired
    private SceneInfoService sceneInfoService;

    @Autowired
    private IconInfoService iconInfoService;

    @Autowired
    private SysLogService sysLogService;

    @ApiModelProperty
    private CompanyPositionService companyPositionService;

    @Autowired
    private PersonApplicationInfoService personApplicationInfoService;

    @Autowired
    private BceFaceService bceFaceService;

    @PostMapping("findByNameAndPhone")
    @ApiOperation(value = "通过姓名和手机号查询人员(公开接口)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "姓名", required = false, paramType = "form"),
            @ApiImplicitParam(name = "phone", value = "电话号码", required = true, paramType = "form")
    })
    public MessageResult<Long> findByNameAndPhone(String name, String phone) {
        MessageResult<Long> messageResult = new MessageResult<>();

        try {
            // PersonInfo personInfo = personInfoService.findByNameAndPhone(name, phone);

            PersonInfo personInfo = personInfoService.findByPhone(phone);
            PersonApplicationInfo personApplicationInfo = personApplicationInfoService.findByTelephoneAndStatus(phone, "0");
            if (personInfo ==null && personApplicationInfo != null) {
                throw new Exception("您的注册信息正在审核中...");
            }
            if (personInfo == null && personApplicationInfo == null) {
                //    throw new Exception("您的信息暂未登记，请先联系管理人员!");
                messageResult.setData(0L);
                messageResult.setResult(true);
                messageResult.setCode(200);
                return messageResult;
            }
            if (personInfo != null && personApplicationInfo != null){
                personApplicationInfo.setDelFlag(true);
                personApplicationInfoService.update(personApplicationInfo);
            }

            messageResult.setData(personInfo.getId());
            messageResult.setResult(true);
            messageResult.setCode(200);
        } catch (Exception ex) {
            log.error(ex.getMessage());
            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }

        return messageResult;
    }


    @PostMapping("switchCompany")
    @ApiOperation(value = "切换管理单位")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "companyId", value = "companyId", required = true, paramType = "form"),
            @ApiImplicitParam(name = "token", value = "令牌", paramType = "form"),
            @ApiImplicitParam(name = "subject", value = "目标(不传)", paramType = "form")
    })
    public MessageResult<Map> switchCompany(String companyId, String token, @RequestAttribute String subject) {
        MessageResult<Map> messageResult = new MessageResult<>();

        try {
            PersonInfo personInfo = personInfoService.findById(Long.valueOf(subject));

            if (personInfo == null) {
                throw new Exception("当前用户不存在!");
            }

            //判断companyId是否存在于当前用户的关联单位中
            List<PersonCompany> personCompanies = personCompanyService.findByPersonId(personInfo.getId());

            long count = personCompanies.stream().filter((item) -> item.getCompanyId().equals(companyId)).count();

            if (count == 0) {
                //当前用户可以管理本单位
                if (personInfo.getAllowViewLocal() && personInfo.getCompanyId().equals(companyId)) {
                    count = 1;
                }
            }

            if (count == 0) {
                throw new Exception("选择单位不在当前用户的管理范围内!");
            }

            CompanyInfo companyInfo = companyInfoService.get(companyId);

            Map<String, Object> companyMap = new HashMap<>();
            companyMap.put("id", companyInfo.getId());
            companyMap.put("name", companyInfo.getName());

            valueOperations.set(RedisConfig.PERSON_SELECT_COMPANY + personInfo.getId(), companyMap, 2, TimeUnit.HOURS);

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

        return messageResult;
    }

    @PostMapping("findByOpenId")
    @ApiOperation(value = "通过openId查询人员(公开接口)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "openId", value = "微信openId", required = true, paramType = "form")
    })
    public MessageResult<Map> findByOpenId(String openId) {
        MessageResult<Map> messageResult = new MessageResult<>();

        try {

            PersonInfo personInfo = null;
            if (StringUtils.isNotBlank(openId)) {
                personInfo = personInfoService.findByOpenId(openId);
            }


            if (personInfo == null) {
                messageResult.setResult(true);
                messageResult.setCode(200);
                return messageResult;

            }

            Map<String, Object> dataMap = new HashMap<String, Object>();
            String token = JwtUtil.createToken(jwtSecret, personInfo.getId() + "", DateTime.now().plusHours(6).toDate());

            dataMap.put("person", personInfo);
            dataMap.put("token", token);
            if (StringUtils.isBlank(personInfo.getPopedom())) {
                throw new Exception("用户对应角色数据为空");
            }

            //用户角色数据
            PersonPopedom personPopedom = personPopedomService.get(personInfo.getPopedom());
            if (personPopedom == null) {
                //    throw new Exception("用户使用的角色数据不存在");
                //自动写入,临时功能
                PersonPopedom personPopedom1 = personPopedomService.autoInsert(personInfo);
                personPopedom = personPopedom1;
                personInfo.setPopedom(personPopedom1.getId());
                personInfo.setCompanyId(personPopedom1.getCompanyId());
                personInfoService.update(personInfo);
            }
            //公司数据
            CompanyInfo companyInfo = companyInfoService.get(personPopedom.getCompanyId());
            if (companyInfo == null) {
                throw new Exception("用户的公司数据有误");
            }
            //系统基础角色数据
            PersonRoleInfo personRoleInfo = personRoleInfoService.get(personPopedom.getPersonRoleId());
            SceneInfo sceneInfo = sceneInfoService.get(personRoleInfo.getSceneId());
            PersonPopedomDTO personPopedomDTO = new PersonPopedomDTO();
            personPopedomDTO.setCompanyId(companyInfo.getId());
            personPopedomDTO.setCompanyName(companyInfo.getName());
            personPopedomDTO.setPersonRoleId(personRoleInfo.getId());
            personPopedomDTO.setPersonRoleName(personRoleInfo.getPersonRoleName());
            personPopedomDTO.setId(personPopedom.getId());
            personPopedomDTO.setSceneId(personRoleInfo.getSceneId());
            personPopedomDTO.setSceneName(sceneInfo.getSceneName());
            personPopedomDTO.setPersonName(personInfo.getName());
            personPopedomDTO.setJob(personPopedom.getRemark());//职务
            CompanyStructureInfo structure = companyStructureInfoService.get(personPopedom.getCompanyStructureId());

            personPopedomDTO.setDeptName(structure != null ? structure.getStructureName() : "");

            dataMap.put("personPopedom", personPopedomDTO);


            //查询此角色用户下的显示图标
            List<IconInfoDTO> iconInfoList = new ArrayList<>();
            if (StringUtils.isNotBlank(personPopedom.getShowIconId())) {
                List<String> idList = Arrays.asList(personPopedom.getShowIconId().split(","));

                for (String id : idList) {
                    //   PersonRoleIcon personRoleIcon = personRoleIconService.get(id);
                    //       if (personRoleIcon != null){
                    IconInfo iconInfo = iconInfoService.get(id);
                    //   PersonRoleIcon personRoleIcon = personRoleIconService.findByPersonRoleIdAndIconId(personRoleInfo.getId(),id);
                    //     if (iconInfo != null && iconInfo.getUseEnable() && personRoleIcon != null) {
                    IconInfoDTO iconInfoDTO = new IconInfoDTO();
                    if (iconInfo != null) {
                        BeanUtils.copyProperties(iconInfo, iconInfoDTO);
                        if (StringUtils.isNotBlank(iconInfo.getIconParam())) {
                            iconInfoDTO.setIconParam(JSONObject.parseObject(iconInfo.getIconParam()));
                        }

                        if (iconInfoList.size() < 7) {
                            iconInfoList.add(iconInfoDTO);
                        }
                        if (iconInfoList.size() >= 7) {
                            break;
                        }
                    }

                    //        }
                }
                /*Map<String, Object> searchParams = new HashMap<>();
                searchParams.put("useEnable", true);
                searchParams.put("personRoleId", personPopedom.getPersonRoleId());
                searchParams.put("inIconId", idList);


                List<Sort> sortList = new ArrayList<>();
                //    sortList.add(new Sort("sort_no", "asc"));
                Page<PersonRoleIcon> page = personRoleIconService.pageSearch(searchParams, 1, 10, false, sortList);

                List<PersonRoleIcon> list = page.getResult();
                if (list.size() > 0) {
                    for (PersonRoleIcon personRoleIcon : list) {
                        IconInfo iconInfo = iconInfoService.get(personRoleIcon.getIconId());
                        //   PersonRoleIcon personRoleIcon = personRoleIconService.findByPersonRoleIdAndIconId(personRoleInfo.getId(),id);
                        //     if (iconInfo != null && iconInfo.getUseEnable() && personRoleIcon != null) {
                        IconInfoDTO iconInfoDTO = new IconInfoDTO();
                        BeanUtils.copyProperties(iconInfo, iconInfoDTO);
                        if (StringUtils.isNotBlank(iconInfo.getIconParam())) {
                            iconInfoDTO.setIconParam(JSONObject.parseObject(iconInfo.getIconParam()));
                        }

                        if (iconInfoList.size() < 7) {
                            iconInfoList.add(iconInfoDTO);
                        }
                        if (iconInfoList.size() >= 7) {
                            break;
                        }

                        //          }
                    }
                }*/

            }
            List<IconInfoDTO> commonIconInfoList = new ArrayList<>();
            List<PersonRoleIcon> personRoleIconList = personRoleIconService.findByPersonRoleIdAndCommonStatus(personPopedomDTO.getPersonRoleId(), true);
            if (personRoleIconList.size() > 0) {
                for (PersonRoleIcon personRoleIcon : personRoleIconList) {
                    IconInfo iconInfo = iconInfoService.get(personRoleIcon.getIconId());
                    if (iconInfo != null) {
                        IconInfoDTO iconInfoDTO = new IconInfoDTO();
                        BeanUtils.copyProperties(iconInfo, iconInfoDTO);
                        if (StringUtils.isNotBlank(iconInfo.getIconParam())) {
                            iconInfoDTO.setIconParam(JSONObject.parseObject(iconInfo.getIconParam()));
                        }

                        commonIconInfoList.add(iconInfoDTO);
                    }

                }
            }


            dataMap.put("iconInfoList", iconInfoList);
            dataMap.put("commonIconInfoList", commonIconInfoList);


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

        return messageResult;
    }

    @PostMapping("findPopedomList")
    @ApiOperation(value = "查询用户角色列表")
    public MessageResult<Map> findPopedomList(String token, @RequestAttribute String subject) {
        MessageResult<Map> messageResult = new MessageResult<>();

        try {
            PersonInfo personInfo = personInfoService.get(new Long(subject));

            if (personInfo == null) {
                messageResult.setResult(true);
                messageResult.setCode(200);
                return messageResult;

            }

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


            List<PersonPopedomDTO> list = new ArrayList<>();
            //用户角色数据
            List<PersonPopedom> personPopedomList = personPopedomService.findByPersonId(personInfo.getId());
            if (personPopedomList.size() > 0) {
                for (PersonPopedom personPopedom : personPopedomList) {
                    //公司数据
                    CompanyInfo companyInfo = companyInfoService.get(personPopedom.getCompanyId());
                    if (companyInfo != null) {


                        //系统基础角色数据
                        PersonRoleInfo personRoleInfo = personRoleInfoService.get(personPopedom.getPersonRoleId());
                        SceneInfo sceneInfo = sceneInfoService.get(personRoleInfo.getSceneId());
                        PersonPopedomDTO personPopedomDTO = new PersonPopedomDTO();
                        personPopedomDTO.setCompanyId(companyInfo.getId());
                        personPopedomDTO.setCompanyName(companyInfo.getName());
                        personPopedomDTO.setPersonRoleId(personRoleInfo.getId());

                        String name = personRoleInfo.getPersonRoleName();
                        if ("家属".equals(personRoleInfo.getPersonRoleName())) {
                            if (StringUtils.isBlank(personPopedom.getRelationPopedom())) {
                                name = name + "(未关联)";
                            } else {
                                PersonPopedom personPopedom1 = personPopedomService.get(personPopedom.getRelationPopedom());
                                if (personPopedom1 != null) {
                                    PersonInfo personInfo1 = personInfoService.get(personPopedom1.getPersonId());
                                    if (personInfo1 != null) {
                                        name = name + "(" + personInfo1.getName() + ")";
                                    }
                                }
                            }

                        } else {

                        }

                        personPopedomDTO.setPersonRoleName(name);
                        personPopedomDTO.setId(personPopedom.getId());
                        personPopedomDTO.setSceneId(personRoleInfo.getSceneId());
                        personPopedomDTO.setSceneName(sceneInfo.getSceneName());
                        personPopedomDTO.setPersonName(personInfo.getName());
                        personPopedomDTO.setFaceImagUrl(personRoleInfo.getPic());
                        list.add(personPopedomDTO);
                    }
                }
            }


            dataMap.put("list", list);
            messageResult.setData(dataMap);
            messageResult.setResult(true);
            messageResult.setCode(200);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }

        return messageResult;
    }


    @PostMapping("exchangePopedom")
    @ApiOperation(value = "切换用户角色")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户角色列表id", required = true, paramType = "form")
    })
    public MessageResult<Map> exchangePopedom(String token, @RequestAttribute String subject, String id) {
        MessageResult<Map> messageResult = new MessageResult<>();

        try {
            PersonInfo personInfo = personInfoService.get(new Long(subject));

            if (personInfo == null) {
                messageResult.setResult(true);
                messageResult.setCode(200);
                return messageResult;

            }

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

            PersonPopedom personPopedom = personPopedomService.get(id);
            if (personPopedom == null) {
                throw new Exception("选择的角色信息不存在");
            }
            if (personPopedom.getId().equals(personInfo.getPopedom())) {
                dataMap.put("update", false);//是否需要切换

            } else {
                personInfo.setCompanyId(personPopedom.getCompanyId());
                personInfo.setPopedom(personPopedom.getId());
                personInfo.setUpdateTime(new Date());
                personInfoService.update(personInfo);
                dataMap.put("update", true);//是否需要切换
            }


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

        return messageResult;
    }


    @PostMapping("logOut")
    @ApiOperation(value = "用户登出")
    public MessageResult<Map> logOut(String token, @RequestAttribute String subject) {
        MessageResult<Map> messageResult = new MessageResult<>();

        try {
            PersonInfo personInfo = personInfoService.get(new Long(subject));

            if (personInfo == null) {
                messageResult.setResult(true);
                messageResult.setCode(200);
                return messageResult;

            }

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


            personInfo.setOpenId(" ");
            personInfoService.update(personInfo);

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

        return messageResult;
    }

    @PostMapping("getVerifyCode")
    @ApiOperation(value = "获取短信验证码(公开接口)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "personId", value = "人员编号", required = true, paramType = "form"),
            @ApiImplicitParam(name = "telephone", value = "电话", required = true, paramType = "form"),
    })
    public MessageResult<String> getVerifyCode(Long personId, String telephone) {
        MessageResult<String> messageResult = new MessageResult<>();

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

            if (personInfo == null) {
                throw new Exception("人员编号不存在!");
            }*/

            PersonInfo personInfo = personInfoService.findByPhone(telephone);
            if (personInfo == null){
                throw new Exception("未导入系统，请联系管理员");
            }

            String key = "SMS_" + telephone;

            String verifyCode = (String) valueOperations.get(key);

            if (StringUtils.isEmpty(verifyCode)) {
                verifyCode = SMSUtil.generateNumberString(6);
                JSONObject verifyCodeJSON = new JSONObject();
                verifyCodeJSON.put("code", verifyCode);

                messageResult = SMSUtil.send(telephone, "SMS_49390047", verifyCodeJSON.toString());

                //设置当前用户的验证码,5分钟内有效
                valueOperations.set(key, verifyCode, 10, TimeUnit.MINUTES);
            }

            messageResult.setMessage("发送成功");
            messageResult.setResult(true);
            messageResult.setCode(200);
        } catch (Exception ex) {
            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }

        return messageResult;
    }

    @PostMapping("validateCode")
    @ApiOperation(value = "验证短信验证码(公开接口)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "personId", value = "人员编号", required = true, paramType = "form"),
            @ApiImplicitParam(name = "verifyCode", value = "验证码", required = true, paramType = "form"),
            @ApiImplicitParam(name = "openId", value = "微信openId", paramType = "form")
    })
    public MessageResult<Map> validateCode(Long personId, String verifyCode, String openId, String telephone) {
        MessageResult<Map> messageResult = new MessageResult<>();

        try {

            PersonInfo personInfo = personInfoService.findByPhone(telephone);
            if (personInfo == null){
                throw new Exception("未导入系统，请联系管理员");
            }
            String smsKey = "SMS_" + telephone;

            String beforeVerifyCode = (String) valueOperations.get(smsKey);

            if (StringUtils.isBlank(openId)){
                throw new Exception("用户openId为空");
            }


            if (StringUtils.isEmpty(beforeVerifyCode)) {
                throw new Exception("验证码已过期!");
            }

            if (!beforeVerifyCode.equals(verifyCode)) {
                throw new Exception("验证码错误!");
            }

            PersonInfo person = null;
            String token = null;
            if (StringUtils.isNotEmpty(openId)) {
            //    PersonInfo personInfo = personInfoService.get(personId);

                if (personInfo != null) {
                    personInfo.setOpenId(openId);
                    personInfo.setUpdateTime(new Date());

                    personInfoService.update(personInfo);
                    person = personInfo;
                    token = JwtUtil.createToken(jwtSecret, String.valueOf(personId), DateTime.now().plusHours(6).toDate());
                }

            }


            Map<String, Object> map = new HashMap<>();
            map.put("token", token);
            map.put("personInfo", person);

            messageResult.setData(map);
            messageResult.setResult(true);
            messageResult.setCode(200);
        } catch (Exception ex) {
            log.error(ex.getMessage());
            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }

        return messageResult;
    }

    @PostMapping("upload")
    @ApiOperation(value = "人员照片上传")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "photoName", value = "照片名称", required = true, paramType = "form"),
            @ApiImplicitParam(name = "photoFile", value = "员工照片", required = true, paramType = "form", dataType = "__file"),
            @ApiImplicitParam(name = "token", value = "令牌", required = false, paramType = "query"),
            @ApiImplicitParam(name = "subject", value = "令牌", required = false, paramType = "query")
    })
    public MessageResult<String> upload(
            String photoName, MultipartFile photoFile, String token, @RequestAttribute String subject) {
        MessageResult<String> messageResult = new MessageResult<>();

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

            if (personInfo == null) {
                throw new Exception("人员信息不存在!");
            }

//            if (personInfo.getFaceBound()!=null && personInfo.getFaceBound()){
//                throw new Exception("人员照片已绑定到设备，不能再上传!");
//            }

            String retFileUrl = OSSUtil.upload(ossConfig, "/person", photoName, photoFile.getInputStream());

            messageResult.setResult(true);
            messageResult.setData(retFileUrl);
            messageResult.setCode(200);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);

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

        return messageResult;
    }


    @PostMapping("uploadBase64")
    @ResponseBody
    @ApiOperation(value = "员工照片上传")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "photoName", value = "照片名称", required = true, paramType = "form"),
            @ApiImplicitParam(name = "photoBase64Data", value = "员工照片base64编码", required = true, paramType = "form")
    })
    public MessageResult<String> uploadBase64(String photoName, String photoBase64Data) {
        MessageResult<String> messageResult = new MessageResult<>();

        SysLog sysLog = new SysLog();
        sysLog.setPointcut("人员照片上传");

        try {
            sysLog.setRemark("base64 照片大小：" + photoBase64Data.length());

            //前50个字符
            if (StringUtils.isNotEmpty(photoBase64Data)) {
                sysLog.setData(photoBase64Data.substring(0, Math.min(photoBase64Data.length(), 50)));
            }

            BASE64Decoder decoder = new BASE64Decoder();

            String[] arr = photoBase64Data.split(",");

            byte[] imgData = decoder.decodeBuffer(arr[1]);

            for (int i = 0; i < imgData.length; ++i) {
                if (imgData[i] < 0) {// 调整异常数据
                    imgData[i] += 256;
                }
            }

            ByteArrayInputStream inputStream = new ByteArrayInputStream(imgData);

            if (StringUtils.isEmpty(photoName)) {
                photoName = "1.jpg";
            }

            String retFileUrl = OSSUtil.upload(ossConfig, "/person", photoName, inputStream);

            messageResult.setResult(true);
            messageResult.setData(retFileUrl);
            messageResult.setCode(200);

            sysLog.setUrl(retFileUrl);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);

            messageResult.setResult(false);
            messageResult.setMessage(e.getMessage());

            sysLog.setRemark(sysLog.getRemark() + "," + e.getMessage());
        }

        sysLog.setCreateTime(new Date());
        sysLogService.insert(sysLog);

        return messageResult;
    }

    @PostMapping("save")
    @ApiOperation(value = "保存人员信息并将照片上传到终端")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "personId", value = "人员编号", required = true, paramType = "form"),
            @ApiImplicitParam(name = "openId", value = "微信openId", required = true, paramType = "form"),
            @ApiImplicitParam(name = "faceImageUrl", value = "照片地址", required = true, paramType = "form"),
            @ApiImplicitParam(name = "token", value = "令牌", paramType = "form")
    })
    public MessageResult<PersonInfo> save(Long personId, String openId, String faceImageUrl, String token) {
        MessageResult<PersonInfo> messageResult = new MessageResult<>();

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

            if (personInfo == null) {
                throw new Exception("人员信息不存在!");
            }

           /* if (personInfo.getFaceBound()!=null && personInfo.getFaceBound()){
                throw new Exception("人员照片已绑定到设备，不能再上传!");
            }*/

            //todo 更新人脸照片
            personInfo.setOpenId(openId);
            personInfo.setFaceImageUrl(faceImageUrl);
            personInfo.setUpdateTime(new Date());

            personInfoService.update(personInfo);

            //todo 加入到导入图片队列中
            rabbitTemplate.convertAndSend("importImageExchange", "importImage", personId);

            messageResult.setData(personInfo);
            messageResult.setResult(true);

            messageResult.setCode(200);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);

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

        return messageResult;
    }

    @ApiOperation(value = "人员列表")
    @RequestMapping(value = "pageList", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "姓名", required = false, paramType = "form", dataType = "String"),
            @ApiImplicitParam(name = "idCard", value = "身份证", required = false, paramType = "form", dataType = "String"),
            @ApiImplicitParam(name = "phone", value = "手机号", required = false, paramType = "form", dataType = "String"),
            @ApiImplicitParam(name = "token", value = "令牌", paramType = "query", dataType = "form"),
            @ApiImplicitParam(name = "subject", value = "目标(不传)", paramType = "form")
    })
    public MessageResult<Map> pageList(
            @RequestParam(value = "name", defaultValue = "") String name,
            @RequestParam(value = "idCard", defaultValue = "") String idCard,
            @RequestParam(value = "phone", defaultValue = "") String phone,
            @RequestParam(value = "pageIndex", defaultValue = "1") int pageIndex,
            @RequestParam(value = "pageSize", defaultValue = "20") int pageSize,
            String token,
            @RequestAttribute String subject) {
        MessageResult<Map> msgResult = new MessageResult<>();

        try {
            User user = userService.get(subject);

            if (user == null) {
                throw new Exception("当前用户不是管理员！");
            }

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

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

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

            searchParams.put("companyId", user.getCompanyId());

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

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


        return msgResult;
    }

    @PostMapping("add")
    @ApiOperation(value = "添加人员信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "姓名", required = true, paramType = "form"),
            @ApiImplicitParam(name = "phone", value = "电话", required = true, paramType = "form"),
            @ApiImplicitParam(name = "faceImageUrl", value = "照片地址", required = true, paramType = "form"),
            @ApiImplicitParam(name = "bindDevices", value = "绑定设备(,分隔)", required = true, paramType = "form"),
            @ApiImplicitParam(name = "token", value = "令牌", paramType = "form"),
            @ApiImplicitParam(name = "subject", value = "目标(不传)", paramType = "form")
    })
    public MessageResult<PersonInfo> add(String name, String phone, String faceImageUrl, String bindDevices, String token, @RequestAttribute String subject) {
        MessageResult<PersonInfo> messageResult = new MessageResult<>();

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

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

            if (StringUtils.isEmpty(admin.getPopedom())
                    && admin.getPopedom().indexOf("2") == -1) {
                throw new Exception("当前用户不是管理员！");
            }

            PersonInfo personInfo = personInfoService.findByNameAndPhone(name, phone);

            if (personInfo == null) {
                personInfo = new PersonInfo();
                personInfo.setCompanyId(companyId);
                personInfo.setName(name);
                personInfo.setPhone(phone);
                personInfo.setFaceEnabled(true);
                personInfo.setFaceImageUrl(faceImageUrl);
                personInfo.setPopedom("1");
                personInfo.setWorkStatus("1");
                personInfo.setDelFlag(false);
                personInfo.setCreateBy(String.valueOf(admin.getId()));
                personInfo.setCreateTime(new Date());

                //插入后，会将自增id写到id属性中
                int affectCount = personInfoService.insert(personInfo);

                //todo 关联设备
                String[] deviceIds = bindDevices.split(",");

                for (String deviceId : deviceIds) {
                    PersonDeviceRelation personDeviceRelation = new PersonDeviceRelation();
                    personDeviceRelation.setId(UUID.randomUUID().toString());
                    personDeviceRelation.setDeviceId(deviceId);
                    personDeviceRelation.setPersonId(personInfo.getId());
                    personDeviceRelation.setDelFlag(false);
                    personDeviceRelation.setCreateBy(subject);
                    personDeviceRelation.setCreateTime(new Date());
                    personDeviceRelationService.insert(personDeviceRelation);
                }

                if (affectCount > 0) {
                    //todo 加入到导入图片队列中
                    rabbitTemplate.convertAndSend("importImageExchange", "importImage", personInfo.getId());
                }

                messageResult.setData(personInfo);
                messageResult.setResult(true);
                messageResult.setCode(200);
            } else {
                messageResult.setResult(false);
                messageResult.setMessage("人员已存在。");
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            messageResult.setResult(false);
            messageResult.setMessage(e.getMessage());
        }

        return messageResult;
    }


    @PostMapping("register")
    @ApiOperation(value = "注册")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "personId", value = "用户id", required = false, paramType = "form"),
            @ApiImplicitParam(name = "sceneId", value = "场景id", required = true, paramType = "form"),
            @ApiImplicitParam(name = "companyId", value = "公司id", required = false, paramType = "form"),
            @ApiImplicitParam(name = "personRoleId", value = "角色id", required = true, paramType = "form"),
            @ApiImplicitParam(name = "companyStructureId", value = "机构id", required = false, paramType = "form"),
            @ApiImplicitParam(name = "name", value = "姓名", required = true, paramType = "form"),
            @ApiImplicitParam(name = "telephone", value = "电话", required = true, paramType = "form"),
            @ApiImplicitParam(name = "address", value = "地址", required = false, paramType = "form"),
            @ApiImplicitParam(name = "idCard", value = "身份证号码", required = false, paramType = "form"),
            @ApiImplicitParam(name = "faceImageUrl", value = "人脸", required = false, paramType = "form"),
            @ApiImplicitParam(name = "popularizePersonId", value = "推广者id", required = false, paramType = "form"),
            @ApiImplicitParam(name = "openId",value = "openId",required = true,paramType = "form")
    })
    public MessageResult<PersonInfo> register(String personId, String sceneId, String companyId, String personRoleId, String companyStructureId, String name, String telephone, String address, String idCard, String faceImageUrl, String serviceCompanyId, String popularizePersonId,String openId) {
        MessageResult<PersonInfo> messageResult = new MessageResult<>();

            try {
                String key = "personInfo_register_" + telephone;

                //3秒内不能重复注册
            boolean lockSuccess = valueOperations.setIfAbsent(key, true, 3, TimeUnit.SECONDS);

            if (!lockSuccess) {
                throw new Exception("注册过于频繁！");
            }

            PersonApplicationInfo personApplicationInfo0 = personApplicationInfoService.findIsExistApply(companyId, telephone, "0");
            if (personApplicationInfo0 != null) {
                throw new Exception("您有一条申请正在审核中");
            }

            PersonApplicationInfo personApplicationInfo1 = personApplicationInfoService.findIsExistApply(companyId, telephone, "1");
            if (personApplicationInfo1 != null){
                PersonInfo personInfo = personInfoService.findByPhone(telephone);
                if (personInfo != null){
                    throw new Exception("您的注册审核已通过，可以直接登录");
                }else {
                    personApplicationInfo1.setDelFlag(true);
                    personApplicationInfoService.update(personApplicationInfo1);
                }

            }


            PersonApplicationInfo personApplicationInfo = new PersonApplicationInfo();

            //居家养老特殊处理
            if ("4".equals(sceneId)) {
                if (StringUtils.isBlank(companyId) || "0".equals(companyId)) {
                    CompanyInfo companyInfo = companyInfoService.findByName("居家养老");
                    if (companyInfo == null) {
                        throw new Exception("未配置居家养老所属公司");
                    }
                    companyId = companyInfo.getId();
                }

                if (StringUtils.isBlank(serviceCompanyId)) {
                    throw new Exception("居家养老需选择服务公司");
                }
                if (StringUtils.isNotBlank(personId)) {
                    List<PersonPopedom> personPopedomList = personPopedomService.findByPersonId(Long.valueOf(personId));
                    if (personPopedomList.size() > 0) {
                        for (PersonPopedom personPopedom : personPopedomList) {
                            if (personPopedom.getCompanyId().equals(companyId) && personPopedom.getPersonRoleId().equals(personRoleId)) {
                                throw new Exception("您已经注册过此场景下的角色");
                            }

                        }
                    }
                }

                personApplicationInfo.setId(UUID.randomUUID().toString());
                if (StringUtils.isNotBlank(personId)) {
                    personApplicationInfo.setPersonId(Long.valueOf(personId));
                }

                personApplicationInfo.setCompanyId(companyId);
                personApplicationInfo.setServiceCompanyId(serviceCompanyId);
                personApplicationInfo.setName(name);
                personApplicationInfo.setApplicantTime(new Date());
                personApplicationInfo.setPersonRoleId(personRoleId);
                personApplicationInfo.setTelephone(telephone);
                personApplicationInfo.setIdCard(idCard.toUpperCase());
                personApplicationInfo.setFaceImageUrl(faceImageUrl);
                personApplicationInfo.setAddress(address);
                personApplicationInfo.setSceneId(sceneId);
                personApplicationInfo.setStatus("1");
                personApplicationInfo.setCreateTime(new Date());
                personApplicationInfo.setExamineName("自动审核");
                personApplicationInfo.setExamineTime(new Date());
                personApplicationInfo.setDelFlag(false);
                personApplicationInfo.setOpenId(openId);
                if (StringUtils.isNotBlank(popularizePersonId)) {
                    personApplicationInfo.setPopularizePersonId(Long.valueOf(popularizePersonId));
                }
                personApplicationInfoService.insert(personApplicationInfo);

                personInfoService.insertPersonAndPopedom(personApplicationInfo, null, null);


                messageResult.setResult(true);
                messageResult.setCode(200);
            } else {
                if (StringUtils.isBlank(companyId)) {
                    throw new Exception("所属公司不能为空");
                }
                if (StringUtils.isNotBlank(personId)) {
                    List<PersonPopedom> personPopedomList = personPopedomService.findByPersonId(Long.valueOf(personId));
                    if (personPopedomList.size() > 0) {
                        for (PersonPopedom personPopedom : personPopedomList) {
                            if (companyId.equals(personPopedom.getCompanyId()) && companyStructureId.equals(personPopedom.getCompanyStructureId()) && personRoleId.equals(personPopedom.getPersonRoleId())) {
                                throw new Exception("您已经注册过该公司下的角色");
                            }

                        }
                    }
                }


                personApplicationInfo.setId(UUID.randomUUID().toString());
                if (StringUtils.isNotBlank(personId)) {
                    personApplicationInfo.setPersonId(Long.valueOf(personId));
                }
                //     personApplicationInfo.setPersonId(Long.valueOf(personId));
                personApplicationInfo.setCompanyId(companyId);
                personApplicationInfo.setName(name);
                personApplicationInfo.setApplicantTime(new Date());
                personApplicationInfo.setPersonRoleId(personRoleId);
                personApplicationInfo.setStructureId(companyStructureId);
                personApplicationInfo.setTelephone(telephone);
                personApplicationInfo.setIdCard(idCard);
                personApplicationInfo.setFaceImageUrl(faceImageUrl);
                personApplicationInfo.setAddress(address);
                personApplicationInfo.setSceneId(sceneId);
                personApplicationInfo.setStatus("0");
                personApplicationInfo.setCreateTime(new Date());
                personApplicationInfo.setDelFlag(false);
                personApplicationInfo.setOpenId(openId);
                if (StringUtils.isNotBlank(popularizePersonId)) {
                    personApplicationInfo.setPopularizePersonId(Long.valueOf(popularizePersonId));
                }
                personApplicationInfoService.insert(personApplicationInfo);

                messageResult.setResult(true);
                messageResult.setCode(200);


                if (StringUtils.isNotBlank(personId)) {
                    //发送通知
                    messageInfoService.sendForPerson(Long.valueOf(personId), Long.valueOf(personId), "身份注册提醒", "注册等待审核中...", "1");
                }

                //异步发审核人消息
                new Thread(() -> {

                    try {
                        personInfoService.sendRegisterMessage(personApplicationInfo);
                    } catch (Exception ex) {
                        log.error(ex.getMessage(), ex);
                    }


                }).start();
            }


        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            messageResult.setResult(false);
            messageResult.setCode(400);
            messageResult.setMessage(e.getMessage());
        }

        return messageResult;
    }

    @ApiOperation(value = "保存人员信息并将照片上传到终端")
    @PostMapping("saveDetail")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "姓名", required = false, paramType = "form"),
            @ApiImplicitParam(name = "phone", value = "手机号码", required = false, paramType = "form"),
            @ApiImplicitParam(name = "idCard", value = "身份证号", required = false, paramType = "form"),
            @ApiImplicitParam(name = "wechatNoticeEnabled", value = "是否接收微信通知", required = false, paramType = "form", dataType = "Boolean"),
            @ApiImplicitParam(name = "openId", value = "微信openId", required = true, paramType = "form"),
            @ApiImplicitParam(name = "faceImageUrl", value = "用户头像", required = false, paramType = "form"),
            @ApiImplicitParam(name = "carNum", value = "车牌号", required = false, paramType = "form"),
            @ApiImplicitParam(name = "jobNumber", value = "工号", required = false, paramType = "form"),
            @ApiImplicitParam(name = "token", value = "令牌", paramType = "form")
    })
    public MessageResult<PersonInfo> saveDetail(String name, String phone, String idCard, Boolean wechatNoticeEnabled, String openId, String faceImageUrl,String carNum,String jobNumber, String token) {
        MessageResult<PersonInfo> messageResult = new MessageResult<>();

        try {
            PersonInfo personInfo = personInfoService.findByOpenId(openId);

            if (personInfo == null) {
                throw new Exception("人员信息不存在!");
            }

            CheckIdCard cic = null;
            if (StringUtils.isEmpty(idCard)) {
//                    msgResult.setMessage("身份证不能为空!");
//                    msgResult.setResult(false);
//                    return msgResult;
            } else {
                personInfo.setIdCard(idCard.trim().toUpperCase());

                cic = new CheckIdCard(personInfo.getIdCard());
                if (!cic.validate()) {
                    messageResult.setMessage("身份证验证失败!");
                    messageResult.setResult(false);
                    return messageResult;
                }
            }

            personInfo.setName(name);
            personInfo.setPhone(phone);

            if (wechatNoticeEnabled != null) {
                personInfo.setWechatNoticeEnabled(wechatNoticeEnabled);
            }


            String oldFaceImageUrl = personInfo.getFaceImageUrl();

            personInfo.setFaceImageUrl(faceImageUrl);

            //新上传的照片地址不同
            if (StringUtils.isNotEmpty(faceImageUrl) && !faceImageUrl.equals(oldFaceImageUrl)) {
                //todo 检测照片质量
                MessageResult<String> detectResult = bceFaceService.smartDetect(faceImageUrl);

                if (!detectResult.isResult()) {
                    throw new Exception(detectResult.getMessage());
                }

                rabbitTemplate.convertAndSend("importImageExchange", "importImage", personInfo.getId());
            }

            personInfo.setUpdateTime(new Date());
            if (StringUtils.isNotBlank(carNum)){
                personInfo.setCarNum(carNum);
            }
            if (StringUtils.isNotBlank(jobNumber)){
                personInfo.setJobNumber(jobNumber);
            }
            personInfoService.update(personInfo);

            messageResult.setData(personInfo);
            messageResult.setResult(true);

            messageResult.setCode(200);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);

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

        return messageResult;
    }

    @PostMapping("updateIdCard")
    @ResponseBody
    @ApiOperation(value = "更新身份证号码")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "idCard", value = "身份证号码", required = true, paramType = "form"),
            @ApiImplicitParam(name = "token", value = "令牌", required = true, paramType = "form"),
            @ApiImplicitParam(name = "subject", value = "目标(不传)", paramType = "form")
    })
    public MessageResult<Map> updateIdCard(String name, String idCard, String token, @RequestAttribute String subject) {

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

        try {
            PersonInfo person = personInfoService.get(Long.valueOf(subject));
            if (StringUtils.isBlank(idCard)) {
                throw new Exception("身份证为空");
            }
            CheckIdCard cic = null;
            cic = new CheckIdCard(idCard);
            if (!cic.validate()) {
                throw new Exception("身份证号码错误");
            }

            person.setName(name);
            person.setIdCard(IdCardUtils.encrypt(idCard.toUpperCase()));
            personInfoService.update(person);
            messageResult.setResult(true);
            messageResult.setCode(200);
            messageResult.setMessage("更新成功");

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

        return messageResult;


    }

    @PostMapping("problemFeedback")
    @ApiOperation(value = "问题反馈")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "content", value = "问题内容", required = false, paramType = "form"),
            @ApiImplicitParam(name = "picUrl", value = "图片地址", required = false, paramType = "form"),
            @ApiImplicitParam(name = "telephone", value = "联系电话", required = false, paramType = "form"),
            @ApiImplicitParam(name = "subject", value = "目标(不传)", paramType = "form")
    })
    public MessageResult<Map> problemFeedback(String token, @RequestAttribute String subject, String content, String picUrl, String telephone) {
        MessageResult<Map> messageResult = new MessageResult<>();

        try {
            PersonInfo personInfo = personInfoService.get(new Long(subject));

            if (personInfo == null) {
                messageResult.setResult(true);
                messageResult.setCode(200);
                return messageResult;

            }

            if (StringUtils.isBlank(content)) {
                throw new Exception("请输入反馈内容");
            }

            Map<String, Object> dataMap = new HashMap<String, Object>();
            ProblemFeedback problemFeedback = new ProblemFeedback();
            problemFeedback.setId(UUID.randomUUID().toString());
            problemFeedback.setProblemContent(content);
            problemFeedback.setProblemPic(picUrl);
            problemFeedback.setContactTelephone(telephone);
            problemFeedback.setCreateBy(personInfo.getId().toString());
            problemFeedback.setCreateTime(new Date());
            problemFeedbackService.insert(problemFeedback);


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

        return messageResult;
    }

    @PostMapping("applicationPersonList")
    @ApiOperation(value = "注册申请人员列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "令牌", required = true, paramType = "form"),
            @ApiImplicitParam(name = "subject", value = "目标(不传)", paramType = "form"),
            @ApiImplicitParam(name = "status", value = "状态（0：待处理，1：已处理）", required = true, paramType = "form"),
            @ApiImplicitParam(name = "name", value = "姓名", required = false, paramType = "form")
    })
    public MessageResult<Map> applicationPersonList(String token, @RequestAttribute String subject, String status,String name, @RequestParam(value = "pageIndex", defaultValue = "1") int pageIndex, @RequestParam(value = "pageSize", defaultValue = "20") int pageSize) {
        MessageResult<Map> messageResult = new MessageResult<>();

        try {
            PersonInfo personInfo = personInfoService.get(new Long(subject));

            if (personInfo == null) {
                messageResult.setResult(true);
                messageResult.setCode(200);
                return messageResult;

            }
            PersonPopedom personPopedom = personPopedomService.get(personInfo.getPopedom());
            CompanyInfo companyInfo = companyInfoService.get(personPopedom.getCompanyId());

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

            Page<PersonApplicationInfo> page = new Page<>();

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




            //判断是否有审核权限
            if (personPopedom.getEnableRegisterExamine()) {

                if (StringUtils.isNotBlank(name)){

                    if (NumberUtil.isNumber(name)){
                        searchParams.put("telephone", "%" + name+ "%");
                    }else {
                        searchParams.put("name", "%" + name+ "%");
                    }

                }


                List<CompanyInfo> companyInfoList = companyInfoService.findAllCompanyByCode(companyInfo.getCode() + "%");
                if ("2".equals(companyInfo.getSceneId())){
                    if (companyInfoList.size() > 0) {
                        for (CompanyInfo companyInfo1 : companyInfoList) {
                            if (!companyIdList.contains(companyInfo1.getId())) {
                                companyIdList.add(companyInfo1.getId());
                            }
                        }
                    }
                    searchParams.put("InCompanyId", companyIdList);
                }

                //工厂园区场景，不是为居家养老服务的公司
                if ("1".equals(companyInfo.getSceneId()) && !"4".equals(companyInfo.getType())) {

                    //   List<CompanyInfo> companyInfoList = companyInfoService.findAllCompanyByCode("%" + companyInfo.getId() + "%");
                    List<CompanyInfo> serviceCompanyList = companyInfoService.findByRelationCompanyId(companyInfo.getId());

                    if (companyInfoList.size() > 0) {
                        for (CompanyInfo companyInfo1 : companyInfoList) {
                            if (!companyIdList.contains(companyInfo1.getId())) {
                                companyIdList.add(companyInfo1.getId());
                            }
                        }
                    }
                    if (serviceCompanyList.size() > 0) {
                        for (CompanyInfo companyInfo1 : serviceCompanyList) {
                            if (!companyIdList.contains(companyInfo1.getId())) {
                                companyIdList.add(companyInfo1.getId());
                            }
                        }
                    }

                    searchParams.put("InCompanyId", companyIdList);
                    searchParams.put("serviceCompanyIdIsNull", "0");
                }

                //为居家养老服务的公司
                if ("1".equals(companyInfo.getSceneId()) && "4".equals(companyInfo.getType())) {
                    companyIdList.add(companyInfo.getId());

                    searchParams.put("serviceCompanyId", companyInfo.getId());

                }


                //未处理的注册申请
                if ("0".equals(status)) {

                    searchParams.put("status", "0");
                    List<Sort> sortList = new ArrayList<>();
                    sortList.add(new Sort("a.applicant_time", "desc"));
                    page = personApplicationInfoService.pageSearch(searchParams, pageIndex, pageSize, true, sortList);

                }

                //已经处理的注册申请
                if ("1".equals(status)) {
                    //    Map<String, Object> searchParams = new HashMap<>();
                    //   searchParams.put("InCompanyId", companyIdList);
                    searchParams.put("notStatus", "0");
                    List<Sort> sortList = new ArrayList<>();
                    sortList.add(new Sort("a.applicant_time", "desc"));
                    page = personApplicationInfoService.pageSearch(searchParams, pageIndex, pageSize, true, sortList);
                }


                List<PersonApplicationInfo> personApplicationInfoList = page.getResult();
                if (personApplicationInfoList.size() > 0) {
                    for (PersonApplicationInfo personApplicationInfo : personApplicationInfoList) {
                        if ("0".equals(personApplicationInfo.getStatus())) {
                            personApplicationInfo.setStatusN("未审核");
                        }
                        if ("1".equals(personApplicationInfo.getStatus())) {
                            personApplicationInfo.setStatusN("同意");
                        }
                        if ("2".equals(personApplicationInfo.getStatus())) {
                            personApplicationInfo.setStatusN("拒绝");
                        }
                    }
                }

            }


            messageResult.setData(PojoUtils.pageWrapper(page));
            messageResult.setResult(true);
            messageResult.setCode(200);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }

        return messageResult;
    }

    @PostMapping("applicationPersonDetail")
    @ApiOperation(value = "注册人员详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "令牌", required = true, paramType = "form"),
            @ApiImplicitParam(name = "subject", value = "目标(不传)", paramType = "form"),
            @ApiImplicitParam(name = "id", value = "id", required = true, paramType = "form"),
    })
    public MessageResult<PersonApplicationInfo> applicationPersonDetail(String token, @RequestAttribute String subject, String id) {
        MessageResult<PersonApplicationInfo> messageResult = new MessageResult<>();

        try {
            PersonInfo personInfo = personInfoService.get(new Long(subject));

            if (personInfo == null) {
                messageResult.setResult(true);
                messageResult.setCode(200);
                return messageResult;

            }

            PersonApplicationInfo personApplicationInfo = personApplicationInfoService.get(id);
            if (personApplicationInfo == null) {
                throw new Exception("申请人信息不存在");
            }
            String structureName = "无";
            if (StringUtils.isNotBlank(personApplicationInfo.getStructureId())) {


                CompanyStructureInfo companyStructureInfo = companyStructureInfoService.get(personApplicationInfo.getStructureId());

                String parentId = companyStructureInfo.getParentId();
                structureName = companyStructureInfo.getStructureName();
                while (StringUtils.isNotBlank(parentId)) {
                    CompanyStructureInfo companyStructureInfo1 = companyStructureInfoService.get(parentId);
                    structureName = companyStructureInfo1.getStructureName() + " " + structureName;
                    parentId = companyStructureInfo1.getParentId();
                }


            }

            if ("0".equals(personApplicationInfo.getStatus())) {
                personApplicationInfo.setStatusN("未审核");
            }
            if ("1".equals(personApplicationInfo.getStatus())) {
                personApplicationInfo.setStatusN("同意");
            }
            if ("2".equals(personApplicationInfo.getStatus())) {
                personApplicationInfo.setStatusN("拒绝");
            }

            personApplicationInfo.setStructureName(structureName);

            if (StringUtils.isBlank(personApplicationInfo.getExamineName()) && StringUtils.isNotBlank(personApplicationInfo.getExaminePopedomId())) {
                PersonPopedom personPopedom = personPopedomService.get(personApplicationInfo.getExaminePopedomId());
                if (personPopedom != null) {
                    PersonInfo personInfo1 = personInfoService.get(personPopedom.getPersonId());
                    if (personInfo1 != null) {
                        personApplicationInfo.setExamineName(personInfo1.getName());
                    }
                }
            }


            messageResult.setData(personApplicationInfo);
            messageResult.setResult(true);
            messageResult.setCode(200);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }

        return messageResult;
    }

    @PostMapping("examineApplicationPerson")
    @ApiOperation(value = "审核注册人员")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "令牌", required = true, paramType = "form"),
            @ApiImplicitParam(name = "subject", value = "目标(不传)", paramType = "form"),
            @ApiImplicitParam(name = "ids", value = "ids", required = true, paramType = "form"),
            @ApiImplicitParam(name = "status", value = "通过/拒绝（1/2）", required = true, paramType = "form"),
            @ApiImplicitParam(name = "deviceIds", value = "设备ids", required = false, paramType = "form"),
            @ApiImplicitParam(name = "companyId", value = "分配的公司或部门", required = false, paramType = "form"),

    })
    public MessageResult<PersonApplicationInfo> examineApplicationPerson(String token, @RequestAttribute String subject, String ids, String status, String deviceIds, String companyId) {
        MessageResult<PersonApplicationInfo> messageResult = new MessageResult<>();

        try {
            PersonInfo personInfo = personInfoService.get(new Long(subject));

            if (personInfo == null) {
                messageResult.setResult(true);
                messageResult.setCode(200);
                return messageResult;

            }
            if (StringUtils.isBlank(ids)) {
                throw new Exception("请选择要处理的对象");
            }
            if (StringUtils.isBlank(status)) {
                throw new Exception("请选择处理结果");
            }
            personApplicationInfoService.examineApplicationPerson(personInfo,null, ids, status, deviceIds, companyId);


            messageResult.setResult(true);
            messageResult.setCode(200);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }

        return messageResult;
    }

    @PostMapping("examineCompanyList")
    @ApiOperation(value = "审核人员的公司列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "令牌", required = true, paramType = "form"),
            @ApiImplicitParam(name = "subject", value = "目标(不传)", paramType = "form"),
            @ApiImplicitParam(name = "companyId", value = "公司id", required = false, paramType = "form")

    })
    public MessageResult<Map> examineCompanyList(String token, @RequestAttribute String subject, String companyId) {
        MessageResult<Map> messageResult = new MessageResult<>();

        try {
            PersonInfo personInfo = personInfoService.get(new Long(subject));

            if (personInfo == null) {
                messageResult.setResult(true);
                messageResult.setCode(200);
                return messageResult;

            }
            PersonPopedom personPopedom = personPopedomService.get(personInfo.getPopedom());
            //当前角色所属公司
            CompanyInfo companyInfo = companyInfoService.get(personPopedom.getCompanyId());
            List<CompanyInfo> list = new ArrayList<>();

            if (StringUtils.isBlank(companyId)) {

                boolean hasNext = false;
                List<CompanyInfo> companyInfoList = companyInfoService.findByParentId(companyInfo.getId());
                if (companyInfoList.size() > 0) {
                    hasNext = true;
                }
                companyInfo.setHasNext(hasNext);
                list.add(companyInfo);
            } else {
                List<CompanyInfo> companyInfoList = companyInfoService.findByParentId(companyId);
                if (companyInfoList.size() > 0) {
                    for (CompanyInfo companyInfo1 : companyInfoList) {
                        boolean hasNext = false;
                        List<CompanyInfo> companyInfoList1 = companyInfoService.findByParentId(companyInfo1.getId());
                        if (companyInfoList1.size() > 0) {
                            hasNext = true;
                        }
                        companyInfo1.setHasNext(hasNext);
                        list.add(companyInfo1);
                    }
                }
                //    list.addAll(companyInfoList);
            }
            Map<String, Object> map = new HashMap<>();
            map.put("list", list);
            messageResult.setData(map);
            messageResult.setResult(true);
            messageResult.setCode(200);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }

        return messageResult;
    }


    @PostMapping("relationOlder")
    @ApiOperation(value = "关联长者")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "personId", value = "personId", required = false, paramType = "form"),
            @ApiImplicitParam(name = "olderPopedomId", value = "olderPopedomId", required = false, paramType = "form"),
            @ApiImplicitParam(name = "name", value = "姓名", required = true, paramType = "form"),
            @ApiImplicitParam(name = "telephone", value = "电话", required = true, paramType = "form"),
            @ApiImplicitParam(name = "idCard", value = "身份证", required = false, paramType = "form"),
            @ApiImplicitParam(name = "address", value = "地址", required = false, paramType = "form"),
            @ApiImplicitParam(name = "relationName", value = "关系名称", required = true, paramType = "form"),
            @ApiImplicitParam(name = "faceImageUrl", value = "人脸", required = true, paramType = "form"),
            @ApiImplicitParam(name = "openId", value = "openId", required = true, paramType = "form"),

    })
    public MessageResult<PersonApplicationInfo> relationOlder(String personId, String olderPopedomId, String name, String telephone, String idCard, String address, String relationName, String faceImageUrl, String openId) {
        MessageResult<PersonApplicationInfo> messageResult = new MessageResult<>();

        try {

            PersonPopedom personPopedom = personPopedomService.get(olderPopedomId);
            if (personPopedom == null) {
                throw new Exception("长者不存在");
            }
            PersonRoleInfo personRoleInfo = personRoleInfoService.get(personPopedom.getPersonRoleId());
            if (!"长者".equals(personRoleInfo.getPersonRoleName())) {
                throw new Exception("被关联者不是长者");
            }

            //personId为空时注册信息并绑定长者
            if (StringUtils.isBlank(personId)) {
                //创建personInfo
                PersonInfo personInfo = new PersonInfo();
                personInfo.setCompanyId(personPopedom.getCompanyId());
                personInfo.setName(name);
                personInfo.setIdCard(idCard);
                personInfo.setPhone(telephone);
                personInfo.setOpenId(openId);
                personInfo.setFaceEnabled(true);
                personInfo.setGuestEnabled(false);
                personInfo.setWorkStatus("1");
                personInfo.setFaceImageUrl(faceImageUrl);
                personInfo.setDelFlag(false);
                personInfo.setCreateTime(new Date());
                personInfoService.insert(personInfo);

                //创建personPopedom
                PersonPopedom personPopedom1 = new PersonPopedom();
                personPopedom1.setId(UUID.randomUUID().toString());
                personPopedom1.setCompanyId(personPopedom.getCompanyId());

                PersonRoleInfo personRoleInfo1 = personRoleInfoService.findByRoleNameAndSceneId("家属", personRoleInfo.getSceneId());
                if (personRoleInfo1 == null) {
                    throw new Exception("未配置家属角色");
                }
                personPopedom1.setPersonRoleId(personRoleInfo1.getId());
                personPopedom1.setPersonId(personInfo.getId());
                personPopedom1.setShowIconId(personRoleIconService.getDefaultIcon(personRoleInfo1.getId()));
                personPopedom1.setDelFlag(false);
                personPopedom1.setCreateTime(new Date());
                personPopedom1.setAddress(address);
                personPopedom1.setRelationName(relationName);
                personPopedom1.setRelationPopedom(olderPopedomId);
                personPopedomService.insert(personPopedom1);
                personInfo.setPopedom(personPopedom1.getId());
                personInfoService.update(personInfo);

            }
            //只绑定长者信息
            else {
                PersonPopedom personPopedom1 = new PersonPopedom();
                personPopedom1.setId(UUID.randomUUID().toString());
                personPopedom1.setCompanyId(personPopedom.getCompanyId());

                PersonRoleInfo personRoleInfo1 = personRoleInfoService.findByRoleNameAndSceneId("家属", personRoleInfo.getSceneId());
                if (personRoleInfo1 == null) {
                    throw new Exception("未配置家属角色");
                }
                personPopedom1.setPersonRoleId(personRoleInfo1.getId());
                personPopedom1.setPersonId(Long.valueOf(personId));
                personPopedom1.setShowIconId(personRoleIconService.getDefaultIcon(personRoleInfo1.getId()));
                personPopedom1.setDelFlag(false);
                personPopedom1.setCreateTime(new Date());
                personPopedom1.setAddress(address);
                personPopedom1.setRelationName(relationName);
                personPopedom1.setRelationPopedom(olderPopedomId);
                personPopedomService.insert(personPopedom1);

            }


            messageResult.setResult(true);
            messageResult.setCode(200);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }

        return messageResult;
    }

    @PostMapping("olderDetail")
    @ApiOperation(value = "长者详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "olderPopedomId", value = "id", required = false, paramType = "form")
    })
    public MessageResult<PersonPopedomDTO> olderDetail(String olderPopedomId) {
        MessageResult<PersonPopedomDTO> messageResult = new MessageResult<>();

        try {

            PersonPopedomDTO personPopedomDTO = new PersonPopedomDTO();
            if (StringUtils.isNotBlank(olderPopedomId)) {
                PersonPopedom personPopedom = personPopedomService.get(olderPopedomId);
                if (personPopedom == null) {
                    throw new Exception("角色信息不存在");
                }

                String address = "";
                PersonInfo personInfo = personInfoService.get(personPopedom.getPersonId());
                CompanyInfo companyInfo = companyInfoService.get(personPopedom.getCompanyId());
                PersonRoleInfo personRoleInfo = personRoleInfoService.get(personPopedom.getPersonRoleId());
                if ("居家养老".equals(personRoleInfo.getSceneName())) {
                    address = personPopedom.getAddress();
                }
                if ("机构养老".equals(personRoleInfo.getSceneName())) {
                    String structureName = "";
                    if (StringUtils.isNotBlank(personPopedom.getCompanyStructureId())) {
                        CompanyStructureInfo companyStructureInfo = companyStructureInfoService.get(personPopedom.getCompanyStructureId());

                        String parentId = companyStructureInfo.getParentId();
                        structureName = companyStructureInfo.getStructureName();
                        while (StringUtils.isNotBlank(parentId)) {
                            CompanyStructureInfo companyStructureInfo1 = companyStructureInfoService.get(parentId);
                            structureName = companyStructureInfo1.getStructureName() + " " + structureName;
                            parentId = companyStructureInfo1.getParentId();
                        }
                    }

                    address = companyInfo.getName() + " " + structureName;
                }


                personPopedomDTO.setPersonName(personInfo.getName());
                personPopedomDTO.setFaceImagUrl(personInfo.getFaceImageUrl());
                personPopedomDTO.setAddress(address);


            }


            messageResult.setData(personPopedomDTO);
            messageResult.setResult(true);
            messageResult.setCode(200);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }

        return messageResult;
    }


    @PostMapping("submitParkingApply")
    @ApiOperation(value = "提交车位申请")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "令牌", required = true, paramType = "form"),
            @ApiImplicitParam(name = "subject", value = "目标(不传)", paramType = "form"),
            @ApiImplicitParam(name = "carNum", value = "车牌号", required = true, paramType = "form"),
            @ApiImplicitParam(name = "parkingId", value = "车位id", required = true, paramType = "form"),
            @ApiImplicitParam(name = "parkingName", value = "车位名称", required = true, paramType = "form"),
            @ApiImplicitParam(name = "startTime", value = "开始时间", required = true, paramType = "form"),
            @ApiImplicitParam(name = "num", value = "日期数量", required = true, paramType = "form"),
            @ApiImplicitParam(name = "unitId", value = "日期单位", required = true, paramType = "form")
    })
    public MessageResult<PersonApplicationInfo> submitParkingApply(String token, @RequestAttribute String subject, String carNum, String parkingId, String parkingName, String startTime, String num, String unitId) {
        MessageResult<PersonApplicationInfo> messageResult = new MessageResult<>();

        try {
            PersonInfo personInfo = personInfoService.get(new Long(subject));

            String key = "personInfo_register_" + personInfo.getId();

            //10秒内不能重复提交
            boolean lockSuccess = valueOperations.setIfAbsent(key, true, 10, TimeUnit.SECONDS);

            if (!lockSuccess) {
                throw new Exception("操作过于频繁！");
            }


            PersonPopedom personPopedom = personPopedomService.get(personInfo.getPopedom());

            //车位信息
            ParkingInfo parkingInfo = parkingInfoService.get(parkingId);
            if (parkingInfo == null) {
                throw new Exception("没有此车位信息");
            }

            //日期单位信息
            ParkingWay parkingWay = parkingWayService.get(unitId);
            if (parkingWay == null) {
                throw new Exception("没有此日期单位");
            }

            //查询是否已经有一条未处理的申请记录
            ParkingApply parkingApply0 = parkingApplyService.findByPopedomIdAndStatus(personPopedom.getId(), "0");
            if (parkingApply0 != null) {
                throw new Exception("您已有一条待处理的车位申请记录");
            }
            //查询是否有已处理但未支付的审计记录
            ParkingApply parkingApply1 = parkingApplyService.findByPopedomIdAndPayStatus(personPopedom.getId(), 10);
            if (parkingApply1 != null) {
                throw new Exception("您有一条待支付的车位申请记录");
            }


            //预估费用
            BigDecimal cost = parkingWay.getMoney().multiply(new BigDecimal(num));

            ParkingApply parkingApply = new ParkingApply();
            parkingApply.setId(UUID.randomUUID().toString());
            parkingApply.setCreateBy(personPopedom.getId());
            parkingApply.setCreateTime(new Date());
            parkingApply.setDelFlag(false);
            parkingApply.setParkingId(parkingId);
            parkingApply.setParkingName(parkingName);
            parkingApply.setPopedomId(personPopedom.getId());
            parkingApply.setContractDuration(num + parkingWay.getName());
            parkingApply.setStartTime(DateUtil.parse(startTime, "yyyy-MM-dd"));
            parkingApply.setCarNum(carNum);
            parkingApply.setEstimateFee(cost.setScale(2));
            if ("日".equals(parkingWay.getName())) {
                parkingApply.setEndTime(DateUtil.offsetSecond(DateUtil.offsetDay(parkingApply.getStartTime(), Integer.valueOf(num)), -1));
            }
            if ("月".equals(parkingWay.getName())) {
                parkingApply.setEndTime(DateUtil.offsetSecond(DateUtil.offsetMonth(parkingApply.getStartTime(), Integer.valueOf(num)), -1));
            }
            if ("年".equals(parkingWay.getName())) {
                parkingApply.setEndTime(DateUtil.offsetSecond(DateUtil.offset(parkingApply.getStartTime(), DateField.YEAR, Integer.valueOf(num)), -1));
            }

            parkingApply.setStatus("0");
            parkingApply.setCompanyId(parkingInfo.getCompanyId());
            parkingApplyService.insert(parkingApply);

            //申请成功后发送待办事件
            new Thread(() -> {
                try {
                    personInfoService.sendParkingMessage(parkingApply);
                } catch (Exception ex) {
                    log.error(ex.getMessage(), ex);
                }


            }).start();


            messageResult.setResult(true);
            messageResult.setCode(200);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }

        return messageResult;
    }


    @PostMapping("ParkingApplicationList")
    @ApiOperation(value = "租车申请列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "令牌", required = true, paramType = "form"),
            @ApiImplicitParam(name = "subject", value = "目标(不传)", paramType = "form"),
            @ApiImplicitParam(name = "status", value = "状态（0：待处理，1：已处理,2:查询自己）", required = true, paramType = "form")
    })
    public MessageResult<Map> ParkingApplicationList(String token, @RequestAttribute String subject, String status, @RequestParam(value = "pageIndex", defaultValue = "1") int pageIndex, @RequestParam(value = "pageSize", defaultValue = "20") int pageSize) {
        MessageResult<Map> messageResult = new MessageResult<>();

        try {
            PersonInfo personInfo = personInfoService.get(new Long(subject));

            PersonPopedom personPopedom = personPopedomService.get(personInfo.getPopedom());
            CompanyInfo companyInfo = companyInfoService.get(personPopedom.getCompanyId());

            Map<String, Object> searchParams = new HashMap<>();
            if ("0".equals(status)) {
                searchParams.put("status", "0");
                searchParams.put("companyId", companyInfo.getId());
            }
            if ("1".equals(status)) {
                searchParams.put("notStatus", "0");
                searchParams.put("companyId", companyInfo.getId());
            }
            if ("2".equals(status)) {
                searchParams.put("popedomId", personInfo.getPopedom());
            }

            List<Sort> sortList = new ArrayList<>();
            sortList.add(new Sort("create_time", "desc"));
            Page<ParkingApply> page = parkingApplyService.pageSearch(searchParams, pageIndex, pageSize, sortList);

            List<ParkingApply> list = page.getResult();
            List<ParkingApplyDTO> parkingApplyDTOList = new ArrayList<>();
            if (list.size() > 0) {
                for (ParkingApply parkingApply : list) {
                    ParkingApplyDTO parkingApplyDTO = new ParkingApplyDTO();
                    parkingApplyDTO.setParkingName(parkingApply.getParkingName());
                    parkingApplyDTO.setId(parkingApply.getId());
                    parkingApplyDTO.setRentTime(DateUtil.format(parkingApply.getStartTime(), "yyyy-MM-dd") + " 至 " + DateUtil.format(parkingApply.getEndTime(), "yyyy-MM-dd"));


                    PersonPopedom personPopedom1 = personPopedomService.get(parkingApply.getPopedomId());
                    PersonInfo personInfo1 = personInfoService.get(personPopedom1.getPersonId());
                    parkingApplyDTO.setApplicationName(personInfo1.getName());
                    parkingApplyDTO.setTelephone(personInfo1.getPhone());
                    parkingApplyDTO.setApplicationTime(DateUtil.format(parkingApply.getCreateTime(), "yyyy-MM-dd HH:mm"));
                    parkingApplyDTO.setStatus(parkingApply.getStatus());
                    if ("0".equals(parkingApply.getStatus())) {
                        parkingApplyDTO.setStatusN("待处理");
                    }
                    if ("1".equals(parkingApply.getStatus())) {
                        parkingApplyDTO.setStatusN("已处理");
                    }
                    if ("2".equals(parkingApply.getStatus())) {
                        parkingApplyDTO.setStatusN("已拒绝");
                    }
                    if ("3".equals(parkingApply.getStatus())) {
                        parkingApplyDTO.setStatusN("已关闭");
                    }

                    parkingApplyDTOList.add(parkingApplyDTO);
                }
            }


            Map<String, Object> map = new HashMap<>();
            map.put("num", parkingApplyDTOList.size());
            map.put("list", parkingApplyDTOList);


            messageResult.setData(map);
            messageResult.setResult(true);
            messageResult.setCode(200);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }

        return messageResult;
    }

    @PostMapping("ParkingApplicationDetail")
    @ApiOperation(value = "租车申请详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "令牌", required = true, paramType = "form"),
            @ApiImplicitParam(name = "subject", value = "目标(不传)", paramType = "form"),
            @ApiImplicitParam(name = "id", value = "id", required = true, paramType = "form")
    })
    public MessageResult<ParkingApplyDTO> ParkingApplicationDetail(String token, @RequestAttribute String subject, String id) {
        MessageResult<ParkingApplyDTO> messageResult = new MessageResult<>();

        try {
            PersonInfo personInfo = personInfoService.get(new Long(subject));

            PersonPopedom personPopedom = personPopedomService.get(personInfo.getPopedom());
            CompanyInfo companyInfo = companyInfoService.get(personPopedom.getCompanyId());

            ParkingApply parkingApply = parkingApplyService.get(id);
            if (parkingApply == null) {
                throw new Exception("信息不存在");
            }


            ParkingApplyDTO parkingApplyDTO = new ParkingApplyDTO();
            parkingApplyDTO.setParkingName(parkingApply.getParkingName());
            parkingApplyDTO.setId(parkingApply.getId());
            parkingApplyDTO.setRentTime(DateUtil.format(parkingApply.getStartTime(), "yyyy-MM-dd") + " 至 " + DateUtil.format(parkingApply.getEndTime(), "yyyy-MM-dd"));
            parkingApplyDTO.setCarNum(parkingApply.getCarNum());
            parkingApplyDTO.setContractDuration(parkingApply.getContractDuration());
            parkingApplyDTO.setEstimateFee(parkingApply.getEstimateFee());

            PersonPopedom personPopedom1 = personPopedomService.get(parkingApply.getPopedomId());
            PersonInfo personInfo1 = personInfoService.get(personPopedom1.getPersonId());
            parkingApplyDTO.setApplicationName(personInfo1.getName());
            parkingApplyDTO.setTelephone(personInfo1.getPhone());
            parkingApplyDTO.setApplicationTime(DateUtil.format(parkingApply.getCreateTime(), "yyyy-MM-dd HH:mm"));
            parkingApplyDTO.setActualFee(parkingApply.getActualFee());
            parkingApplyDTO.setStatus(parkingApply.getStatus());
            parkingApplyDTO.setPayType(parkingApply.getPayType());
            parkingApplyDTO.setReason(parkingApply.getReason());
            parkingApplyDTO.setUpdateTime(DateUtil.format(parkingApply.getUpdateTime(), "yyyy-MM-dd HH:mm"));
            parkingApplyDTO.setCreateTime(DateUtil.format(parkingApply.getCreateTime(), "yyyy-MM-dd HH:mm"));
            if ("0".equals(parkingApply.getStatus())) {
                parkingApplyDTO.setStatusN("待处理");
            }
            if ("1".equals(parkingApply.getStatus())) {
                parkingApplyDTO.setStatusN("已处理");
            }
            if ("2".equals(parkingApply.getStatus())) {
                parkingApplyDTO.setStatusN("已拒绝");
            }
            if ("3".equals(parkingApply.getStatus())) {
                parkingApplyDTO.setStatusN("已关闭");
            }

            messageResult.setData(parkingApplyDTO);
            messageResult.setResult(true);
            messageResult.setCode(200);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }

        return messageResult;
    }

    @PostMapping("ParkingApplicationConfirmLease")
    @ApiOperation(value = "车位确认租出")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "令牌", required = true, paramType = "form"),
            @ApiImplicitParam(name = "subject", value = "目标(不传)", paramType = "form"),
            @ApiImplicitParam(name = "id", value = "id", required = true, paramType = "form"),
            @ApiImplicitParam(name = "actualFee", value = "实际金额", required = true, paramType = "form")
    })
    public MessageResult<ParkingApplyDTO> ParkingApplicationConfirmLease(String token, @RequestAttribute String subject, String id, String actualFee) {
        MessageResult<ParkingApplyDTO> messageResult = new MessageResult<>();

        try {
            PersonInfo personInfo = personInfoService.get(new Long(subject));

            PersonPopedom personPopedom = personPopedomService.get(personInfo.getPopedom());


            ParkingApply parkingApply = parkingApplyService.get(id);
            if (parkingApply == null) {
                throw new Exception("信息不存在");
            }

            if (!"0".equals(parkingApply.getStatus())) {
                throw new Exception("申请已处理");
            }

            parkingApply.setUpdateTime(new Date());
            parkingApply.setStatus("1");
            parkingApply.setPayType("1");
            parkingApply.setActualFee(new BigDecimal(actualFee));
            parkingApplyService.update(parkingApply);

            //修改车位出租结束时间
            ParkingInfo parkingInfo = parkingInfoService.get(parkingApply.getParkingId());
            parkingInfo.setApplyEndTime(parkingApply.getEndTime());
            parkingInfoService.update(parkingInfo);
            //申请人
            PersonPopedom personPopedom1 = personPopedomService.get(parkingApply.getPopedomId());


            //发送通知
            messageInfoService.sendForPerson(personPopedom1.getPersonId(), personInfo.getId(), "车位申请", "恭喜您，车位：" + parkingApply.getParkingName() + "申请成功！", "1");

            //异步模板消息发送
            new Thread(() -> {
                PersonInfo personInfo1 = personInfoService.get(personPopedom1.getPersonId());
                if (personInfo1.getWechatNoticeEnabled()) {
                    WechatMessageUtil.sendParkingSuccessLease(personInfo1.getOpenId(), parkingApply.getParkingName(), parkingApply.getCarNum(), DateUtil.format(parkingApply.getStartTime(), "yyyy-MM-dd") + "至" + DateUtil.format(parkingApply.getEndTime(), "yyyy-MM-dd"), wxPayProperties.getAppId(), wxPayProperties.getAppSecret(), "", "您的车位申请已通过，申请车位：" + parkingApply.getParkingName());
                }

            }).start();


            messageResult.setResult(true);
            messageResult.setCode(200);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }

        return messageResult;
    }

    @PostMapping("ParkingApplicationClose")
    @ApiOperation(value = "关闭车位申请")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "令牌", required = true, paramType = "form"),
            @ApiImplicitParam(name = "subject", value = "目标(不传)", paramType = "form"),
            @ApiImplicitParam(name = "id", value = "id", required = true, paramType = "form"),
            @ApiImplicitParam(name = "reason", value = "原因", required = true, paramType = "form")
    })
    public MessageResult<ParkingApplyDTO> ParkingApplicationClose(String token, @RequestAttribute String subject, String id, String reason) {
        MessageResult<ParkingApplyDTO> messageResult = new MessageResult<>();

        try {
            PersonInfo personInfo = personInfoService.get(new Long(subject));

            PersonPopedom personPopedom = personPopedomService.get(personInfo.getPopedom());


            ParkingApply parkingApply = parkingApplyService.get(id);
            if (parkingApply == null) {
                throw new Exception("信息不存在");
            }

            if (!"0".equals(parkingApply.getStatus())) {
                throw new Exception("申请已处理");
            }

            parkingApply.setUpdateTime(new Date());
            parkingApply.setStatus("3");
            parkingApply.setReason(reason);
            parkingApplyService.update(parkingApply);

            //申请人
            PersonPopedom personPopedom1 = personPopedomService.get(parkingApply.getPopedomId());
            //发送通知

            messageInfoService.sendForPerson(personPopedom1.getPersonId(), personInfo.getId(), "车位申请", "您的车位：" + parkingApply.getParkingName() + "申请被拒绝，原因：" + parkingApply.getReason(), "1");

            //异步模板消息发送
            new Thread(() -> {
                PersonInfo personInfo1 = personInfoService.get(personPopedom1.getPersonId());

                if (personInfo1.getWechatNoticeEnabled()) {
                    WechatMessageUtil.sendParkingFailLease(personInfo1.getOpenId(), parkingApply.getReason(), parkingApply.getCarNum(), DateUtil.format(new Date(), "yyyy-MM-dd HH:mm"), wxPayProperties.getAppId(), wxPayProperties.getAppSecret());
                }

            }).start();

            messageResult.setResult(true);
            messageResult.setCode(200);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }

        return messageResult;
    }


    @PostMapping("ParkingPersonApplicationList")
    @ApiOperation(value = "车位申请列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "令牌", required = true, paramType = "form"),
            @ApiImplicitParam(name = "subject", value = "目标(不传)", paramType = "form")

    })
    public MessageResult<List<ParkingApplyDTO>> ParkingPersonApplicationList(String token, @RequestAttribute String subject) {
        MessageResult<List<ParkingApplyDTO>> messageResult = new MessageResult<>();

        try {
            PersonInfo personInfo = personInfoService.get(new Long(subject));

            PersonPopedom personPopedom = personPopedomService.get(personInfo.getPopedom());


            List<ParkingApply> parkingApplyList = parkingApplyService.findByPopedomId(personPopedom.getId());
            List<ParkingApplyDTO> list = new ArrayList<>();
            if (parkingApplyList.size() > 0) {
                for (ParkingApply parkingApply : parkingApplyList) {
                    ParkingApplyDTO parkingApplyDTO = new ParkingApplyDTO();
                    parkingApplyDTO.setParkingName(parkingApply.getParkingName());
                    parkingApplyDTO.setId(parkingApply.getId());
                    parkingApplyDTO.setRentTime(DateUtil.format(parkingApply.getStartTime(), "yyyy-MM-dd") + " 至 " + DateUtil.format(parkingApply.getEndTime(), "yyyy-MM-dd"));


                    PersonPopedom personPopedom1 = personPopedomService.get(parkingApply.getPopedomId());
                    PersonInfo personInfo1 = personInfoService.get(personPopedom1.getPersonId());
                    parkingApplyDTO.setApplicationName(personInfo1.getName());
                    parkingApplyDTO.setTelephone(personInfo1.getPhone());
                    parkingApplyDTO.setApplicationTime(DateUtil.format(parkingApply.getCreateTime(), "yyyy-MM-dd HH:mm"));
                    parkingApplyDTO.setStatus(parkingApply.getStatus());
                    if ("0".equals(parkingApply.getStatus())) {
                        parkingApplyDTO.setStatusN("待处理");
                    }
                    if ("1".equals(parkingApply.getStatus())) {
                        parkingApplyDTO.setStatusN("已处理");
                    }
                    if ("2".equals(parkingApply.getStatus())) {
                        parkingApplyDTO.setStatusN("已拒绝");
                    }
                    if ("3".equals(parkingApply.getStatus())) {
                        parkingApplyDTO.setStatusN("已关闭");
                    }

                    list.add(parkingApplyDTO);
                }
            }


            messageResult.setData(list);
            messageResult.setResult(true);
            messageResult.setCode(200);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }

        return messageResult;
    }


    @PostMapping("ParkingApplicationSendOrder")
    @ApiOperation(value = "车位申请推送账单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "令牌", required = true, paramType = "form"),
            @ApiImplicitParam(name = "subject", value = "目标(不传)", paramType = "form"),
            @ApiImplicitParam(name = "id", value = "id", required = true, paramType = "form"),
            @ApiImplicitParam(name = "url", value = "url", required = true, paramType = "form"),
            @ApiImplicitParam(name = "actualFee", value = "实际金额", required = true, paramType = "form")
    })
    public MessageResult<ParkingApplyDTO> ParkingApplicationSendOrder(String token, @RequestAttribute String subject, String id, String actualFee, String url) {
        MessageResult<ParkingApplyDTO> messageResult = new MessageResult<>();

        try {
            PersonInfo personInfo = personInfoService.get(new Long(subject));

            PersonPopedom personPopedom = personPopedomService.get(personInfo.getPopedom());


            ParkingApply parkingApply = parkingApplyService.get(id);
            if (parkingApply == null) {
                throw new Exception("信息不存在");
            }

            if (!"0".equals(parkingApply.getStatus())) {
                throw new Exception("申请已处理");
            }

            //申请人
            PersonPopedom personPopedom1 = personPopedomService.get(parkingApply.getPopedomId());

            PersonInfo personInfo1 = personInfoService.get(personPopedom1.getPersonId());

            ParkingInfo parkingInfo = parkingInfoService.get(parkingApply.getParkingId());
            parkingInfo.setApplyEndTime(parkingApply.getEndTime());
            parkingInfoService.update(parkingInfo);


            //创建车位账单
            String orderId = parkingApplyService.parkingApplicationCreateOrder(parkingApply, actualFee, personInfo1, personInfo.getCompanyId());


            //发送通知
            messageInfoService.sendForPerson(personPopedom1.getPersonId(), personInfo.getId(), "车位申请", "恭喜您，车位：" + parkingApply.getParkingName() + "申请已处理，请及时支付", "1");

            //异步模板消息发送
            new Thread(() -> {
                if (personInfo1.getWechatNoticeEnabled()) {

                    String perosnToken = JwtUtil2.createToken(jwtSecret, personInfo1.getId() + "", DateTime.now().plusHours(6).toDate());

                    WechatMessageUtil.sendParkingSuccessLease(personInfo1.getOpenId(), parkingApply.getParkingName(), parkingApply.getCarNum(),
                            DateUtil.format(parkingApply.getStartTime(), "yyyy-MM-dd") + "至" + DateUtil.format(parkingApply.getEndTime(), "yyyy-MM-dd"),
                            wxPayProperties.getAppId(), wxPayProperties.getAppSecret(),
                            wxConfig.getPortalUrl() + "master/mine/bill/pay?id=" + orderId + "&exchange=1&role_id=" + parkingApply.getPopedomId() + "&token=" + perosnToken + "&openId=" + personInfo1.getOpenId(),
                            "您的车位申请已通过，申请车位：" + parkingApply.getParkingName() + "，请在30分钟内完成支付，否则订单关闭。");
                }

            }).start();

            //创建延时消息30分钟未支付修改订单状态
            rabbitTemplate.convertAndSend("orderDelayExchange", "order", orderId, message -> {
                message.getMessageProperties().setHeader("x-delay", 30 * 60 * 1000);
                return message;
            });


            messageResult.setResult(true);
            messageResult.setCode(200);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }

        return messageResult;
    }

    @PostMapping("submitMedicationRemind")
    @ApiOperation(value = "提交吃药提醒")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "令牌", required = true, paramType = "form"),
            @ApiImplicitParam(name = "subject", value = "目标(不传)", paramType = "form"),
            @ApiImplicitParam(name = "medicationName", value = "药品名称", required = true, paramType = "form"),
            @ApiImplicitParam(name = "startTime", value = "开始时间", required = true, paramType = "form"),
            @ApiImplicitParam(name = "medicationDays", value = "使用天数", required = true, paramType = "form"),
            @ApiImplicitParam(name = "nextDays", value = "用药间隔天数", required = true, paramType = "form"),
            @ApiImplicitParam(name = "medicationFrequency", value = "当天用药次数", required = true, paramType = "form"),
            @ApiImplicitParam(name = "usage", value = "每天的用药量", required = true, paramType = "form"),
            @ApiImplicitParam(name = "remindTime", value = "提醒时间", required = true, paramType = "form")
    })
    public MessageResult<Map> submitMedicationRemind(String token, @RequestAttribute String subject, String medicationName, String startTime, String medicationDays, String nextDays, String medicationFrequency, String usage, String remindTime, String id) {
        MessageResult<Map> messageResult = new MessageResult<>();

        try {
            PersonInfo personInfo = personInfoService.get(new Long(subject));

            String key = "personInfo_medication" + personInfo.getId();

            //10秒内不能重复提交
            boolean lockSuccess = valueOperations.setIfAbsent(key, true, 10, TimeUnit.SECONDS);

            if (!lockSuccess) {
                throw new Exception("操作过于频繁！");
            }

            if (Integer.parseInt(medicationDays) > 30) {
                throw new Exception("使用天数不可大于30天");
            }

            Date dateTime = DateUtil.parse(startTime);
            Date beginTime = DateUtil.beginOfDay(new Date());
            if (dateTime.compareTo(beginTime) < 0) {
                throw new Exception("用药开始时间不可小于今日");
            }


            List<String> stringList = Arrays.asList(remindTime.split(","));
            if (stringList.size() != Integer.parseInt(medicationFrequency)) {
                throw new Exception("用药次数与提醒时间数量不一致");
            }

            if (StringUtils.isNotBlank(id)) {
                MedicationInfo medicationInfo = medicationInfoService.get(id);
                if (medicationInfo != null) {
                    medicationInfo.setDelFlag(true);
                    medicationInfoService.update(medicationInfo);
                }
            }


            PersonPopedom personPopedom = personPopedomService.get(personInfo.getPopedom());
            MedicationInfo medicationInfo = new MedicationInfo();
            medicationInfo.setId(UUID.randomUUID().toString());
            medicationInfo.setCreatePopedomId(personPopedom.getId());
            if (StringUtils.isNotBlank(personPopedom.getRelationPopedom())) {
                medicationInfo.setBeRemindPopedomId(personPopedom.getRelationPopedom());
            } else {
                medicationInfo.setBeRemindPopedomId(personPopedom.getId());
            }
            medicationInfo.setMedicationName(medicationName);
            medicationInfo.setStartTime(DateUtil.parse(startTime, "yyyy-MM-dd"));
            //要推移多少天
            int days = Integer.valueOf(medicationDays) * (Integer.valueOf(nextDays) + 1) - Integer.valueOf(nextDays);
            medicationInfo.setEndTime(DateUtil.offsetDay(medicationInfo.getStartTime(), days - 1));
            medicationInfo.setMedicationDays(Integer.valueOf(medicationDays));
            medicationInfo.setNextDays(Integer.valueOf(nextDays));
            medicationInfo.setMedicationFrequency(Integer.valueOf(medicationFrequency));
            medicationInfo.setUsage(usage);
            medicationInfo.setRemindTime(remindTime);
            medicationInfo.setDelFlag(false);
            medicationInfo.setNeedRemind(true);
            medicationInfo.setCreateBy(personPopedom.getId());
            medicationInfo.setCreateTime(new Date());
            medicationInfoService.insert(medicationInfo);


            Boolean needRemind = medicationInfoService.isMedication(medicationInfo, new Date());

            log.warn("是否发送提醒：" + needRemind);
            if (needRemind) {

                log.warn("创建当天的延时消息队列:" + medicationInfo.getId());
                //创建当天的延时消息队列
                medicationInfoService.createRemindMessage(medicationInfo);
            }

            Map<String, Object> map = new HashMap<>();
            map.put("id", medicationInfo.getId());


            messageResult.setData(map);
            messageResult.setResult(true);
            messageResult.setCode(200);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }

        return messageResult;
    }


    @PostMapping("medicationCalendar")
    @ApiOperation(value = "用药日历")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "令牌", required = true, paramType = "form"),
            @ApiImplicitParam(name = "subject", value = "目标(不传)", paramType = "form"),
            @ApiImplicitParam(name = "id", value = "id", required = false, paramType = "form")
    })
    public MessageResult<Map> medicationCalendar(String token, @RequestAttribute String subject, String id) {
        MessageResult<Map> messageResult = new MessageResult<>();

        try {

            PersonInfo personInfo = personInfoService.get(Long.valueOf(subject));
            PersonPopedom personPopedom = personPopedomService.get(personInfo.getPopedom());
            String popedomId = null;
            if (StringUtils.isNotBlank(personPopedom.getRelationPopedom())) {
                popedomId = personPopedom.getRelationPopedom();
            } else {
                popedomId = personPopedom.getId();
            }
            List<DaysDTO> list = null;

            if (StringUtils.isNotBlank(id)) {
                list = medicationInfoService.getMedicationDays(id);
            } else {
                list = medicationInfoService.getAllMedicationDays(popedomId);
            }


            Map<String, Object> map = new HashMap<>();
            map.put("list", list);


            messageResult.setData(map);
            messageResult.setResult(true);
            messageResult.setCode(200);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }

        return messageResult;
    }


    @PostMapping("medicationList")
    @ApiOperation(value = "用药计划和药品列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "令牌", required = true, paramType = "form"),
            @ApiImplicitParam(name = "subject", value = "目标(不传)", paramType = "form")
    })
    public MessageResult<Map> medicationList(String token, @RequestAttribute String subject) {
        MessageResult<Map> messageResult = new MessageResult<>();

        try {


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

            //有关联长者时，popedomId为所关联的长者，否则为自己的
            String popedomId = "";
            if (StringUtils.isNotBlank(personPopedom.getRelationPopedom())) {
                popedomId = personPopedom.getRelationPopedom();
            } else {
                popedomId = personPopedom.getId();
            }

            Map<String, Object> searchParams = new HashMap<>();
            searchParams.put("beRemindPopedomId", popedomId);
            searchParams.put("startTime", DateUtil.beginOfDay(new Date()));
            searchParams.put("endTime", DateUtil.beginOfDay(new Date()));
            List<Sort> sortList = new ArrayList<>();
            sortList.add(new Sort("create_time", "desc"));
            Page<MedicationInfo> page = medicationInfoService.pageSearch(searchParams, 1, 10, false, sortList);
            Map<String, Object> map = new HashMap<>();


            List<MedicationInfo> list = page.getResult();
            List<MedicationTimeDTO> medicationTimeDTOS = new ArrayList<>();
            List<MedicationInfo> medicationInfos = new ArrayList<>();
            if (list.size() > 0) {
                //今天要服用的药物

                for (MedicationInfo medicationInfo : list) {
                    //今天此药是否要服用
                    Boolean isMedication = medicationInfoService.isMedication(medicationInfo, new Date());
                    if (isMedication) {
                        Long hasUsedDays = 0L;

                        if (medicationInfo.getStartTime().compareTo(DateUtil.beginOfDay(new Date())) <= 0 && medicationInfo.getEndTime().compareTo(DateUtil.beginOfDay(new Date())) >= 0) {
                            Long days = DateUtil.between(medicationInfo.getStartTime(), DateUtil.beginOfDay(new Date()), DateUnit.DAY);
                            hasUsedDays = days / (medicationInfo.getNextDays() + 1);
                        }
                        if (medicationInfo.getEndTime().compareTo(DateUtil.beginOfDay(new Date())) < 0) {
                            hasUsedDays = Long.valueOf(medicationInfo.getMedicationDays());
                        }
                        medicationInfo.setHasUsedDays(hasUsedDays);
                        medicationInfo.setNeedUsedDays(medicationInfo.getMedicationDays() - hasUsedDays);

                        medicationInfos.add(medicationInfo);
                    }
                }


                //提醒的时间列表
                List<String> timeList = new ArrayList<>();
                if (medicationInfos.size() > 0) {
                    for (MedicationInfo medicationInfo : medicationInfos) {
                        List<String> list1 = Arrays.asList(medicationInfo.getRemindTime().split(","));
                        for (String string : list1) {
                            if (!timeList.contains(string)) {
                                timeList.add(string);
                            }
                        }
                    }

                }

                //时间排序
                if (timeList.size() > 0) {
                    Collections.sort(timeList, new Comparator<String>() {
                        @Override
                        public int compare(String time1, String time2) {

                            Date date1 = DateUtil.parse(time1, "mm:ss");
                            Date date2 = DateUtil.parse(time2, "mm:ss");
                            return date1.compareTo(date2);
                        }
                    });


                    for (String time : timeList) {
                        for (MedicationInfo medicationInfo : medicationInfos) {
                            if (medicationInfo.getRemindTime().contains(time)) {
                                MedicationTimeDTO medicationTimeDTO = new MedicationTimeDTO();
                                medicationTimeDTO.setMedicationName(medicationInfo.getMedicationName());
                                medicationTimeDTO.setTime(time);
                                medicationTimeDTO.setUsage(medicationInfo.getUsage());
                                medicationTimeDTOS.add(medicationTimeDTO);
                            }
                        }
                    }
                }

            }

            //全部用药列表
            map.put("allList", medicationInfos);
            map.put("timeList", medicationTimeDTOS);
            messageResult.setData(map);
            messageResult.setResult(true);
            messageResult.setCode(200);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }

        return messageResult;
    }


    @PostMapping("medicationCalendarDefine")
    @ApiOperation(value = "用药日历确定")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "令牌", required = true, paramType = "form"),
            @ApiImplicitParam(name = "subject", value = "目标(不传)", paramType = "form"),
            @ApiImplicitParam(name = "id", value = "id", required = true, paramType = "form")
    })
    public MessageResult<Map> medicationCalendarDefine(String token, @RequestAttribute String subject, String id) {
        MessageResult<Map> messageResult = new MessageResult<>();

        try {

            MedicationInfo medicationInfo = medicationInfoService.get(id);
                /*if (medicationInfo != null) {
                    medicationInfo.setNeedRemind(true);
                    medicationInfoService.update(medicationInfo);


                    Boolean needRemind = medicationInfoService.isMedication(medicationInfo,new Date());

                    log.warn("是否发送提醒："+needRemind);
                    if (needRemind) {

                        log.warn("创建当天的延时消息队列:"+medicationInfo.getId());
                        //创建当天的延时消息队列
                        medicationInfoService.createRemindMessage(medicationInfo);
                    }

                }*/

            Map<String, Object> map = new HashMap<>();
            messageResult.setData(map);
            messageResult.setResult(true);
            messageResult.setCode(200);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }

        return messageResult;
    }


    @PostMapping("medicationRemindSwitch")
    @ApiOperation(value = "用药日提醒开关")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "令牌", required = true, paramType = "form"),
            @ApiImplicitParam(name = "subject", value = "目标(不传)", paramType = "form"),
            @ApiImplicitParam(name = "status", value = "0/1(关闭/开启)", required = true, paramType = "form"),
            @ApiImplicitParam(name = "id", value = "id", required = true, paramType = "form"),
    })
    public MessageResult<Map> medicationRemindSwitch(String token, @RequestAttribute String subject, String status, String id) {
        MessageResult<Map> messageResult = new MessageResult<>();

        try {
            MedicationInfo medicationInfo = medicationInfoService.get(id);

            if (medicationInfo != null) {
                boolean needRemind = false;
                if ("1".equals(status)) {
                    needRemind = true;
                }
                medicationInfo.setNeedRemind(needRemind);
                medicationInfoService.update(medicationInfo);
            }

            Map<String, Object> map = new HashMap<>();
            messageResult.setData(map);
            messageResult.setResult(true);
            messageResult.setCode(200);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }

        return messageResult;
    }

    @PostMapping("medicationDelete")
    @ApiOperation(value = "用药删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "令牌", required = true, paramType = "form"),
            @ApiImplicitParam(name = "subject", value = "目标(不传)", paramType = "form"),
            @ApiImplicitParam(name = "id", value = "id", required = true, paramType = "form")
    })
    public MessageResult<Map> medicationDelete(String token, @RequestAttribute String subject, String id) {
        MessageResult<Map> messageResult = new MessageResult<>();

        try {


            MedicationInfo medicationInfo = medicationInfoService.get(id);

            if (medicationInfo != null) {
                medicationInfo.setDelFlag(true);
                medicationInfoService.update(medicationInfo);
            }

            Map<String, Object> map = new HashMap<>();
            messageResult.setData(map);
            messageResult.setResult(true);
            messageResult.setCode(200);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }

        return messageResult;
    }

    @PostMapping("medicationDetail")
    @ApiOperation(value = "用药详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "令牌", required = true, paramType = "form"),
            @ApiImplicitParam(name = "subject", value = "目标(不传)", paramType = "form"),
            @ApiImplicitParam(name = "id", value = "id", required = true, paramType = "form")
    })
    public MessageResult<MedicationInfo> medicationDetail(String token, @RequestAttribute String subject, String id) {
        MessageResult<MedicationInfo> messageResult = new MessageResult<>();

        try {


            MedicationInfo medicationInfo = medicationInfoService.get(id);


            messageResult.setData(medicationInfo);
            messageResult.setResult(true);
            messageResult.setCode(200);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }

        return messageResult;
    }

    @GetMapping(value = "sendMessage")
    public MessageResult<String> sendMessage() {
        MessageResult<String> messageResult = new MessageResult<>();

        try {

            BusinessOut businessOut = businessOutService.get("77aad9d8-077a-47c2-b40f-a30f25743729");


            long millisecond = DateUtil.betweenMs(DateUtil.date(), businessOut.getStartTime());
            log.warn("创建延时队列修改工作状态，id：" + businessOut.getId() + "时间：" + millisecond);
            rabbitTemplate.convertAndSend("businessOutDelayExchange", "businessOutSubmit", businessOut.getId(), (message) -> {
                message.getMessageProperties().setHeader("x-delay", millisecond);
                return message;
            });


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

        return messageResult;
    }


    @ApiOperation(value = "激活人员列表数据")
    @PostMapping("activationListData")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "令牌", paramType = "form"),
            @ApiImplicitParam(name = "subject", value = "目标(不传)", paramType = "form"),
            @ApiImplicitParam(name = "name", value = "姓名", required = false, paramType = "form"),
            @ApiImplicitParam(name = "status", value = "状态（0：未激活，1：已激活）", required = false, paramType = "form")
    })
    public MessageResult<Map> activationListData(String token, @RequestAttribute String subject, String name, String status, @RequestParam(value = "pageIndex", defaultValue = "1") int pageIndex, @RequestParam(value = "pageSize", defaultValue = "10") int pageSize) {
        MessageResult<Map> messageResult = new MessageResult<>();

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

            if (personInfo == null) {
                throw new Exception("人员信息不存在!");
            }

            PersonPopedom personPopedom0 = personPopedomService.get(personInfo.getPopedom());

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

            CompanyInfo companyInfo = companyInfoService.get(personPopedom0.getCompanyId());
            List<CompanyInfo> companyInfoList = companyInfoService.findAllCompanyByCode(companyInfo.getCode() + "%");
            searchParams.put("companyList", companyInfoList);
            if ("0".equals(status)) {
                searchParams.put("nullOpenId", "0");
            }
            if ("1".equals(status)) {
                searchParams.put("notNullOpenId", "0");
            }
            if (StringUtils.isNotBlank(name)) {
                searchParams.put("name", "%" + name + "%");
            }
            List<Sort> sortList = new ArrayList<>();
            sortList.add(new Sort("create_time", "desc"));
            Page<PersonPopedom> page = personPopedomService.pageSearch(searchParams, pageIndex, pageSize, true, sortList);

            Map<String, Object> searchParams1 = new HashMap<>();
            searchParams1.put("companyList", companyInfoList);
            searchParams1.put("nullOpenId", "0");
            //未激活
            Page<PersonPopedom> page1 = personPopedomService.pageSearch(searchParams1, pageIndex, pageSize, true, sortList);

            Map<String, Object> searchParams2 = new HashMap<>();
            searchParams2.put("companyList", companyInfoList);
            searchParams2.put("notNullOpenId", "0");
            //已激活
            Page<PersonPopedom> page2 = personPopedomService.pageSearch(searchParams2, pageIndex, pageSize, true, sortList);


            List<PersonPopedom> personPopedomList = page.getResult();
            Map<String, Object> map = new HashMap<>();
            if (personPopedomList.size() > 0) {

                for (PersonPopedom personPopedom : personPopedomList) {
                    PersonInfo personInfo1 = personInfoService.get(personPopedom.getPersonId());

                    PersonPopedomDTO personPopedomDTO = new PersonPopedomDTO();

                    BeanUtils.copyProperties(personPopedom, personPopedomDTO);
                    personPopedomDTO.setActivationStatus(status);
                    personPopedomDTO.setPersonRoleName(personPopedom.getRoleName());
                    personPopedomDTO.setFaceImagUrl(personPopedom.getFaceImageUrl());
                    personPopedomDTO.setTelephone(personInfo1.getPhone());


                    list.add(personPopedomDTO);

                }


            }

            Map<String, Object> pageMap = new HashMap<>();
            pageMap.put("recordsTotal", page.getTotal());
            pageMap.put("recordsFiltered", page.getTotal());
            pageMap.put("totalPage", page.getPages());
            pageMap.put("pageNumber", page.getPageNum());
            pageMap.put("pageSize", page.getPageSize());
            pageMap.put("data", list);
            pageMap.put("notActivation", page1.getTotal());
            pageMap.put("activation", page2.getTotal());

            messageResult.setData(pageMap);
            messageResult.setResult(true);
            messageResult.setCode(200);

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

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

        return messageResult;
    }


    @PostMapping("submitReturnInfo")
    @ApiOperation(value = "提交返乡信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "openId", value = "openId", required = true, paramType = "form"),
            @ApiImplicitParam(name = "name", value = "登记人姓名", required = true, paramType = "form"),
            @ApiImplicitParam(name = "idCard", value = "身份证号码", required = true, paramType = "form"),
            @ApiImplicitParam(name = "phone", value = "手机号码", required = true, paramType = "form"),
            @ApiImplicitParam(name = "liveRegionId", value = "居住地", required = true, paramType = "form"),
            @ApiImplicitParam(name = "liveDetailAddress", value = "居住地详细地址", required = true, paramType = "form"),
            @ApiImplicitParam(name = "originId", value = "始发地", required = true, paramType = "form"),
            @ApiImplicitParam(name = "originDetailAddress", value = "始发地详细地址", required = true, paramType = "form"),
            @ApiImplicitParam(name = "avenuePlace", value = "途径地", required = true, paramType = "form"),
            @ApiImplicitParam(name = "vehicle", value = "交通工具", required = true, paramType = "form"),
            @ApiImplicitParam(name = "arriveTime", value = "返乡时间", required = true, paramType = "form"),
            @ApiImplicitParam(name = "haveCheckStr", value = "是否有7日内核酸检测报告", required = true, paramType = "form"),
            @ApiImplicitParam(name = "remark", value = "备注", required = false, paramType = "form"),
            @ApiImplicitParam(name = "checkImageUrl", value = "核酸检测报告图片地址", required = false, paramType = "form"),
            @ApiImplicitParam(name = "travelImageUrl", value = "行程卡图片地址", required = false, paramType = "form"),
            @ApiImplicitParam(name = "healthCodeUrl", value = "健康码图片地址", required = false, paramType = "form"),
            @ApiImplicitParam(name = "code", value = "短信验证码", required = true, paramType = "form"),
            @ApiImplicitParam(name = "type" ,value = "返乡类型",required = false,paramType = "form")

    })
    public MessageResult<Map> submitReturnInfo(String openId, String name, String idCard, String phone, String liveRegionId, String liveDetailAddress, String originId, String originDetailAddress, String avenuePlace, String vehicle, String arriveTime, String haveCheckStr, String remark, String checkImageUrl, String travelImageUrl, String healthCodeUrl, String code,String type) {
        MessageResult<Map> messageResult = new MessageResult<>();

        try {

            if (StringUtils.isBlank(openId)) {
                throw new Exception("获取微信信息有误");
            }
            if (StringUtils.isBlank(name)) {
                throw new Exception("姓名不可为空");
            }
            if (StringUtils.isBlank(idCard)) {
                throw new Exception("身份证不可为空");
            }

            if (!new CheckIdCard(idCard).validate()){
                throw new Exception("请输入有效身份证号码");
            }

            List<CompanyInfo> companyInfoList = companyInfoService.findByRegionIdAndSceneId(liveRegionId,"2");
            if (companyInfoList.size()==0 ){
                throw new Exception("居住地无对应社区，请选择开发区对应社区");
            }
            String smsKey = "SMS_" + phone;

            String beforeVerifyCode = (String) valueOperations.get(smsKey);

            if (StringUtils.isEmpty(beforeVerifyCode)) {
                throw new Exception("验证码已过期!");
            }

            if (!beforeVerifyCode.equals(code)) {
                throw new Exception("验证码错误!");
            }

            boolean check = false;
            if ("1".equals(haveCheckStr)){
                check = true;
            }


            String id = "";

            ReturnInfo returnInfo0 = returnInfoService.findByOpenId(openId);
            if (returnInfo0 == null){

                ReturnInfo returnInfo1 = returnInfoService.findByIdCardOrPhone(idCard,null);
                if (returnInfo1 !=null){
                    throw new Exception("此身份证已被使用");
                }
                ReturnInfo returnInfo2 = returnInfoService.findByIdCardOrPhone(null,phone);
                if (returnInfo2 !=null){
                    throw new Exception("此手机号已被使用");
                }
                ReturnInfo returnInfo = new ReturnInfo();
                returnInfo.setId(UUID.randomUUID().toString());
                returnInfo.setName(name);
                returnInfo.setOpenId(openId);
                returnInfo.setIdCard(idCard);
                returnInfo.setPhone(phone);
                returnInfo.setLiveRegionId(liveRegionId);
                returnInfo.setLiveDetailAddress(liveDetailAddress);
                returnInfo.setOriginId(originId);
                returnInfo.setOriginDetailAddress(originDetailAddress);
                returnInfo.setAvenuePlace(avenuePlace);
                returnInfo.setVehicle(vehicle);
                returnInfo.setArriveTime(DateUtil.parse(arriveTime, "yyyy-MM-dd"));
                returnInfo.setHaveCheck(check);
                returnInfo.setRemark(remark);
                returnInfo.setType(type);
                returnInfo.setCheckImageUrl(checkImageUrl);
                returnInfo.setTravelImageUrl(travelImageUrl);
                returnInfo.setHealthCodeUrl(healthCodeUrl);
                returnInfo.setCreateTime(new Date());
                returnInfo.setDelFlag(false);
                returnInfoService.insert(returnInfo);
                id = returnInfo.getId();



                //队列处理返乡登记人的信息
            //    rabbitTemplate.convertAndSend("insertPersonInfoSuperviseQueue",returnInfo);
            }else {
                returnInfo0.setName(name);
                returnInfo0.setIdCard(idCard);
                returnInfo0.setPhone(phone);
                returnInfo0.setLiveRegionId(liveRegionId);
                returnInfo0.setLiveDetailAddress(liveDetailAddress);
                returnInfo0.setOriginId(originId);
                returnInfo0.setOriginDetailAddress(originDetailAddress);
                returnInfo0.setAvenuePlace(avenuePlace);
                returnInfo0.setVehicle(vehicle);
                returnInfo0.setArriveTime(DateUtil.parse(arriveTime, "yyyy-MM-dd"));
                returnInfo0.setType(type);
                returnInfo0.setHaveCheck(check);
                returnInfo0.setRemark(remark);
                returnInfo0.setCheckImageUrl(checkImageUrl);
                returnInfo0.setTravelImageUrl(travelImageUrl);
                returnInfo0.setHealthCodeUrl(healthCodeUrl);
                returnInfo0.setUpdateTime(new Date());
                returnInfoService.update(returnInfo0);

                id = returnInfo0.getId();

            }

            Map<String,Object> map = new HashMap<>();
            map.put("id",id);

            messageResult.setData(map);
            messageResult.setResult(true);
            messageResult.setCode(200);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }

        return messageResult;
    }

    @PostMapping("confirmReturnInfo")
    @ApiOperation(value = "确认返乡信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "openId", value = "openId", required = true, paramType = "form"),
            @ApiImplicitParam(name = "id", value = "主id", required = true, paramType = "form")
    })
    public MessageResult<Map> confirmReturnInfo(String openId, String id) {
        MessageResult<Map> messageResult = new MessageResult<>();

        try {

            if (StringUtils.isBlank(openId)) {
                throw new Exception("获取微信信息有误");
            }
            if (StringUtils.isBlank(id)) {
                throw new Exception("id不存在");
            }
            ReturnInfo returnInfo = returnInfoService.get(id);
            if (returnInfo != null){
                returnInfo.setEnableUpdate(false);
                returnInfoService.update(returnInfo);
            }

            List<CompanyInfo> companyInfoList = companyInfoService.findByRegionIdAndSceneId(returnInfo.getLiveRegionId(),"2");

            //发送社区管理员有人登记返乡
            new Thread(()->{
                try{
                    PersonRoleInfo personRoleInfo = personRoleInfoService.findByRoleNameAndSceneId("社区疫情专员","2");
                    if (personRoleInfo != null){
                        List<PersonPopedom> personPopedomList = personPopedomService.findByCompanyIdAndRoleIds(companyInfoList.get(0).getId(),personRoleInfo.getId());
                        if (personPopedomList.size()>0){
                            for (PersonPopedom personPopedom : personPopedomList){
                                PersonInfo personInfo = personInfoService.get(personPopedom.getPersonId());
                                String accessToken = JwtUtil2.createToken(jwtSecret, personInfo.getId() + "", DateTime.now().plusHours(30*24).toDate());
                                if (personInfo.getWechatNoticeEnabled()){
                                    WechatMessageUtil.sendReturnMessage(personInfo.getOpenId(),"有新的返乡人员登记",DateUtil.format(returnInfo.getCreateTime(),"yyyy-MM-dd HH:mm"),returnInfo.getLiveDetailAddress(),personInfo.getName(),"您好，您所属辖区有新的返乡登记记录，请及时跟进。点击“详情”可查看具体信息",wxConfig.getPortalUrl() + "other/return/info?id=" + returnInfo.getId() + "&exchange=1&role_id=" + personPopedom.getId() + "&token=" + accessToken,wxConfig.getAppId(),wxConfig.getAppSecret());
                                }
                            }
                        }
                    }
                }catch (Exception ex){
                    log.error(ex.getMessage(),ex);
                }
            }).start();

            //队列处理返乡登记人的信息
                rabbitTemplate.convertAndSend("insertPersonInfoSuperviseQueue",returnInfo);


            messageResult.setResult(true);
            messageResult.setCode(200);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }

        return messageResult;
    }


    @PostMapping("returnInfoDetail")
    @ApiOperation(value = "返乡信息详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "openId", value = "openId", required = true, paramType = "form")
    })
    public MessageResult<ReturnInfo> returnInfoDetail(String openId) {
        MessageResult<ReturnInfo> messageResult = new MessageResult<>();

        try {

            if (StringUtils.isBlank(openId)) {
                throw new Exception("获取微信信息有误");
            }

            ReturnInfo returnInfo = returnInfoService.findByOpenId(openId);

            if (returnInfo != null){
                String haveCheckStr = "0";
                if (returnInfo.getHaveCheck()){
                    haveCheckStr = "1";
                }

                returnInfo.setHaveCheckStr(haveCheckStr);
            }


            messageResult.setData(returnInfo);
            messageResult.setResult(true);
            messageResult.setCode(200);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }

        return messageResult;
    }

    @PostMapping("regionList")
    @ApiOperation(value = "区域列表(公开接口)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "type", value = "类型（1：居住地，2：始发地）", required = true, paramType = "form")
    })
    public MessageResult<Map> regionList(String type) {
        MessageResult<Map> messageResult = new MessageResult<>();

        try {

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


            String key = "region" + type;
            List tmpList = (List) valueOperations.get(key);

            if (tmpList == null) {
                List<RegionInfoDTO> list0 =  regionInfoService.findByType(type);
                list = list0;
                valueOperations.set(key, list0);
            }else {
                list = tmpList;

                new Thread(() -> {
                    List<RegionInfoDTO> list0 =  regionInfoService.findByType(type);
                    valueOperations.set(key, list0);
                }).start();
            }

            map.put("list", list);

            messageResult.setData(map);
            messageResult.setResult(true);
            messageResult.setCode(200);
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            messageResult.setCode(400);
            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }

        return messageResult;
    }

    @PostMapping("commissionerReturnInfoList")
    @ApiOperation(value = "返乡管理人员返乡数据列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "令牌", paramType = "form"),
            @ApiImplicitParam(name = "subject", value = "目标(不传)", paramType = "form"),
            @ApiImplicitParam(name = "name", value = "姓名/手机号码", required = false, paramType = "form")
    })
    public MessageResult<Map> commissionerReturnInfoList(String token, @RequestAttribute String subject, String name,@RequestParam(value = "pageIndex", defaultValue = "1") int pageIndex, @RequestParam(value = "pageSize", defaultValue = "10") int pageSize) {
        MessageResult<Map> messageResult = new MessageResult<>();

        try {

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

            if (personInfo == null) {
                throw new Exception("人员信息不存在!");
            }

            List<ReturnInfoDTO> list = new ArrayList<>();
            Page<ReturnInfo> page = new Page<>();
            PersonPopedom personPopedom = personPopedomService.get(personInfo.getPopedom());



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

        //    RegionInfo regionInfo = regionInfoService.get(companyInfo.getRegionId());
            if (companyInfoList.size() >0){
                Map<String, Object> searchParams = new HashMap<>();
                searchParams.put("liveRegionIdList",companyInfoList);
//                searchParams.put("enableUpdate",false);

                if (StringUtils.isNotBlank(name)){
                    if (NumberUtil.isNumber(name)){
                        searchParams.put("phone","%"+name+"%");
                    }
                    if (!NumberUtil.isNumber(name)){
                        searchParams.put("name","%"+name+"%");
                    }
                }

                List<Sort> sortList = new ArrayList<>();
                sortList.add(new Sort("create_time", "desc"));
                sortList.add(new Sort("new_flag","asc"));
                page = returnInfoService.pageSearch(searchParams, pageIndex, pageSize,true, sortList);

                List<ReturnInfo> returnInfoList = page.getResult();

                Map<String, Object> map = new HashMap<>();
                if (returnInfoList.size() > 0) {

                    for (ReturnInfo returnInfo : returnInfoList) {

                        ReturnInfoDTO returnInfoDTO = new ReturnInfoDTO();
                        BeanUtils.copyProperties(returnInfo,returnInfoDTO);
                        returnInfoDTO.setSex(IdcardUtil.getGenderByIdCard(returnInfo.getIdCard()));
                        list.add(returnInfoDTO);

                    }

                }
            }




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

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



            messageResult.setData(pageMap);
            messageResult.setResult(true);
            messageResult.setCode(200);
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            messageResult.setCode(400);
            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }

        return messageResult;
    }

    @PostMapping("commissionerReturnInfoDetail")
    @ApiOperation(value = "返乡管理人员返乡数据详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "令牌", paramType = "form"),
            @ApiImplicitParam(name = "subject", value = "目标(不传)", paramType = "form"),
            @ApiImplicitParam(name = "id", value = "id", required = true, paramType = "form")
    })
    public MessageResult<ReturnInfoDTO> commissionerReturnInfoDetail(String token, @RequestAttribute String subject, String id) {
        MessageResult<ReturnInfoDTO> messageResult = new MessageResult<>();

        try {

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

            if (personInfo == null) {
                throw new Exception("人员信息不存在!");
            }

            ReturnInfo returnInfo = returnInfoService.get(id);
            ReturnInfoDTO returnInfoDTO = new ReturnInfoDTO();
            BeanUtils.copyProperties(returnInfo,returnInfoDTO);
            returnInfoDTO.setSex(IdcardUtil.getGenderByIdCard(returnInfo.getIdCard()));
            returnInfo.setNewFlag(false);
            returnInfoService.update(returnInfo);





           messageResult.setData(returnInfoDTO);
            messageResult.setResult(true);
            messageResult.setCode(200);
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            messageResult.setCode(400);
            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }

        return messageResult;
    }

    @PostMapping("personShiftInfo")
    @ApiOperation(value = "个人班次数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "token", value = "令牌", paramType = "form"),
            @ApiImplicitParam(name = "subject", value = "目标(不传)", paramType = "form"),
            @ApiImplicitParam(name = "date", value = "时间（如：2021-05-10）", required = true, paramType = "form")
    })
    public MessageResult<List<PersonShiftInfoListDTO>> personShiftInfo(String token, @RequestAttribute String subject,String date) {
        MessageResult<List<PersonShiftInfoListDTO>> messageResult = new MessageResult<>();

        try {

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

            if (personInfo == null) {
                throw new Exception("人员信息不存在!");
            }

            String dateStr = date + " " + "00:00:00";
            String dateStr1 = date + " " + "12:00:00";
            List<PersonShiftInfoListDTO> personShiftInfoListList = new ArrayList<>();
            for (int n=0;n<7;n++){
                Date date1 = DateUtil.parse(dateStr);
                Date date2 = DateUtil.offsetDay(date1,n);
                Date date3 = DateUtil.parse(dateStr1);
                Date date4 = DateUtil.offsetDay(date3,n);
                PersonShiftInfoListDTO personShiftInfoListDTO = new PersonShiftInfoListDTO();
                personShiftInfoListDTO.setDateStr(DateUtil.format(date2,"yyyy-MM-dd"));
                WorkPersonScheduling workPersonScheduling = workPersonSchedulingService.findByPersonIdSchedulingDay(personInfo.getId(),date2);
                if (workPersonScheduling == null){
                    personShiftInfoListDTO.setDesc("无");
                    personShiftInfoListDTO.setStatus("3");
                    personShiftInfoListList.add(personShiftInfoListDTO);
                }
                else {
                    List<String> shiftIdList = Arrays.asList(workPersonScheduling.getShiftIds().split(","));
                    List<PersonShiftInfoDTO> personShiftInfoDTOList = new ArrayList<>();
                    for (String shiftId : shiftIdList){
                        PersonShiftInfoDTO personShiftInfoDTO = new PersonShiftInfoDTO();
                        WorkShiftInfo workShiftInfo = workShiftInfoService.get(shiftId);
                        personShiftInfoDTO.setName(workShiftInfo.getName());
                        if (workShiftInfo.getDays().compareTo(BigDecimal.ZERO) == 0){
                            personShiftInfoListDTO.setDesc("休息");
                            personShiftInfoListDTO.setStatus("2");
                            personShiftInfoDTO.setStatus("2");
                        }
                        else {
                            personShiftInfoDTO.setDateStr(workShiftInfo.getWorkTime()+"-" + workShiftInfo.getClosingTime());
                            personShiftInfoDTO.setStatus("1");
                            personShiftInfoListDTO.setDesc("上班");
                            personShiftInfoListDTO.setStatus("1");
                        }
                        personShiftInfoDTOList.add(personShiftInfoDTO);
                    }
                    //出差
                    Map<String,Object> searchParams = new HashMap<>();
                    searchParams.put("personPopedomId",personInfo.getPopedom());
                    searchParams.put("status","1");
                    searchParams.put("shiftStartTime",date4);
                    searchParams.put("shiftEndTime",date4);
                    List<Sort> sortList = new ArrayList<>();
                    sortList.add(new Sort("a.create_time","desc"));
                    Page<BusinessOut> page = businessOutService.pageSearch(searchParams,1,1,false,sortList);
                    List<BusinessOut> businessOutList = page.getResult();
                    if (businessOutList.size()>0){
                        BusinessOut businessOut = businessOutList.get(0);
                        PersonShiftInfoDTO personShiftInfoDTO = new PersonShiftInfoDTO();
                        String start = DateUtil.format(businessOut.getStartTime(),"HH:mm:ss");
                        String end = DateUtil.format(businessOut.getEstimatedDate(),"HH:mm:ss");
                        String startStr = "上午";
                        if (start.equals("12:00:00")){
                            startStr = "下午";
                        }
                        String endStr = "上午";
                        if (businessOut.getEndTime() == null){
                            if (end.equals("12:00:00")){
                                endStr = "下午";
                            }
                        }else {
                            endStr = " "+ DateUtil.format(businessOut.getEndTime(),"HH:mm:ss");
                        }

                        personShiftInfoDTO.setDateStr(DateUtil.format(businessOut.getStartTime(),"yyyy-MM-dd") + startStr + "-" + DateUtil.format(businessOut.getEstimatedDate(),"yyyy-MM-dd") +endStr);
                        personShiftInfoDTO.setName("出差");
                        personShiftInfoDTO.setStatus("4");

                        personShiftInfoDTOList.add(personShiftInfoDTO);
                        personShiftInfoListDTO.setDesc("出差");
                        personShiftInfoListDTO.setStatus("4");
                    }

                    //请假
                    List<RequestForLeaveInfo> requestForLeaveInfoList = requestForLeaveInfoService.findByPersonIdAndDate(personInfo.getId(),date2,date2);
                    if (requestForLeaveInfoList.size()>0){
                        for (RequestForLeaveInfo requestForLeaveInfo: requestForLeaveInfoList){
                            PersonShiftInfoDTO personShiftInfoDTO = new PersonShiftInfoDTO();
                            personShiftInfoDTO.setName("请假");
                            personShiftInfoDTO.setStatus("5");
                          //  personShiftInfoDTO.setDateStr(DateUtil.format(requestForLeaveInfo.getStartTime(),"yyyy-MM-dd HH:mm:ss") + "-" +DateUtil.format(requestForLeaveInfo.getEndTime(),"yyyy-MM-dd HH:mm:ss"));
                            String startStr = "上午";
                            String endStr = "上午";
                            if ("1".equals(requestForLeaveInfo.getStartTimeQuantum())){
                                startStr = "下午";
                            }
                            if ("1".equals(requestForLeaveInfo.getEndTimeQuantum())){
                                endStr = "下午";
                            }
                            personShiftInfoDTO.setDateStr(DateUtil.format(requestForLeaveInfo.getStartTime(),"yyyy-MM-dd") + startStr + "-" +DateUtil.format(requestForLeaveInfo.getEndTime(),"yyyy-MM-dd") +endStr);
                            personShiftInfoDTOList.add(personShiftInfoDTO);
                            personShiftInfoListDTO.setDesc("请假");
                            personShiftInfoListDTO.setStatus("5");

                        }
                    }


                    personShiftInfoListDTO.setPersonShiftInfoDTOList(personShiftInfoDTOList);
                    personShiftInfoListList.add(personShiftInfoListDTO);
                }


            }

            messageResult.setData(personShiftInfoListList);
            messageResult.setResult(true);
            messageResult.setCode(200);
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            messageResult.setCode(400);
            messageResult.setResult(false);
            messageResult.setMessage(ex.getMessage());
        }

        return messageResult;
    }


}
