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

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.jpsoft.shinestar.config.OSSConfig;
import com.jpsoft.shinestar.modules.base.dto.PersonInfoDTO;
import com.jpsoft.shinestar.modules.base.entity.*;
import com.jpsoft.shinestar.modules.base.service.*;
import com.jpsoft.shinestar.modules.common.utils.CheckIdCard;
import com.jpsoft.shinestar.modules.common.utils.OSSUtil;
import com.jpsoft.shinestar.modules.common.utils.POIUtils;
import com.jpsoft.shinestar.modules.common.utils.PojoUtils;
import com.jpsoft.shinestar.modules.common.dto.Sort;
import com.jpsoft.shinestar.modules.common.dto.MessageResult;
import com.jpsoft.shinestar.modules.outapi.dto.GreenCodeDTO;
import com.jpsoft.shinestar.modules.outapi.service.OutApiService;
import com.jpsoft.shinestar.modules.pacs.dto.IsPersonExistVo;
import com.jpsoft.shinestar.modules.pacs.dto.PacsMsgResult;
import com.jpsoft.shinestar.modules.pacs.dto.PacsResult;
import com.jpsoft.shinestar.modules.pacs.service.IGuardService;
import com.jpsoft.shinestar.modules.sys.service.UserCompanyService;
import com.jpsoft.shinestar.modules.uniview.vo.LapiMsgResult;
import com.jpsoft.shinestar.modules.uniview.vo.LapiResult;
import com.jpsoft.shinestar.modules.sys.entity.SysLog;
import com.jpsoft.shinestar.modules.sys.entity.User;
import com.jpsoft.shinestar.modules.sys.service.DataDictionaryService;
import com.jpsoft.shinestar.modules.sys.service.SysLogService;
import com.jpsoft.shinestar.modules.sys.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

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

    @Autowired
    private IGuardService guardService;
    @Autowired
    private OSSConfig ossConfig;
    @Autowired
    private PersonInfoService personInfoService;
    @Autowired
    private UserService userService;
    @Autowired
    private PersonDeviceRelationService personDeviceRelationService;
    @Autowired
    private DeviceInfoService deviceInfoService;
    @Autowired
    private CompanyInfoService companyInfoService;
    @Autowired
    private PersonCompanyService personCompanyService;
    @Autowired
    private CompanyPositionService companyPositionService;
    @Autowired
    private DataDictionaryService dataDictionaryService;
    @Autowired
    private PersonDeviceFilterLogService personDeviceFilterLogService;
    @Autowired
    private PunchLocationService punchLocationService;
    @Autowired
    private PunchRecordService punchRecordService;
    @Autowired
    private SysLogService sysLogService;
    @Autowired
    private PersonRoleInfoService personRoleInfoService;
    @Autowired
    private PersonPopedomService personPopedomService;
    @Autowired
    private CompanyStructureInfoService companyStructureInfoService;
    @Autowired
    private PersonRoleIconService personRoleIconService;
    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private OutApiService outApiService;
    @Autowired
    private UserCompanyService userCompanyService;

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

        PersonInfo personInfo = new PersonInfo();

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

        return msgResult;
    }

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

        try {
            if(personInfo.getName()!= null) {
                personInfo.setName(personInfo.getName().replace(" ", ""));
            }
            if(personInfo.getPhone()!= null) {
                personInfo.setPhone(personInfo.getPhone().replace(" ", ""));
            }
            if(personInfo.getIdCard()!= null) {
                personInfo.setIdCard(personInfo.getIdCard().replace(" ", ""));
            }

            Map<String, Object> searchParams = new HashMap<>();
            searchParams.put("companyId", personInfo.getCompanyId());
            searchParams.put("name", personInfo.getName());
            searchParams.put("phone", personInfo.getPhone());
            List<Sort> sortList = new ArrayList<>();
            sortList.add(new Sort("id_","asc"));
            Page<PersonInfo> page = personInfoService.pageSearch(searchParams, 1, 1,false, sortList);

            if (page.size() > 0) {
                msgResult.setMessage("该人员已存在!");
                msgResult.setResult(false);
                return msgResult;
            } else {
                CheckIdCard cic = null;
                if (StringUtils.isEmpty(personInfo.getIdCard())) {
//                    msgResult.setMessage("身份证不能为空!");
//                    msgResult.setResult(false);
//                    return msgResult;
                } else {
                    personInfo.setIdCard(personInfo.getIdCard().trim().toUpperCase());

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

            personInfo.setDelFlag(false);
            personInfo.setCreateBy(subject);
            personInfo.setCreateTime(new Date());

            int affectCount = personInfoService.insert(personInfo);

            if (affectCount > 0) {
                //添加身份
                PersonPopedom personPopedom = new PersonPopedom();

                String showIcon = personRoleIconService.getDefaultIcon(personInfo.getPersonRoleId());

                personPopedom.setId(UUID.randomUUID().toString());
                personPopedom.setPersonRoleId(personInfo.getPersonRoleId());
                personPopedom.setCompanyId(personInfo.getCompanyId());
                personPopedom.setPersonId(personInfo.getId());
                personPopedom.setShowIconId(showIcon);
                personPopedom.setDelFlag(false);
                personPopedom.setCreateBy(subject);
                personPopedom.setCreateTime(new Date());

                personPopedomService.insert(personPopedom);

                //设置用户身份
                personInfo.setPopedom(personPopedom.getId());
                if(StringUtils.isEmpty(personInfo.getHqStatus())){
                    personInfo.setHqStatus("0");
                }
                personInfoService.update(personInfo);

                if(StringUtils.isEmpty(personInfo.getHqStatus()) || "0".equals(personInfo.getHqStatus())){
                    //如果后勤状态为空 或者为非后勤人员 则清空排序
                    personInfoService.updateNullForHqSortNo(personInfo.getId());
                }

                String personCompany = personInfo.getPersonCompany();

                if(StringUtils.isNotEmpty(personCompany)) {
                    String[] pcs = personCompany.split(",");
                    PersonCompany classPersonCompany = null;

                    //查找新创建用户ID
                    personInfo = personInfoService.findByNameAndPhone(personInfo.getName(), personInfo.getPhone());

                    for (String pc : pcs) {
                        //添加
                        classPersonCompany = new PersonCompany();
                        classPersonCompany.setId(UUID.randomUUID().toString());
                        classPersonCompany.setCompanyId(pc);
                        classPersonCompany.setPersonId(personInfo.getId());
                        classPersonCompany.setDelFlag(false);
                        classPersonCompany.setCreateBy(subject);
                        classPersonCompany.setCreateTime(new Date());
                        personCompanyService.insert(classPersonCompany);
                    }
                }

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

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

        return msgResult;
    }

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

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

            if (personInfo != null) {
                //查询用户关联子公司表
                List<PersonCompany> personCompanyList = personCompanyService.findByPersonId(id);
                String pc = "";
                for(PersonCompany personCompany : personCompanyList){
                    pc += personCompany.getCompanyId() + ",";
                }
                if(pc.length() > 0) {
                    pc = pc.substring(0, pc.length() - 1);
                }

                personInfo.setPersonCompany(pc);

                if(StringUtils.isNotEmpty(personInfo.getCompanyId())) {
                    CompanyInfo companyInfo = companyInfoService.get(personInfo.getCompanyId());

                    if (companyInfo != null) {
                        personInfo.setCompanyType(companyInfo.getType());
                    }
                }

                if (StringUtils.isNotEmpty(personInfo.getPopedom())) {
                    //查询关联身份
                    PersonPopedom personPopedom = personPopedomService.get(personInfo.getPopedom());

                    if (personPopedom != null) {
                        personInfo.setPersonRoleId(personPopedom.getPersonRoleId());
                    }
                }

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

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

        return msgResult;
    }

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

        try {
            personInfo.setUpdateBy(subject);
            personInfo.setUpdateTime(new Date());
//          personInfo.setFaceBound(false);

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

            if(personPopedom!=null) {
                //更新身份
                personPopedom.setCompanyId(personInfo.getCompanyId());
                personPopedom.setPersonRoleId(personInfo.getPersonRoleId());
                personPopedom.setUpdateBy(subject);
                personPopedom.setUpdateTime(new Date());

                personPopedomService.update(personPopedom);
            }
            else{
                //添加身份
                personPopedom = new PersonPopedom();

                String showIcon = personRoleIconService.getDefaultIcon(personInfo.getPersonRoleId());

                personPopedom.setId(UUID.randomUUID().toString());
                personPopedom.setPersonRoleId(personInfo.getPersonRoleId());
                personPopedom.setCompanyId(personInfo.getCompanyId());
                personPopedom.setPersonId(personInfo.getId());
                personPopedom.setShowIconId(showIcon);
                personPopedom.setDelFlag(false);
                personPopedom.setCreateBy(subject);
                personPopedom.setCreateTime(new Date());

                personPopedomService.insert(personPopedom);

                personInfo.setPopedom(personPopedom.getId());
            }

            int affectCount = personInfoService.update(personInfo);


            if(StringUtils.isEmpty(personInfo.getHqStatus()) || "0".equals(personInfo.getHqStatus())){
                //如果后勤状态为空 或者为非后勤人员 则清空排序
                personInfoService.updateNullForHqSortNo(personInfo.getId());
            }

            String personCompany = personInfo.getPersonCompany();
            String[] pcs = personCompany.split(",");
            //删除
            personCompanyService.deleteByPersonId(personInfo.getId());
            PersonCompany classPersonCompany = null;
            for(String pc : pcs){
                //添加
                if(StringUtils.isEmpty(pc)){
                    continue;
                }
                classPersonCompany = new PersonCompany();
                classPersonCompany.setId(UUID.randomUUID().toString());
                classPersonCompany.setCompanyId(pc);
                classPersonCompany.setPersonId(personInfo.getId());
                classPersonCompany.setDelFlag(false);
                classPersonCompany.setCreateBy(subject);
                classPersonCompany.setCreateTime(new Date());
                personCompanyService.insert(classPersonCompany);
            }


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

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

        return msgResult;
    }

    @ApiOperation(value="保存信息")
    @PostMapping("save")
    public MessageResult<PersonInfo> save(@RequestBody PersonInfo personInfo,@RequestAttribute String subject){
        User user = userService.get(subject);
        MessageResult<PersonInfo> msgResult = new MessageResult<>();

        try {
            int affectCount = 0;
            if(personInfo.getId() != null) {
//                personInfo.setCompanyId(user.getCompanyId());
                personInfo.setDelFlag(false);
                personInfo.setCreateBy(subject);
                personInfo.setCreateTime(new Date());

                affectCount = personInfoService.insert(personInfo);
            }else{
                personInfo.setUpdateBy(subject);
                personInfo.setUpdateTime(new Date());

                affectCount = personInfoService.update(personInfo);
            }

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

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

        return msgResult;
    }

    @ApiOperation(value="获取详情信息")
    @GetMapping("detail/{id}")
    public MessageResult<PersonInfo> detail(@PathVariable("id") Long id){
        MessageResult<PersonInfo> msgResult = new MessageResult<>();

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

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

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

        return msgResult;
    }

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

        try {
            PersonInfo personInfo = personInfoService.get(id);
            personInfo.setDelFlag(true);
            personInfo.setUpdateBy(subject);
            personInfo.setUpdateTime(new Date());
            personInfo.setFaceBound(false);
            personInfo.setFaceEnabled(false);

            int affectCount = personInfoService.update(personInfo);

            new Thread(()->{
                try {
                    guardService.deletePerson(personInfo.getId());
                }
                catch (Exception ex){
                    logger.error(ex.getMessage(),ex);
                }
            }).start();

//            HSSFWorkbook workbook = new HSSFWorkbook();
//            HSSFSheet sheet = workbook.createSheet();
//            if(!deleteDevicePerson(personInfo, sheet)){
//                ByteArrayOutputStream output = new ByteArrayOutputStream();
//                workbook.write(output);
//                byte[] buffer = output.toByteArray();
//                ByteArrayInputStream input = new ByteArrayInputStream(buffer);
//                String downloadUrl = OSSUtil.upload(ossConfig,"import","error.xls",input);
//
//                msgResult.setData(false);
//                msgResult.setMessage(downloadUrl);
//            }

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

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

        return msgResult;
    }

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

        try {
            int affectCount = 0;

            for (Long id : idList) {
                PersonInfo personInfo = personInfoService.get(id);
                personInfo.setDelFlag(true);
                personInfo.setUpdateBy(subject);
                personInfo.setUpdateTime(new Date());
                personInfo.setFaceBound(false);
                personInfo.setFaceEnabled(false);

                affectCount += personInfoService.update(personInfo);

                new Thread(()->{
                    try {
                        guardService.deletePerson(personInfo.getId());
                    }
                    catch (Exception ex){
                        logger.error(ex.getMessage(),ex);
                    }
                }).start();
            }

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

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

        return msgResult;
    }

    @ApiOperation(value="列表")
    @RequestMapping(value = "pageList",method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户编号", required = false, paramType = "form", dataType = "String"),
            @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 = "companyCode",value = "企业编码", required = false, paramType = "form",dataType = "String"),
            @ApiImplicitParam(name = "parentId",value = "上级企业ID", required = false, paramType = "form",dataType = "String"),
            @ApiImplicitParam(name = "subordinate",value = "是否查询下级单位", required = false, paramType = "form",dataType = "String"),
            @ApiImplicitParam(name = "derviceName",value = "设备名称", required = false, paramType = "form",dataType = "String"),
            @ApiImplicitParam(name = "hqStatus",value = "后勤类型", required = false, paramType = "form",dataType = "String"),
            @ApiImplicitParam(name = "position1",value = "一级位置", required = false, paramType = "form",dataType = "String"),
            @ApiImplicitParam(name = "position2",value = "二级位置", required = false, paramType = "form",dataType = "String"),
            @ApiImplicitParam(name = "position3",value = "三级位置", required = false, paramType = "form",dataType = "String"),
            @ApiImplicitParam(name = "position4",value = "四级位置", required = false, paramType = "form",dataType = "String"),
            @ApiImplicitParam(name = "position5",value = "五级位置", required = false, paramType = "form",dataType = "String"),
            @ApiImplicitParam(name = "faceBound",value = "是否同步", required = false, paramType = "form",dataType = "String"),
            @ApiImplicitParam(name = "isUploadPhoto",value = "是否上传照片", required = false, paramType = "form",dataType = "String"),
            @ApiImplicitParam(name = "parkId",value = "园区ID", required = false, paramType = "form",dataType = "String"),
            @ApiImplicitParam(name = "healthyCode", value = "健康码", required = false, paramType = "form", dataType = "String"),
            @ApiImplicitParam(name = "outsourcerStatus",value = "是否外勤人员", required = false, paramType = "form",dataType = "String"),
            @ApiImplicitParam(name = "jobNumber",value = "工号", required = false, paramType = "form",dataType = "String"),
            @ApiImplicitParam(name = "carNum",value = "车牌号", required = false, paramType = "form",dataType = "String"),
    })
    public MessageResult<Map> pageList(
            @RequestParam(value = "id", defaultValue = "") String id,
            @RequestParam(value="name",defaultValue="") String name,
            @RequestParam(value="idCard",defaultValue="") String idCard,
            @RequestParam(value="phone",defaultValue="") String phone,
            @RequestParam(value="companyCode",defaultValue="")  String companyCode,
            @RequestParam(value="parentId",defaultValue="")  String parentId,
            @RequestParam(value="subordinate",defaultValue="false")  Boolean subordinate,
            @RequestParam(value="roleId",defaultValue="")  String roleId,
            @RequestParam(value="derviceName",defaultValue="") String derviceName,
            @RequestParam(value="hqStatus",defaultValue="")  String hqStatus,
            @RequestParam(value="position1",defaultValue="") String position1,
            @RequestParam(value="position2",defaultValue="") String position2,
            @RequestParam(value="position3",defaultValue="") String position3,
            @RequestParam(value="position4",defaultValue="") String position4,
            @RequestParam(value="position5",defaultValue="") String position5,
            @RequestParam(value="pageIndex",defaultValue="1") int pageIndex,
            @RequestParam(value="pageSize",defaultValue="20") int pageSize,
            @RequestParam(value="faceBound",defaultValue="") Integer faceBound,
            @RequestParam(value="isUploadPhoto",defaultValue="") String isUploadPhoto,
            @RequestParam(value="parkId",defaultValue="") String parkId,
            @RequestParam(value="enableRegisterExamine",defaultValue="") Boolean enableRegisterExamine,
            @RequestParam(value="enableAttendance",defaultValue="") Boolean enableAttendance,
            @RequestParam(value = "healthyCode", defaultValue = "")String healthyCode ,
            @RequestParam(value="outsourcerStatus",defaultValue="")  String outsourcerStatus,
            @RequestParam(value="jobNumber",defaultValue="")  String jobNumber,
            @RequestParam(value="carNum",defaultValue="")  String carNum,
            @RequestAttribute String subject){
        //当前用户ID
        User user = userService.get(subject);

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

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

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

        List<Sort> sortList = new ArrayList<>();

        if(StringUtils.isNotEmpty(hqStatus)){
            searchParams.put("hqStatus", hqStatus);
            sortList.add(new Sort("a.hq_sort_no", "asc"));
        }
        sortList.add(new Sort("a.id_", "asc"));


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

        if (StringUtils.isNotEmpty(name)) {
            String[] names = name.split(",");
                List nameList = new ArrayList();
                for (String n : names) {
                    nameList.add("%"+ n +"%");
                }
                searchParams.put("nameList", nameList);
        }

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

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

        if (StringUtils.isEmpty(companyCode)){
            if (!userService.hasRole(subject,"SYSADMIN")) {
                searchParams.put("companyCode", companyInfo.getCode() + "%");

                //查询关联单位表
                List<CompanyInfo> relateList = userCompanyService.findByUserId(user.getId());
                searchParams.put("relateCompanyList" , relateList);
            }
        }
        else{
            if(subordinate){
                searchParams.put("companyCode", companyCode + "%");
            }
            else {
                searchParams.put("companyCode", companyCode);
            }
        }

        //选择了上级单位
        if(StringUtils.isNotEmpty(parentId)){
            searchParams.put("relateCompanyList" , null);

            CompanyInfo parentCompanyInfo = companyInfoService.get(parentId);

            String parentCode = parentCompanyInfo.getCode();

            if (StringUtils.isEmpty(parentCode)){
                if (!userService.hasRole(subject,"SYSADMIN")) {
                    searchParams.put("companyCode", companyInfo.getCode() + "%");
                }
            }
            else{
                if(subordinate){
                    searchParams.put("companyCode", parentCode + "%");
                }
                else {
                    searchParams.put("companyCode", parentCode);
                }
            }
        }

        if (StringUtils.isNotEmpty(position1)) {
            searchParams.put("position1","%" + position1 + "%");
        }
        if (StringUtils.isNotEmpty(position2)) {
            searchParams.put("position2","%" + position2 + "%");
        }
        if (StringUtils.isNotEmpty(position3)) {
            searchParams.put("position3","%" + position3 + "%");
        }
        if (StringUtils.isNotEmpty(position4)) {
            searchParams.put("position4","%" + position4 + "%");
        }
        if (StringUtils.isNotEmpty(position5)) {
            searchParams.put("position5","%" + position5 + "%");
        }

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

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

        if(StringUtils.isNotEmpty(derviceName)){
            List<Long> personDeviceRelation = personDeviceRelationService.findByDerviceName("%" + derviceName + "%");
            //String relationPersonIds = String.join(",",personDeviceRelation);
            searchParams.put("relationPersonIds", personDeviceRelation);
        }

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

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

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

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

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

        //查询外协部门
        if(StringUtils.isNotEmpty(outsourcerStatus)){
            if("1".equals(outsourcerStatus)) {
                searchParams.put("isOutsourcer", true);
            }
        }

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

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



        Page<PersonInfo> page = personInfoService.pageSearch(searchParams,pageIndex,pageSize,true,sortList);
        Page<PersonInfoDTO> pageDTO = PojoUtils.convertPage(page, PersonInfoDTO.class);

        for(PersonInfoDTO dto : pageDTO.getResult()){
            List<DeviceInfo> deviceNameList = personDeviceRelationService.findDeviceByPersonId(dto.getId());

            String deviceName = deviceNameList.stream()
                                .map((device)->device.getAliasName())
                                .collect(Collectors.joining(","));

            dto.setDeviceName(deviceName);

            List<PersonPopedom> ppList = personPopedomService.findByPersonId(dto.getId());
            String allMechanismName = ppList.stream()
                    .map((pp)->pp.getCompanyName() + "-" + pp.getRoleName())
                    .collect(Collectors.joining(","));
            dto.setMechanism(allMechanismName);
//            String allRoleName = ppList.stream()
//                    .map((pp)->pp.getRoleName())
//                    .collect(Collectors.joining(","));
//            dto.setAllRoleName(allRoleName);
//            CompanyInfo personCompany = companyInfoService.get(dto.getCompanyId());
//
//            if(personCompany!=null) {
//                dto.setCompanyType(personCompany.getType());
//            }
        }

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

        return msgResult;
    }

    @ApiOperation(value="人脸授权")
    @PostMapping("enabledFace")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "人员编号", required = false, paramType = "form",dataType = "String")
    })
    public MessageResult<Boolean> enabledFace(@RequestParam(value="id",defaultValue="") Long id,@RequestAttribute String subject){
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet();
        MessageResult<Boolean> msgResult = new MessageResult<>();
        msgResult.setData(true);

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

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

                guardService.deletePerson(personInfo.getId());
//                if(!deleteDevicePerson(personInfo, sheet)){
//                    msgResult.setData(false);
//                }

                personInfo.setFaceBound(false);
                personInfo.setUpdateTime(new Date());
                personInfo.setFaceEnabled(false);
            }else{
                personInfo.setFaceEnabled(true);
            }
            personInfo.setUpdateBy(subject);
            personInfo.setUpdateTime(new Date());

            int affectCount = personInfoService.update(personInfo);

            if (affectCount > 0) {
                msgResult.setResult(true);
//                if(!msgResult.getData()){
//                    ByteArrayOutputStream output = new ByteArrayOutputStream();
//                    workbook.write(output);
//                    byte[] buffer = output.toByteArray();
//                    ByteArrayInputStream input = new ByteArrayInputStream(buffer);
//                    String downloadUrl = OSSUtil.upload(ossConfig,"import","error.xls",input);
//
//                    msgResult.setMessage(downloadUrl);
//                }
            }else{
                msgResult.setResult(false);
                msgResult.setMessage("数据库保存失败");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

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

        return msgResult;
    }

    @ApiOperation(value = "自动同步开启关闭")
    @PostMapping("enabledSync")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "人员编号", required = false, paramType = "form", dataType = "String")
    })
    public MessageResult<PersonInfo> enabledSync(@RequestParam(value = "id", defaultValue = "") Long id, @RequestAttribute String subject) {
        MessageResult<PersonInfo> msgResult = new MessageResult<>();

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

            if (personInfo.getIsSync()) {
                personInfo.setIsSync(false);
            } else {
                personInfo.setIsSync(true);
            }
            personInfo.setUpdateBy(subject);
            personInfo.setUpdateTime(new Date());

            int affectCount = personInfoService.update(personInfo);

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

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

        return msgResult;
    }

    @ApiOperation(value = "批量开启自动同步")
    @PostMapping("enabledSyncList")
    public MessageResult<PersonInfo> enabledSyncList(@RequestBody List<String> ids, @RequestAttribute String subject) {
        MessageResult<PersonInfo> msgResult = new MessageResult<>();

        try {
            int affectCount = 0;
            for (String id : ids) {
                PersonInfo personInfo = personInfoService.get(Long.valueOf(id));
                personInfo.setIsSync(true);
                personInfo.setUpdateBy(subject);
                personInfo.setUpdateTime(new Date());
                personInfoService.update(personInfo);

                affectCount++;
            }

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

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

        return msgResult;
    }

    @ApiOperation(value="人脸批量授权")
    @PostMapping("enabledFaceList")
    public MessageResult<PersonInfo> enabledFaceList(@RequestBody List<String> ids,@RequestAttribute String subject){
        MessageResult<PersonInfo> msgResult = new MessageResult<>();

        try {
            int affectCount = 0;
            for(String id : ids) {
                PersonInfo personInfo = personInfoService.get(Long.valueOf(id));
                personInfo.setFaceEnabled(true);
                personInfo.setUpdateBy(subject);
                personInfo.setUpdateTime(new Date());
                personInfoService.update(personInfo);

                affectCount++;
            }

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

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

        return msgResult;
    }

    @ApiOperation(value="刷卡授权")
    @PostMapping("enabledCard")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "人员编号", required = false, paramType = "form",dataType = "String")
    })
    public MessageResult<PersonInfo> enabledCard(@RequestParam(value="id",defaultValue="") Long id,@RequestAttribute String subject){
        MessageResult<PersonInfo> msgResult = new MessageResult<>();

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

            if(personInfo.getCardEnabled()){
                personInfo.setCardEnabled(false);
            }else{
                personInfo.setCardEnabled(true);
            }
            personInfo.setUpdateBy(subject);
            personInfo.setUpdateTime(new Date());

            int affectCount = personInfoService.update(personInfo);

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

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

        return msgResult;
    }

    @ApiOperation(value="手机授权")
    @PostMapping("enabledApp")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "人员编号", required = false, paramType = "form",dataType = "String")
    })
    public MessageResult<PersonInfo> enabledApp(@RequestParam(value="id",defaultValue="") Long id,@RequestAttribute String subject){
        MessageResult<PersonInfo> msgResult = new MessageResult<>();

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

            if(personInfo.getAppEnabled()){
                personInfo.setAppEnabled(false);
            }else{
                personInfo.setAppEnabled(true);
            }
            personInfo.setUpdateBy(subject);
            personInfo.setUpdateTime(new Date());

            int affectCount = personInfoService.update(personInfo);

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

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

        return msgResult;
    }

    @ApiOperation(value="访客授权")
    @PostMapping("enabledGuest")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "人员编号", required = false, paramType = "form",dataType = "String")
    })
    public MessageResult<PersonInfo> enabledGuest(@RequestParam(value="id",defaultValue="") Long id,@RequestAttribute String subject){
        MessageResult<PersonInfo> msgResult = new MessageResult<>();

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

            if(personInfo.getGuestEnabled()){
                personInfo.setGuestEnabled(false);
            }else{
                personInfo.setGuestEnabled(true);
            }
            personInfo.setUpdateBy(subject);
            personInfo.setUpdateTime(new Date());

            int affectCount = personInfoService.update(personInfo);

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

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

        return msgResult;
    }

    @ApiOperation(value="微信通知切换")
    @PostMapping("enabledWechatNotice")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "人员编号", required = false, paramType = "form",dataType = "String")
    })
    public MessageResult<PersonInfo> enabledWechatNotice(@RequestParam(value="id",defaultValue="") Long id,@RequestAttribute String subject){
        MessageResult<PersonInfo> msgResult = new MessageResult<>();

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

            if(personInfo.getWechatNoticeEnabled()!=null && personInfo.getWechatNoticeEnabled()){
                personInfo.setWechatNoticeEnabled(false);
            }else{
                personInfo.setWechatNoticeEnabled(true);
            }

            personInfo.setUpdateBy(subject);
            personInfo.setUpdateTime(new Date());

            int affectCount = personInfoService.update(personInfo);

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

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

        return msgResult;
    }

    @ApiOperation(value="导入人员")
    @PostMapping("importXls")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uploadFile",value = "上传文件", required = true,paramType="form", dataType = "__file")
    })
    public MessageResult<String> importXls(MultipartFile uploadFile,
                                           String companyId,
                                           String personRoleId,
                                           @RequestAttribute String subject){
        User user = userService.get(subject);
        MessageResult<String> msgResult = new MessageResult<>();

        try {
            POIUtils poiUtils = new POIUtils(uploadFile.getInputStream());
            int sheetIndex = 0;
            Sheet sheet1 = poiUtils.getSheetAt(sheetIndex);

            String[] colNames = new String[]{"部门","姓名","身份证","手机号","职位名称","工号"};
            Map<String,Integer> headerMap = new HashMap<>();

            Row headerRow = sheet1.getRow(0);

            for (int i=0;i<colNames.length;i++) {
                String colName = colNames[i];

                for (int j = 0; j < headerRow.getLastCellNum(); j++) {
                    String title = headerRow.getCell(j).getStringCellValue();

                    if (title.indexOf(colName)!=-1){
                        headerMap.put(colName, j);
                        break;
                    }
                }
            }

            int affectCount = 0;
            int failCount = 0;
            int validateColIndex = 13;

            for(int rowIndex=1 ; rowIndex<=sheet1.getLastRowNum(); rowIndex++){
                try {
                    String name = "";

                    if(headerMap.containsKey("姓名")){
                        name = poiUtils.getCellValue(sheetIndex,rowIndex,headerMap.get("姓名")).toString().replace(" ","");
                    }

                    String idCard = "";

                    if(headerMap.containsKey("身份证")) {
                        idCard = poiUtils.getCellValue(sheetIndex, rowIndex, headerMap.get("身份证")).toString().replace(" ", "");
                    }

                    String phone = "";

                    if(headerMap.containsKey("手机号")) {
                        phone = poiUtils.getCellValue(sheetIndex, rowIndex, headerMap.get("手机号")).toString().replace(" ", "");
                    }

                    //公司
                    String companyName = "";

                    if(headerMap.containsKey("部门")) {
                        companyName = poiUtils.getCellValue(sheetIndex, rowIndex, headerMap.get("部门")).toString().replace(" ", "");
                    }
//
//                    //部门
//                    String companyStructureName = "";
//
//                    if(headerMap.containsKey("部门")) {
//                        companyStructureName = poiUtils.getCellValue(sheetIndex, rowIndex, headerMap.get("部门")).toString().replace(" ", "");
//                    }
//
//                    //角色
//                    String roleName = "";
//
//                    if(headerMap.containsKey("角色")) {
//                        roleName = poiUtils.getCellValue(sheetIndex, rowIndex, headerMap.get("角色")).toString().replace(" ", "");
//                    }

                    //职位名称
                    String remarkName = "";

                    if(headerMap.containsKey("职位名称")) {
                        remarkName = poiUtils.getCellValue(sheetIndex, rowIndex, headerMap.get("职位名称")).toString().replace(" ", "");
                    }

                    String jobNumber = "";
                    if(headerMap.containsKey("工号")) {
                        jobNumber = poiUtils.getCellValue(sheetIndex, rowIndex, headerMap.get("工号")).toString().replace(" ", "");
                    }

                    if(StringUtils.isEmpty(companyName)){
                        sheet1.getRow(rowIndex).createCell(validateColIndex).setCellValue("未填写部门!");
                        failCount++;
                        continue;
                    }

                    CompanyInfo companyInfo = companyInfoService.findByName(companyName);
                    if(companyInfo == null){
                        sheet1.getRow(rowIndex).createCell(validateColIndex).setCellValue("部门不存在!");
                        failCount++;
                        continue;
                    }else{
                        companyId = companyInfo.getId();
                    }

                    if(StringUtils.isEmpty(name)){
                        sheet1.getRow(rowIndex).createCell(validateColIndex).setCellValue("未填写姓名!");
                        failCount++;
                        continue;
                    }

                    if(StringUtils.isEmpty(phone)){
                        sheet1.getRow(rowIndex).createCell(validateColIndex).setCellValue("未填写手机!");
                        failCount++;
                        continue;
                    }

                    //CompanyInfo companyInfo = companyInfoService.get(companyId);


//                    if(companyInfo == null){
//                        sheet1.getRow(rowIndex).createCell(validateColIndex).setCellValue("公司不存在!");
//                        failCount++;
//                        continue;
//                    }else{
//                        companyId = companyInfo.getId();
//                    }

                    PersonRoleInfo personRoleInfo = personRoleInfoService.get(personRoleId);

                    String showIcon = personRoleIconService.getDefaultIcon(personRoleInfo.getId());

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

                    //用户身份
                    PersonPopedom personPopedom = new PersonPopedom();
                    personPopedom.setId(UUID.randomUUID().toString());
                    personPopedom.setPersonRoleId(personRoleInfo.getId());
                    personPopedom.setCompanyId(companyId);
                    //personPopedom.setCompanyStructureId(structureId);
                    personPopedom.setShowIconId(showIcon);
                    personPopedom.setRemark(remarkName);
                    personPopedom.setDelFlag(false);
                    personPopedom.setCreateBy(subject);
                    personPopedom.setCreateTime(new Date());

                    if (personInfo!=null) {
//                        personPopedom.setPersonId(personInfo.getId());
//
//                        //用户已存在，判断是否已存在当前角色
//                        PersonPopedom oldPp = personPopedomService.findByVerify(personPopedom);
//
//                        if (oldPp!=null){
//                            //已存在就跳过
//                            affectCount++;
//                            continue;
//                        }

                        //如果用户存在
                        String oldPopedomId = personInfo.getPopedom();
                        PersonPopedom oldPp = personPopedomService.get(oldPopedomId);
                        //先删除旧的角色--用户默认角色
                        if(oldPp != null){
                            oldPp.setDelFlag(true);
                            oldPp.setUpdateBy(subject);
                            oldPp.setUpdateTime(new Date());
                            personPopedomService.update(oldPp);
                        }

                        //修改用户默认公司
                        personInfo.setCompanyId(personPopedom.getCompanyId());
                        //保存新角色ID到用户默认角色
                        personInfo.setPopedom(personPopedom.getId());
                        personInfo.setJobNumber(jobNumber);
                        personInfo.setUpdateBy(subject);
                        personInfo.setUpdateTime(new Date());
                        //修改
                        personInfoService.update(personInfo);
                        personPopedom.setPersonId(personInfo.getId());
                    }
                    else{
                        personInfo = new PersonInfo();

                        personInfo.setCompanyId(companyId);
                        personInfo.setName(name);

                        CheckIdCard cic = null;

                        if(StringUtils.isNotEmpty(idCard)){
                            idCard = idCard.trim().toUpperCase();

                            cic = new CheckIdCard(idCard);
                            if (!cic.validate()){
                                sheet1.getRow(rowIndex).createCell(validateColIndex).setCellValue("身份证验证失败!");
                                failCount++;
                                continue;
                            }
                        }

                        personInfo.setIdCard(idCard);
                        personInfo.setPhone(phone);
                        personInfo.setJobNumber(jobNumber);

                        personInfo.setFaceEnabled(true);
                        personInfo.setCardEnabled(true);
                        personInfo.setAppEnabled(true);
                        personInfo.setGuestEnabled(false);

                        personInfo.setDelFlag(false);
                        personInfo.setCreateBy(subject);
                        personInfo.setCreateTime(new Date());
                        personInfo.setPopedom(personPopedom.getId());
                        personInfo.setHqStatus("0");

                        personInfoService.insert(personInfo);

                        personPopedom.setPersonId(personInfo.getId());
                    }

                    //保存新身份
                    personPopedomService.insert(personPopedom);
                    affectCount++;
                }
                catch(Exception innerEx){
                    logger.error(innerEx.getMessage(),innerEx);
                }
            }

            if (failCount>0){
                //有导入失败的记录
                msgResult.setResult(false);
                msgResult.setMessage("数据成功导入" + affectCount + "条,有" + failCount + "条数据未导入成功，错误原因请查看报表。");

                //todo 只保留错误数据的sheet
                Workbook wb = poiUtils.exportErrorXls(sheetIndex,validateColIndex,1 + affectCount + failCount);

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

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

                String downloadUrl = OSSUtil.upload(ossConfig,"import","error.xls",input);

                //todo 返回导入失败报表下载链接
                msgResult.setData(downloadUrl);
            }
            else{
                msgResult.setResult(true);
                msgResult.setMessage("数据成功导入" + affectCount + "条");
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

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

        return msgResult;
    }

    @ApiOperation(value="导出人员")
    @PostMapping("exportXls")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户编号", required = false, paramType = "form", dataType = "String"),
            @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 = "parentId",value = "企业编号", required = false, paramType = "form",dataType = "String"),
            @ApiImplicitParam(name = "subordinate",value = "是否查询下级单位", required = false, paramType = "form",dataType = "String"),
            @ApiImplicitParam(name = "position1",value = "一级位置", required = false, paramType = "form",dataType = "String"),
            @ApiImplicitParam(name = "position2",value = "二级位置", required = false, paramType = "form",dataType = "String"),
            @ApiImplicitParam(name = "position3",value = "三级位置", required = false, paramType = "form",dataType = "String"),
            @ApiImplicitParam(name = "position4",value = "四级位置", required = false, paramType = "form",dataType = "String"),
            @ApiImplicitParam(name = "position5",value = "五级位置", required = false, paramType = "form",dataType = "String"),
            @ApiImplicitParam(name = "faceBound",value = "是否同步", required = false, paramType = "form",dataType = "String"),
            @ApiImplicitParam(name = "isUploadPhoto",value = "是否上传照片", required = false, paramType = "form",dataType = "String"),
            @ApiImplicitParam(name = "jobNumber",value = "工号", required = false, paramType = "form",dataType = "String"),
            @ApiImplicitParam(name = "carNum",value = "车牌号", required = false, paramType = "form",dataType = "String")
    })
    public MessageResult<String> exportXls(
            @RequestParam(value = "id", defaultValue = "") String id,
            @RequestParam(value="name",defaultValue="") String name,
            @RequestParam(value="idCard",defaultValue="") String idCard,
            @RequestParam(value="phone",defaultValue="") String phone,
            @RequestParam(value="parentId",defaultValue="")  String parentId,
            @RequestParam(value="hqStatus",defaultValue="")  String hqStatus,
            @RequestParam(value="subordinate",defaultValue="false")  Boolean subordinate,
            @RequestParam(value="position1",defaultValue="") String position1,
            @RequestParam(value="position2",defaultValue="") String position2,
            @RequestParam(value="position3",defaultValue="") String position3,
            @RequestParam(value="position4",defaultValue="") String position4,
            @RequestParam(value="position5",defaultValue="") String position5,
            @RequestParam(value="pageIndex",defaultValue="1") int pageIndex,
            @RequestParam(value="pageSize",defaultValue="20") int pageSize,
            @RequestParam(value="faceBound",defaultValue="") Integer faceBound,
            @RequestParam(value="isUploadPhoto",defaultValue="") String isUploadPhoto,
            @RequestParam(value="jobNumber",defaultValue="")  String jobNumber,
            @RequestParam(value="carNum",defaultValue="")  String carNum,
            @RequestAttribute String subject){
        MessageResult<String> msgResult = new MessageResult<>();
        User user = userService.get(subject);
        CompanyInfo companyInfo = companyInfoService.get(user.getCompanyId());

        try {
            XSSFWorkbook workbook = new XSSFWorkbook();
            XSSFSheet sheet = workbook.createSheet();
            //表头
            XSSFRow rowTitle = sheet.createRow(0);
            XSSFCell cellTitle1 = rowTitle.createCell(0);
            cellTitle1.setCellValue("序号");
            XSSFCell cellTitle2 = rowTitle.createCell(1);
            cellTitle2.setCellValue("工号");
            XSSFCell cellTitle3 = rowTitle.createCell(2);
            cellTitle3.setCellValue("姓名");
            XSSFCell cellTitle4 = rowTitle.createCell(3);
            cellTitle4.setCellValue("手机号");
            XSSFCell cellTitle5 = rowTitle.createCell(4);
            cellTitle5.setCellValue("身份证");
            XSSFCell cellTitle6 = rowTitle.createCell(5);
            cellTitle6.setCellValue("单位");

            //获取公司
            //五级位置
            //CompanyInfo companyInfo = companyInfoService.get(companyId);
//            List<CompanyPosition> companyPositionList = companyPositionService.findByCompanyId(user.getCompanyId());
//            CompanyPosition companyPosition = null;
//
//            if (companyPositionList.size() > 0) {
//                companyPosition = companyPositionList.get(0);
//                HSSFCell cellTitle5 = rowTitle.createCell(4);
//                cellTitle5.setCellValue(companyPosition.getPosition1Name());
//                HSSFCell cellTitle6 = rowTitle.createCell(5);
//                cellTitle6.setCellValue(companyPosition.getPosition2Name());
//                HSSFCell cellTitle7 = rowTitle.createCell(6);
//                cellTitle7.setCellValue(companyPosition.getPosition3Name());
//                HSSFCell cellTitle8 = rowTitle.createCell(7);
//                cellTitle8.setCellValue(companyPosition.getPosition4Name());
//                HSSFCell cellTitle9 = rowTitle.createCell(8);
//                cellTitle9.setCellValue(companyPosition.getPosition5Name());
//            }
//            HSSFCell cellTitle5 = rowTitle.createCell(4);
//            cellTitle5.setCellValue("位置1");
//            HSSFCell cellTitle6 = rowTitle.createCell(5);
//            cellTitle6.setCellValue("位置2");
//            HSSFCell cellTitle7 = rowTitle.createCell(6);
//            cellTitle7.setCellValue("位置3");
//            HSSFCell cellTitle8 = rowTitle.createCell(7);
//            cellTitle8.setCellValue("位置4");
//            HSSFCell cellTitle9 = rowTitle.createCell(8);
//            cellTitle9.setCellValue("位置5");
//            HSSFCell cellTitle10 = rowTitle.createCell(9);
//            cellTitle10.setCellValue("人脸开关");
//            HSSFCell cellTitle11 = rowTitle.createCell(10);
//            cellTitle11.setCellValue("刷卡开关");
//            HSSFCell cellTitle12 = rowTitle.createCell(11);
//            cellTitle12.setCellValue("手机开关");
//            HSSFCell cellTitle13 = rowTitle.createCell(12);
//            cellTitle13.setCellValue("访客开关");

            //表内容
            List<Sort> sortList = new ArrayList<>();
            sortList.add(new Sort("a.id_","asc"));
            Map<String,Object> searchParams = new HashMap<>();
//            if (StringUtils.isNotEmpty(name)) {
//                searchParams.put("name","%" + name + "%");
//            }

            if (StringUtils.isNotEmpty(id)) {
                searchParams.put("id",id);
            }
            if (StringUtils.isNotEmpty(name)) {
                String[] names = name.split(",");
                List nameList = new ArrayList();
                for (String n : names) {
                    nameList.add("%"+ n +"%");
                }
                searchParams.put("nameList", nameList);
            }
            if (StringUtils.isNotEmpty(idCard)) {
                searchParams.put("idCard","%" + idCard + "%");
            }
            if (StringUtils.isNotEmpty(phone)) {
                searchParams.put("phone","%" + phone + "%");
            }
            if (StringUtils.isNotEmpty(hqStatus)) {
                searchParams.put("hqStatus",hqStatus);
            }

            if (StringUtils.isNotEmpty(parentId)) {
                CompanyInfo parent = companyInfoService.get(parentId);
                String companyCode = parent!=null ? parent.getCode() : "";

                if (StringUtils.isNotEmpty(companyCode)) {
                    if (subordinate) {
                        searchParams.put("companyCode", companyCode + "%");
                    } else {
                        searchParams.put("companyCode", companyCode);
                    }
                }
            }
            else{
                if (!userService.hasRole(subject, "SYSADMIN")) {
                    searchParams.put("companyCode", companyInfo.getCode() + "%");
                }
            }
//            if (userService.hasRole(subject,"SYSADMIN")) {
//                if(StringUtils.isNotEmpty(companyId)) {
//                    searchParams.put("companyId", companyId);
//                }
//            }
//            else{
//                searchParams.put("companyId",user.getCompanyId());
//
            if (StringUtils.isNotEmpty(position1)) {
                searchParams.put("position1","%" + position1 + "%");
            }
            if (StringUtils.isNotEmpty(position2)) {
                searchParams.put("position2","%" + position2 + "%");
            }
            if (StringUtils.isNotEmpty(position3)) {
                searchParams.put("position3","%" + position3 + "%");
            }
            if (StringUtils.isNotEmpty(position4)) {
                searchParams.put("position4","%" + position4 + "%");
            }
            if (StringUtils.isNotEmpty(position5)) {
                searchParams.put("position5","%" + position5 + "%");
            }

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

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

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

            Page<PersonInfo> page = personInfoService.pageSearch(searchParams,1,10000,false,sortList);

            for(int i=0; i<page.size(); i++){
                PersonInfo personInfo = page.get(i);

                XSSFRow rowContent = sheet.createRow(i + 1);

                XSSFCell cellContent1 = rowContent.createCell(0);
                cellContent1.setCellValue(i+1);
                XSSFCell cellContent2 = rowContent.createCell(1);
                if (personInfo.getCompanyName() != null) {
                    cellContent2.setCellValue(personInfo.getJobNumber());
                }
                XSSFCell cellContent3 = rowContent.createCell(2);
                if (personInfo.getName() != null) {
                    cellContent3.setCellValue(personInfo.getName());
                }
                XSSFCell cellContent4 = rowContent.createCell(3);
                if (personInfo.getPhone() != null) {
                    cellContent4.setCellValue(personInfo.getPhone());
                }
                XSSFCell cellContent5 = rowContent.createCell(4);
                if (personInfo.getIdCard() != null) {
                    cellContent5.setCellValue(personInfo.getIdCard());
                }
                XSSFCell cellContent6 = rowContent.createCell(5);
                if (personInfo.getCompanyName() != null) {
                    cellContent6.setCellValue(personInfo.getCompanyName());
                }

//                HSSFCell cellContent5 = rowContent.createCell(4);
//                if (personInfo.getPosition1() != null) {cellContent5.setCellValue(personInfo.getPosition1());}
//                HSSFCell cellContent6 = rowContent.createCell(5);
//                if (personInfo.getPosition2() != null) {cellContent6.setCellValue(personInfo.getPosition2());}
//                HSSFCell cellContent7 = rowContent.createCell(6);
//                if (personInfo.getPosition3() != null) {cellContent7.setCellValue(personInfo.getPosition3());}
//                HSSFCell cellContent8 = rowContent.createCell(7);
//                if (personInfo.getPosition4() != null) {cellContent8.setCellValue(personInfo.getPosition4());}
//                HSSFCell cellContent9 = rowContent.createCell(8);
//                if (personInfo.getPosition5() != null) {cellContent9.setCellValue(personInfo.getPosition5());}
//                HSSFCell cellContent10 = rowContent.createCell(9);
//                if(personInfo.getFaceEnabled() != null && personInfo.getFaceEnabled() == true) cellContent10.setCellValue("开"); else cellContent10.setCellValue("关");
//                HSSFCell cellContent11 = rowContent.createCell(10);
//                if(personInfo.getCardEnabled() != null && personInfo.getCardEnabled() == true) cellContent11.setCellValue("开"); else cellContent11.setCellValue("关");
//                HSSFCell cellContent12 = rowContent.createCell(11);
//                if(personInfo.getAppEnabled() != null && personInfo.getAppEnabled() == true) cellContent12.setCellValue("开"); else cellContent12.setCellValue("关");
//                HSSFCell cellContent13 = rowContent.createCell(12);
//                if(personInfo.getGuestEnabled() != null && personInfo.getGuestEnabled() == true) cellContent13.setCellValue("开"); else cellContent13.setCellValue("关");
            }

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

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

            //格式化
            SimpleDateFormat sim = new SimpleDateFormat("yyyyMMddHHmmss");
            String fileName = "导出数据" + sim.format(new Date()) + ".xlsx";
            String downloadUrl = OSSUtil.upload(ossConfig,"import",fileName,input);

            //todo 返回导入失败报表下载链接

            msgResult.setData(downloadUrl);
            msgResult.setResult(true);
            //将exal输出到哪个文件夹中
//            ByteArrayOutputStream out = new ByteArrayOutputStream();
//            workbook.write(out);
//            workbook.close();
//
//            String fileName = new String("导出数据".getBytes("UTF-8"), "iso-8859-1");
//            response.setContentType("application/x-msdownload");
//            response.setHeader("Content-Disposition", "attachment;fileName=" + fileName + ".xls");
//            response.getOutputStream().write(out.toByteArray());
//            response.getOutputStream().flush();
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

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

        return msgResult;
    }

    @ApiOperation(value="数据同步")
    @PostMapping("dataSync")
    public MessageResult<Boolean> dataSync(@RequestBody List<String> ids){
        MessageResult<Boolean> msgResult = new MessageResult<>();
        msgResult.setData(true);
        msgResult.setResult(true);

        try {
            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet sheet = workbook.createSheet();

            for(String id : ids){
                PersonInfo personInfo = personInfoService.get(Long.valueOf(id));

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

                if(!addDevicePerson(personInfo, sheet)){
                    msgResult.setData(false);
                    personInfo.setFaceBound(false);
                }else {
                    personInfo.setFaceBound(true);
                }
                personInfo.setFaceEnabled(true);
                personInfo.setUpdateTime(new Date());
                personInfoService.update(personInfo);
            }

            if(!msgResult.getData()){
                ByteArrayOutputStream output = new ByteArrayOutputStream();
                workbook.write(output);
                byte[] buffer = output.toByteArray();
                ByteArrayInputStream input = new ByteArrayInputStream(buffer);
                String downloadUrl = OSSUtil.upload(ossConfig,"import","error.xls",input);

                msgResult.setMessage(downloadUrl);
            }
        }
        catch(Exception ex){
            logger.error(ex.getMessage(),ex);

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

        return msgResult;
    }

    @ApiOperation(value="删除设备人员图片")
    private Boolean deleteDevicePerson(PersonInfo personInfo, HSSFSheet sheet){
        boolean bl = true;

        try {
            List<PacsMsgResult> msgResultList = guardService.deletePerson(personInfo.getId());
            for (int i = 0; i < msgResultList.size(); i++) {
                PacsMsgResult lapiMsgResult = msgResultList.get(i);

                if (!lapiMsgResult.isSuccess()) {
                    HSSFRow row = sheet.createRow(sheet.getLastRowNum() + 1);
                    HSSFCell cell1 = row.createCell(0);
                    cell1.setCellValue(personInfo.getName());
                    HSSFCell cell2 = row.createCell(1);
                    cell2.setCellValue(lapiMsgResult.getAliasName());
                    HSSFCell cell3 = row.createCell(2);
                    cell3.setCellValue("解绑人脸信息失败!");
                    HSSFCell cell4 = row.createCell(3);
                    cell4.setCellValue(lapiMsgResult.getMsg());

                    bl = false;
                }
            }
        }catch(Exception ex) {
            logger.error(ex.getMessage(), ex);
            bl = false;
        }

        return bl;
    }

    @ApiOperation(value="添加设备人员图片")
    private Boolean addDevicePerson(PersonInfo personInfo, HSSFSheet sheet){
        boolean bl = true;

        try {
            List<PacsResult> msgResultList = guardService.addPerson(personInfo.getId());

            for (int i = 0; i < msgResultList.size(); i++) {
                PacsResult lapiResult = msgResultList.get(i);
                if (!lapiResult.isSuccess()) {
                    Map resultMap = (Map)lapiResult.getData();
                    HSSFRow row = sheet.createRow(sheet.getLastRowNum() + 1);
                    HSSFCell cell1 = row.createCell(0);
                    cell1.setCellValue(personInfo.getName());
                    HSSFCell cell2 = row.createCell(1);
                    cell2.setCellValue(resultMap.get("deviceAliasName").toString());
                    HSSFCell cell3 = row.createCell(2);
                    cell3.setCellValue("绑定人脸信息失败!");
                    HSSFCell cell4 = row.createCell(3);
                    cell4.setCellValue(lapiResult.getMsg());

                    bl = false;
                }
            }
        }catch(Exception ex) {
            logger.error(ex.getMessage(), ex);
            bl = false;

            HSSFRow row = sheet.createRow(sheet.getLastRowNum() + 1);

            HSSFCell cell1 = row.createCell(0);
            cell1.setCellValue(personInfo.getName());

            HSSFCell cell2 = row.createCell(1);
            cell2.setCellValue("");

            HSSFCell cell3 = row.createCell(2);
            cell3.setCellValue("");

            HSSFCell cell4 = row.createCell(3);
            cell4.setCellValue(ex.getMessage());
        }

        return bl;
    }

    @PostMapping("lifeRecordList")
    @ResponseBody
    @ApiOperation(value = "生活记录列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "queryDate", value = "选择日期,格式：yyyy-MM-dd", required = true, paramType = "query"),
            @ApiImplicitParam(name = "personId", value = "人员ID", required = true, paramType = "query")
    })
    public MessageResult<List<Map<String, Object>> > lifeRecordList(String queryDate, String personId, @RequestAttribute String subject) {
        MessageResult<List<Map<String, Object>> > messageResult = new MessageResult<>();

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

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

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

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

            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            Date query = sdf.parse(queryDate);

            Date endDate = new DateTime(query).plusDays(1).toDate();

            String start = queryDate;
            String end = sdf.format(endDate);

            List<PersonDeviceFilterLog> personDeviceFilterLogList = personDeviceFilterLogService.findByPersonAndDate(personInfo.getId(), start, end);

            for (PersonDeviceFilterLog item : personDeviceFilterLogList) {
                Map<String, Object> map = new HashMap<>();

                if (item.getRecordTime() != null) {
                    String recordTime = sdf1.format(item.getRecordTime());
                    map.put("recordTime", recordTime);

                    DeviceInfo device = deviceInfoService.getByDeviceNo(item.getDeviceNo());
                    String deviceName = "";
                    String longtitude = "";
                    String latitude = "";
                    if (device != null) {
                        deviceName = device.getAliasName() + "打卡";
                        longtitude = device.getLongtitude();
                        latitude = device.getLatitude();
                    }

                    map.put("deviceName", deviceName);
                    map.put("longtitude", longtitude);
                    map.put("latitude", latitude);
                }

                list.add(map);
            }

            List<PunchRecord> punchRecordList = punchRecordService.findByPersonAndDate(personInfo.getId(), start, end);
            if (punchRecordList.size()>0){
                for (PunchRecord punchRecord : punchRecordList){
                    PunchLocation punchLocation = punchLocationService.get(punchRecord.getPunchId());
                    if (punchLocation != null){
                        Map<String, Object> map = new HashMap<>();
                        map.put("recordTime",sdf1.format(punchRecord.getCreateTime()));
                        map.put("deviceName", punchLocation.getName());
                        map.put("longtitude", punchLocation.getLongtitude());
                        map.put("latitude", punchLocation.getLatitude());
                        list.add(map);
                    }
                }
            }

            List<Map<String, Object>> sortedList = list.stream().sorted(((l,r)->{
                String time1 = (String)l.get("recordTime");
                String time2 = (String)r.get("recordTime");

                return time2.compareTo(time1);
            })).collect(Collectors.toList());

            messageResult.setData(sortedList);
            messageResult.setResult(true);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            messageResult.setMessage(ex.getMessage());
            messageResult.setResult(false);
        }
        return messageResult;
    }

    @ApiOperation(value = "清除微信openId")
    @PostMapping("unbindWechat")
    public MessageResult<String> unbindWechat(@RequestBody Long id, @RequestAttribute String subject) {
        MessageResult<String> msgResult = new MessageResult<>();

        try {
            PersonInfo personInfo = personInfoService.get(id);
            int affectCount = personInfoService.resetOpenId(id);

            if (affectCount > 0) {
                SysLog sysLog = new SysLog();
                sysLog.setUserId(id+"");
                sysLog.setPointcut("清空微信openId");
                sysLog.setRemark("清空:" + personInfo.getName() + "(" + id + ")的openId:" + personInfo.getOpenId());
                sysLog.setCreateTime(new Date());
                sysLogService.insert(sysLog);

                msgResult.setResult(true);
            } else {
                msgResult.setResult(false);
                msgResult.setMessage("更新失败");
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);

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

        return msgResult;
    }

    @ApiOperation(value = "批量删除用户所有设备上的照片")
    @PostMapping("batchClearFaceImg")
    public MessageResult<String> batchClearFaceImg(@RequestBody List<Long> idList) {
        MessageResult<String> msgResult = new MessageResult<>();

        try {
            for (Long personId : idList) {
                rabbitTemplate.convertAndSend("removeImageExchange", "removeImage", personId);
            }

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

        return msgResult;
    }

    @ApiOperation(value = "删除用户所有设备上的照片")
    @PostMapping("clearFaceImg")
    public MessageResult<Boolean> clearFaceImg(@RequestBody Long id, @RequestAttribute String subject) {
        MessageResult<Boolean> msgResult = new MessageResult<>();
        msgResult.setResult(true);

        Boolean isSuccess = true;
        try {
            //List<PacsMsgResult> result = guardService.deletePerson(id);
            PersonInfo personInfo = personInfoService.get(id);
            if(personInfo == null){
                return msgResult;
            }
            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet sheet = workbook.createSheet();
            if(!deleteDevicePerson(personInfo, sheet)){
                ByteArrayOutputStream output = new ByteArrayOutputStream();
                workbook.write(output);
                byte[] buffer = output.toByteArray();
                ByteArrayInputStream input = new ByteArrayInputStream(buffer);
                String downloadUrl = OSSUtil.upload(ossConfig,"import","error.xls",input);

                msgResult.setData(false);
                msgResult.setMessage(downloadUrl);
            }

            //更新图片状态
            List<PersonDeviceRelation> pdrList = personDeviceRelationService.findByPersonId(id);
            for(PersonDeviceRelation pdr : pdrList) {
                DeviceInfo di = pdr.getDeviceInfo();
                PersonInfo pi = pdr.getPersonInfo();
                String faceDbId = "";
                Boolean isWrite = false;
//                try {
//                    //查找人脸ID
//                    faceDbId = guardService.getFaceDbId(di, pi.getCompanyName());
//                    //查询人员是否成功写入设备
//                    isWrite = guardService.isPersonImageExist(pi, di, faceDbId);
//
//                } catch (Exception e) {
//                    isWrite = false;
//                }

                List<IsPersonExistVo> personExistList = guardService.existPersonInDevice(Arrays.asList(personInfo.getId()),di);

                if (personExistList.size()>0){
                    isWrite = personExistList.get(0).getIsPersonExist();
                }
                //更新状态
                pdr.setIsBound(isWrite);
                pdr.setUpdateBy(subject);
                pdr.setUpdateTime(new Date());
                personDeviceRelationService.update(pdr);
            }
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);

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

        return msgResult;
    }


    @ApiOperation(value = "根据公司查询租户")
    @PostMapping("findByCompanyId")
    public MessageResult<Object> findByCompanyId(String companyId) {
        MessageResult<Object> msgResult = new MessageResult<>();

        try {
            List<PersonInfo> list = personInfoService.findByCompanyId(companyId);

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

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

        return msgResult;
    }

    @ApiOperation(value = "根据后勤公司查询用户")
    @PostMapping("findByHqCompanyId")
    public MessageResult<Object> findByHqCompanyId(String companyId) {
        MessageResult<Object> msgResult = new MessageResult<>();

        try {

            Map<String,Object> searchParams = new HashMap<>();
            if ("hq1".equals(companyId)) {
                //外勤1
                List<CompanyInfo> list1 = companyInfoService.findByClassify("1");
                searchParams.put("companyInfos", list1);

                searchParams.put("hqStatus", "1");
            } else if ("hq2".equals(companyId)) {
                //外勤2
                List<CompanyInfo> list2 = companyInfoService.findByClassify("2");
                searchParams.put("companyInfos", list2);

                searchParams.put("hqStatus", "2");
            } else {
                CompanyInfo parentCompanyInfo = companyInfoService.get(companyId);
                String parentCode = parentCompanyInfo.getCode();
                searchParams.put("attendanceCompanyCode", parentCode + "%");
                searchParams.put("hqStatus", parentCompanyInfo.getClassify());
            }

            List<Sort> sortList = new ArrayList<>();
            sortList.add(new Sort("b.sort_no","asc"));
            sortList.add(new Sort("a.id_","asc"));
            //用户左边列
            Page<PersonInfo> personInfoPage = personInfoService.pageSearch(searchParams,0,10000,false,sortList);
            List<PersonInfo> list = personInfoPage.getResult();

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

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

        return msgResult;
    }

    @ApiOperation(value = "查询物业公司所在人员")
    @PostMapping("findByCompanyCode")
    public MessageResult<Object> findByCompanyCode(@RequestAttribute String subject) {
        MessageResult<Object> msgResult = new MessageResult<>();

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

            User user = userService.get(subject);

            if(user!=null){
                searchParams.put("code","%"+user.getCompanyId()+"%");
            }

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

            List<PersonInfo> list = personInfoService.findByCompanyCode(searchParams,sortList);

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

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

        return msgResult;
    }

    @GetMapping("updateHealthyCode")
    @ApiOperation(value="更新健康码")
    public MessageResult<GreenCodeDTO> updateHealthyCode(long personId){
        MessageResult<GreenCodeDTO> messageResult = new MessageResult<>();

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

            if (StringUtils.isNotBlank(personInfo.getName()) && StringUtils.isNotBlank(personInfo.getIdCard())){
                String  name = personInfo.getName();
                String idCard = personInfo.getIdCard();

                String codeKey = "greenCode_" + name + "_" + idCard;

                redisTemplate.delete(codeKey);

                GreenCodeDTO dto = outApiService.getGreenCode(name, idCard);

                messageResult.setData(dto);
            }

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

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

        return messageResult;
    }

    @PostMapping(value="findPersonByName")
    @ApiOperation(value = "查询人员")
    public MessageResult<List> findPersonByName(@RequestBody JSONObject requestBody){
        String initValue = requestBody.getString("initValue");
        String query = requestBody.getString("query");

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

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

            Set<Long> personIdSet = new HashSet<>();

            if(StringUtils.isNotEmpty(initValue)) {
                String[] arr = initValue.split(",");

                for (String personId : arr) {
                    PersonInfo personInfo = personInfoService.get(Long.valueOf(personId));

                    Map<String, Object> personMap = new HashMap<>();
                    personMap.put("personId", personInfo.getId());
                    personMap.put("strId", personInfo.getId().toString());
                    personMap.put("name", personInfo.getName() + "—" + personInfo.getCompanyName());

                    mapList.add(personMap);

                    personIdSet.add(personInfo.getId());
                }
            }

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

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

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

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

            for (PersonInfo personInfo : page.getResult()) {
                if(!personIdSet.contains(personInfo.getId())) {
                    Map<String, Object> personMap = new HashMap<>();
                    personMap.put("personId", personInfo.getId());
                    personMap.put("strId", personInfo.getId().toString());
                    personMap.put("name", personInfo.getName() + "—" + personInfo.getCompanyName());

                    mapList.add(personMap);
                    personIdSet.add(personInfo.getId());
                }
            }

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

        return messageResult;
    }

    @ApiOperation(value = "查询物业公司所在人员")
    @PostMapping("findStrIdByCompanyCode")
    public MessageResult<Object> findStrIdByCompanyCode(@RequestAttribute String subject) {
        MessageResult<Object> msgResult = new MessageResult<>();

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

            User user = userService.get(subject);

            if(user!=null){
                CompanyInfo companyInfo = companyInfoService.get(user.getCompanyId());
                searchParams.put("code",companyInfo.getCode()+"%");
            }

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

            List<PersonInfo> list = personInfoService.findByCompanyCode(searchParams,sortList);

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

            for (PersonInfo personInfo:list) {
                Map<String,Object> personMap = new HashMap<>();
                personMap.put("strId",personInfo.getId().toString());
                personMap.put("name",personInfo.getName()+"—"+personInfo.getCompanyName());

                mapList.add(personMap);
            }

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

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

        return msgResult;
    }

    //下载图片
    @RequestMapping(value = "/downladUserImg", method = RequestMethod.POST)
    public void downladUserImg(@RequestParam(value="companyCode",defaultValue="")  String companyCode,
                               @RequestParam(value="subordinate",defaultValue="false")  Boolean subordinate,
                               HttpServletResponse response) {
        try {

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

            if(subordinate){
                searchParams.put("companyCode", "%" + companyCode + "%");
            }
            else {
                searchParams.put("companyCode", companyCode);
            }

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

            Page<PersonInfo> page = personInfoService.pageSearch(searchParams,0,1000000,false,sortList);
            for(PersonInfo personInfo : page.getResult()) {
                String fileName = "无名";
                String fileUrl = personInfo.getFaceImageUrl();
                if(StringUtils.isEmpty(fileUrl)){
                    continue;
                }
                fileUrl = fileUrl.replace(" ","%20");

                fileName =personInfo.getCompanyName() + "-" +  personInfo.getName();
                //定义一个URL对象，就是你想下载的图片的URL地址
                URL url = new URL(fileUrl);
                //打开连接
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                //设置请求方式为"GET"
                conn.setRequestMethod("GET");
                //超时响应时间为10秒
                conn.setConnectTimeout(10 * 1000);
                //通过输入流获取图片数据
                InputStream is = conn.getInputStream();
                //得到图片的二进制数据，以二进制封装得到数据，具有通用性
                byte[] data = readInputStream(is);
                //创建一个文件对象用来保存图片，默认保存当前工程根目录，起名叫Copy.jpg
                File imageFile = new File("D:\\img\\" + fileName + ".jpg");
                //创建输出流
                FileOutputStream outStream = new FileOutputStream(imageFile);
                //写入数据
                outStream.write(data);
                //关闭输出流，释放资源
                outStream.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static byte[] readInputStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        //创建一个Buffer字符串
        byte[] buffer = new byte[6024];
        //每次读取的字符串长度，如果为-1，代表全部读取完毕
        int len;
        //使用一个输入流从buffer里把数据读取出来
        while ((len = inStream.read(buffer)) != -1) {
            //用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
            outStream.write(buffer, 0, len);
        }
        //关闭输入流
        inStream.close();
        //把outStream里的数据写入内存
        return outStream.toByteArray();

    }


    @ApiOperation(value = "打包下载照片")
    @RequestMapping(value = "downloadImgZip", method = RequestMethod.GET)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "选中编号", required = true, paramType = "query"),
    })
    public void downloadImgZip(String parentId,Boolean subordinate, HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setCharacterEncoding("utf-8");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);

            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            //设置编码  为了解决中文名称乱码问题
            String fileName = "人员照片" + sdf.format(new Date());
            String zipFileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
            response.setHeader("Content-Disposition", "attachment;fileName=" + zipFileName + ".zip");

            //打包文件
            List<Map<String, Object>> fileList = new ArrayList<>();


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

            List<Sort> sortList = new ArrayList<>();

            sortList.add(new Sort("a.id_", "asc"));

            //选择了上级单位
            if(StringUtils.isNotEmpty(parentId)){
                searchParams.put("relateCompanyList" , null);

                CompanyInfo parentCompanyInfo = companyInfoService.get(parentId);

                String parentCode = parentCompanyInfo.getCode();

                if(subordinate){
                    searchParams.put("companyCode", parentCode + "%");
                }
                else {
                    searchParams.put("companyCode", parentCode);
                }

            }

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

            //二维码
            for (PersonInfo personInfo : page.getResult()) {
                if (StringUtils.isNotEmpty(personInfo.getFaceImageUrl())) {
                    String url = personInfo.getFaceImageUrl();
                    String photoExt = url.substring(url.lastIndexOf("."));
                    String photoFileName = personInfo.getName() + "-" + personInfo.getId() + "-" + photoExt;
                    if(StringUtils.isNotEmpty(personInfo.getJobNumber())) {
                        photoFileName = personInfo.getName() + "-" + personInfo.getId() + "-" + personInfo.getJobNumber() + "-" +  photoExt;
                    }

                    Map<String, Object> fileMap = new HashMap<>();
                    fileMap.put("fileUrl", url + "?x-oss-process=image/resize,l_800,limit_1");
                    fileMap.put("filePath", "照片/");
                    fileMap.put("fileName", photoFileName);

                    fileList.add(fileMap);
                }
            }

            OutputStream output = response.getOutputStream();

            OSSUtil.batchDownload(fileList, output);

            output.flush();
            output.close();
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
        }
    }

}
