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

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.dto.MessageResult;
import com.jpsoft.shinestar.modules.common.dto.Sort;
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.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.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.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
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.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
/**
 * 长者管理
 * sz
 */
@RestController
@RequestMapping("/base/oldPersonInfo")
@Api(description = "oldPersonInfo")
public class OldPersonInfoController {
    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;

    @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());
                personInfoService.update(personInfo);

                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);

            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 = "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")
    })
    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="derviceName",defaultValue="") String derviceName,
            @RequestParam(value="personRoleName",defaultValue="长者") String personRoleName,
            @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,
            @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<>();
        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() + "%");
            }
        }
        else{
            if(subordinate){
                searchParams.put("companyCode", companyCode + "%");
            }
            else {
                searchParams.put("companyCode", companyCode);
            }
        }

        if(StringUtils.isNotEmpty(parentId)){
            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);
        }
        searchParams.put("personRoleName", personRoleName);

        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(" ", "");
                    }

                    if(StringUtils.isEmpty(name)){
                        break;
                    }

                    CompanyInfo companyInfo = companyInfoService.get(companyId);

                    if(StringUtils.isNotEmpty(companyName)){
                        CompanyInfo matchCompany = companyInfoService.findByName(companyName);

                        if(matchCompany!=null){
                            companyInfo = matchCompany;
                        }
                    }

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

                    String structureId = null;

                    if(StringUtils.isNotEmpty(companyStructureName)){
                        CompanyStructureInfo companyStructureInfo = companyStructureInfoService.findByCompanyIdAndName(companyId,companyStructureName);
                        if(companyStructureInfo == null){
                            sheet1.getRow(rowIndex).createCell(validateColIndex).setCellValue("部门不存在!");
                            failCount++;
                            continue;
                        }else{
                            structureId = companyStructureInfo.getId();
                        }
                    }

                    PersonRoleInfo personRoleInfo = personRoleInfoService.get(personRoleId);

                    if(StringUtils.isNotEmpty(roleName)){
                        personRoleInfo = personRoleInfoService.findByRoleNameAndSceneId(roleName,companyInfo.getSceneId());

                        if(personRoleInfo == null){
                            sheet1.getRow(rowIndex).createCell(validateColIndex).setCellValue("该单位不存在该角色!");
                            failCount++;
                            continue;
                        }
                    }

                    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;
                        }
                    }
                    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.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());

                        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")
    })
    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="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,
            @RequestAttribute String subject){
        MessageResult<String> msgResult = new MessageResult<>();
        User user = userService.get(subject);
        CompanyInfo companyInfo = companyInfoService.get(user.getCompanyId());

        try {
            HSSFWorkbook workbook = new HSSFWorkbook();
            HSSFSheet sheet = workbook.createSheet();
            //表头
            HSSFRow rowTitle = sheet.createRow(0);
            HSSFCell cellTitle1 = rowTitle.createCell(0);
            cellTitle1.setCellValue("序号");
            HSSFCell cellTitle2 = rowTitle.createCell(1);
            cellTitle2.setCellValue("姓名");
            HSSFCell cellTitle3 = rowTitle.createCell(2);
            cellTitle3.setCellValue("身份证");
            HSSFCell cellTitle4 = rowTitle.createCell(3);
            cellTitle4.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(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 + "%");
            }

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

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

                HSSFRow rowContent = sheet.createRow(i + 1);
                HSSFCell cellContent1 = rowContent.createCell(0);
                cellContent1.setCellValue(i+1);
                HSSFCell cellContent2 = rowContent.createCell(1);
                if (personInfo.getName() != null) {cellContent2.setCellValue(personInfo.getName());}
                HSSFCell cellContent3 = rowContent.createCell(2);
                if (personInfo.getIdCard() != null) {cellContent3.setCellValue(personInfo.getIdCard());}
                HSSFCell cellContent4 = rowContent.createCell(3);
                if (personInfo.getPhone() != null) {cellContent4.setCellValue(personInfo.getPhone());}
                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);

            String downloadUrl = OSSUtil.upload(ossConfig,"import","error.xls",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;
    }
}
