package com.yeejoin.precontrol.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.PropertyUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.typroject.tyboot.core.foundation.context.RequestContext;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.component.rule.RuleTrigger;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.feign.privilege.model.CompanyModel;
import com.yeejoin.amos.feign.privilege.model.DepartmentModel;
import com.yeejoin.amos.feign.privilege.model.PermissionModel;
import com.yeejoin.amos.feign.privilege.model.RoleModel;
import com.yeejoin.precontrol.common.annotations.OpsLog;
import com.yeejoin.precontrol.common.constant.Constant;
import com.yeejoin.precontrol.common.dto.CommonPageableDto;
import com.yeejoin.precontrol.common.dto.OutOccupationDto;
import com.yeejoin.precontrol.common.dto.PersonDto;
import com.yeejoin.precontrol.common.dto.SingBadManagementDto;
import com.yeejoin.precontrol.common.dto.TeamPersonSearchDto;
import com.yeejoin.precontrol.common.entity.BadManagementPerson;
import com.yeejoin.precontrol.common.entity.Company;
import com.yeejoin.precontrol.common.entity.CompanyAcount;
import com.yeejoin.precontrol.common.entity.CompanyDepartment;
import com.yeejoin.precontrol.common.entity.Person;
import com.yeejoin.precontrol.common.entity.PersonAccount;
import com.yeejoin.precontrol.common.entity.PersonAscription;
import com.yeejoin.precontrol.common.entity.PersonContract;
import com.yeejoin.precontrol.common.entity.PersonContractAttachment;
import com.yeejoin.precontrol.common.entity.PersonExam;
import com.yeejoin.precontrol.common.entity.PersonExamination;
import com.yeejoin.precontrol.common.entity.PersonExaminationAttachment;
import com.yeejoin.precontrol.common.entity.PersonInsurance;
import com.yeejoin.precontrol.common.entity.PersonInsuranceAttachment;
import com.yeejoin.precontrol.common.entity.PersonQualifications;
import com.yeejoin.precontrol.common.entity.PersonQualificationsAttachment;
import com.yeejoin.precontrol.common.entity.PersonSkillEducation;
import com.yeejoin.precontrol.common.entity.Project;
import com.yeejoin.precontrol.common.entity.ProjectDevice;
import com.yeejoin.precontrol.common.entity.TaskPerson;
import com.yeejoin.precontrol.common.entity.UserRegistration;
import com.yeejoin.precontrol.common.enums.AscriptionStatusEum;
import com.yeejoin.precontrol.common.enums.ContractTypeEum;
import com.yeejoin.precontrol.common.enums.ContractUsefulEum;
import com.yeejoin.precontrol.common.enums.ExpiryTypeEum;
import com.yeejoin.precontrol.common.enums.HealthStatusEum;
import com.yeejoin.precontrol.common.enums.IdTypeEum;
import com.yeejoin.precontrol.common.enums.OfflineExamEnum;
import com.yeejoin.precontrol.common.enums.OpsLogEnum;
import com.yeejoin.precontrol.common.enums.PersonActiveStatusEnum;
import com.yeejoin.precontrol.common.enums.RoleEnum;
import com.yeejoin.precontrol.common.enums.SexEum;
import com.yeejoin.precontrol.common.enums.SmallProPageEnum;
import com.yeejoin.precontrol.common.enums.SmallProQrColorEum;
import com.yeejoin.precontrol.common.enums.TaskTypeEnum;
import com.yeejoin.precontrol.common.enums.TypeKeyEnum;
import com.yeejoin.precontrol.common.enums.WordTemplateTypeEum;
import com.yeejoin.precontrol.common.exception.BaseException;
import com.yeejoin.precontrol.common.exception.errorEnum.BaseExceptionEnum;
import com.yeejoin.precontrol.common.feign.IntegralFeign;
import com.yeejoin.precontrol.common.feign.KnowledgeBaseFeign;
import com.yeejoin.precontrol.common.param.PersonParam;
import com.yeejoin.precontrol.common.param.VerityPersonParam;
import com.yeejoin.precontrol.common.publish.TranslateEventPublish;
import com.yeejoin.precontrol.common.service.FileService;
import com.yeejoin.precontrol.common.service.IBadManagementPersonService;
import com.yeejoin.precontrol.common.service.IBadManagementService;
import com.yeejoin.precontrol.common.service.ICompanyAcountService;
import com.yeejoin.precontrol.common.service.ICompanyDepartmentService;
import com.yeejoin.precontrol.common.service.ICompanyService;
import com.yeejoin.precontrol.common.service.IDistrictsService;
import com.yeejoin.precontrol.common.service.IPersonAscriptionService;
import com.yeejoin.precontrol.common.service.IPersonContractAttachmentService;
import com.yeejoin.precontrol.common.service.IPersonContractService;
import com.yeejoin.precontrol.common.service.IPersonExamService;
import com.yeejoin.precontrol.common.service.IPersonExaminationAttachmentService;
import com.yeejoin.precontrol.common.service.IPersonExaminationService;
import com.yeejoin.precontrol.common.service.IPersonInsuranceAttachmentService;
import com.yeejoin.precontrol.common.service.IPersonInsuranceService;
import com.yeejoin.precontrol.common.service.IPersonQualificationsAttachmentService;
import com.yeejoin.precontrol.common.service.IPersonQualificationsService;
import com.yeejoin.precontrol.common.service.IPersonService;
import com.yeejoin.precontrol.common.service.IPersonSkillEducationService;
import com.yeejoin.precontrol.common.service.IProjectDeviceService;
import com.yeejoin.precontrol.common.service.IProjectService;
import com.yeejoin.precontrol.common.service.IStatisticsService;
import com.yeejoin.precontrol.common.service.ITaskPersonService;
import com.yeejoin.precontrol.common.service.IUserRegistrationService;
import com.yeejoin.precontrol.common.service.SmallProService;
import com.yeejoin.precontrol.common.utils.CommonResponseUtil;
import com.yeejoin.precontrol.common.utils.FileHelper;
import com.yeejoin.precontrol.common.utils.PlatformUtils;
import com.yeejoin.precontrol.common.utils.RedisUtil;
import com.yeejoin.precontrol.common.utils.StringUtil;
import com.yeejoin.precontrol.common.utils.WordTemplateUtils;
import com.yeejoin.precontrol.common.vo.ApprovalPersonVo;
import com.yeejoin.precontrol.common.vo.PersonMsgVo;
import com.yeejoin.precontrol.common.vo.PersonSalaryExcelVo;
import com.yeejoin.precontrol.common.vo.PersonVo;
import com.yeejoin.precontrol.common.vo.ReginParams;
import com.yeejoin.precontrol.common.vo.TeamVo;
import com.yeejoin.precontrol.common.ws.WebSocket;
import com.yeejoin.precontrol.controller.publics.BaseController;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import sun.misc.BASE64Encoder;

/**
 * 人员基本信息
 *
 * @author duanwei
 * @date 2020-06-30
 */
@RestController
@Api(tags = "人员api")
@RequestMapping(value = "/person", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Slf4j
public class PersonController extends BaseController {
	/**
	 * 用户服务
	 */
	@Autowired
	IPersonService iPersonService;
	/**
	 * 关系表服务
	 */
	@Autowired
	IPersonAscriptionService ascriptionService;
	/**
	 * 人员技能和学历服务
	 */
	@Autowired
	IPersonSkillEducationService skillEducationService;
	/**
	 * 人员资质信息服务
	 */
	@Autowired
	IPersonQualificationsService qualificationService;
	/**
	 * 人员资质信息附件服务
	 */
	@Autowired
	IPersonQualificationsAttachmentService qualificAttachService;
	/**
	 * 人员合同信息服务
	 */
	@Autowired
	IPersonContractService contractService;
	/**
	 * 人员合同信息附件服务
	 */
	@Autowired
	IPersonContractAttachmentService contractAttachService;
	/**
	 * 人员体检信息服务类
	 */
	@Autowired
	IPersonExaminationService examinnationService;
	/**
	 * 人员体检信息附件服务
	 */
	@Autowired
	IPersonExaminationAttachmentService examinatiAttachService;
	/**
	 * 人员保险信息服务
	 */
	@Autowired
	IPersonInsuranceService insuranceService;
	/**
	 * 人员保险信息附件服务
	 */
	@Autowired
	IPersonInsuranceAttachmentService insuranceAttachService;
	/**
	 * 小程序服务
	 */
	@Autowired
	SmallProService smallProService;
	/**
	 * 文件服务
	 */
	@Autowired
	FileService fileService;
	/**
	 * 地区服务
	 */
	@Autowired
	IDistrictsService districtsService;
	/**
	 * 公司服务
	 */
	@Autowired
	ICompanyService companyService;
	/**
	 * 项目服务
	 */
	@Autowired
	IProjectService projectService;
	/**
	 * 翻译事件服务
	 */
	@Autowired
	TranslateEventPublish translateEventPublish;
	/**
	 * 文件服务器地址
	 */
	@Value("${fileserver.domain}")
	String fileServerUrl;
	/**
	 * 公司服务
	 */
	@Autowired
	ICompanyService iCompanyService;
	/**
	 * 关系表服务
	 */
	@Autowired
	IPersonAscriptionService iPersonAscriptionService;
	/**
	 * 公司账户服务
	 */
	@Autowired
	ICompanyAcountService iCompanyAcountService;
	/**
	 * 考试成绩服务
	 */
	@Autowired
	IPersonExamService iPersonExamService;
	/**
	 * 产品号
	 */
	@Value("${admin.product}")
	String product;
	/**
	 * 产品密钥
	 */
	@Value("${admin.appkey}")
	String appkey;
	/**
	 * 账户
	 */
	@Value("${admin.user}")
	String user;
	/**
	 * 密码
	 */
	@Value("${admin.password}")
	String password;

	@Autowired
	IBadManagementService iBadManagementService;

	@Autowired
	IBadManagementPersonService iBadManagementPersonService;

	@Autowired
	KnowledgeBaseFeign KnowledgeBaseFeign;

	@Autowired
	IProjectDeviceService iProjectDeviceService;

	@Autowired
	RuleTrigger ruleTrigger;

	@Autowired
	IPersonExamService personExamService;

	@Autowired
	RedisUtil redisUtil;

	@Autowired
	IStatisticsService statisticsService;

	@Autowired
	IntegralFeign integralFeign;

	@Autowired
	IUserRegistrationService userRegistrationService;

	@Autowired
	ICompanyDepartmentService companyDepartmentService;

	@Autowired
	ITaskPersonService taskPersonService;
	
	@Autowired
	PlatformUtils platformUtils;

	/**
	 * 新增人员基本信息
	 *
	 * @return
	 */
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	@ApiOperation(httpMethod = "POST", value = "新增人员基本信息", notes = "新增人员基本信息")
	public Object savePerson(@RequestBody PersonDto personDto) {
		Person person = iPersonService.queryByIdNumber(personDto.getIdNumber());
		if (person != null) {
			throw new BaseException("该身份证号已存在");
		}
		Person resultPerson = this.saveOrUpdatePerson(personDto);
		translateEventPublish.publish(resultPerson);
		return true;
	}

	/**
	 * 修改人员基本信息
	 *
	 * @return
	 */
	@RequestMapping(value = "/updateById", method = RequestMethod.PUT)
	@ApiOperation(httpMethod = "PUT", value = "修改人员基本信息", notes = "修改人员基本信息")
	@OpsLog(value = OpsLogEnum.EDIT_PERSON)
	public Object updateByIdPerson(HttpServletRequest request, @RequestBody PersonDto personDto) {
		Person person = this.saveOrUpdatePerson(personDto);
		translateEventPublish.publish(person);
		return true;
	}

	/**
	 * 根据id删除
	 *
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
	@ApiOperation(httpMethod = "DELETE", value = "根据id删除", notes = "根据id删除")
	public Object deleteById(@PathVariable Long id) {
		HashMap filters = new HashMap<String, Long>();
		filters.put("person_id", id);
		try {
			// 归属信息
			ascriptionService.removeByMap(filters);
			// 技能学历
			skillEducationService.removeByMap(filters);
			// 资质信息
			qualificationService.removeByMap(filters);
			// 合同信息
			contractService.removeByMap(filters);
			// 体检信息
			examinnationService.removeByMap(filters);
			// 保险信息
			insuranceService.removeByMap(filters);
			// 人员信息
			iPersonService.removeById(id);
			return true;
		} catch (Exception e) {
			throw new BaseException("删除失败:" + e.toString());
		}
	}

	/**
	 * 根据ids删除
	 *
	 * @param ids
	 * @return
	 */
	@RequestMapping(value = "/ids/{ids}", method = RequestMethod.DELETE)
	@ApiOperation(httpMethod = "DELETE", value = "根据ids删除", notes = "根据ids删除")
	@OpsLog(value = OpsLogEnum.DELETE_PERSON)
	public Object deleteByIds(HttpServletRequest request, @PathVariable List<Long> ids) {
		int count = iPersonAscriptionService.count(new LambdaQueryWrapper<PersonAscription>()
				.in(PersonAscription::getPersonId, ids).isNotNull(PersonAscription::getProjectId));
		if (count > 0) {
			throw new BaseException("人员未离岗,无法删除");
		}
		List<Person> list = iPersonService.list(new LambdaQueryWrapper<Person>().in(Person::getId, ids));
		List<String> phones = list.stream().map(i -> i.getPhone()).collect(Collectors.toList());
		List<String> userIds = list.stream().map(i -> i.getUserId().toString()).collect(Collectors.toList());
		String users = Arrays.toString(userIds.toArray());
		users = users.replace("[", "").replace("]", "");
		FeignClientResult<List<String>> result = Privilege.agencyUserClient.multDeleteUser(users);
		if (result.getStatus() == 200 && StringUtil.isNotEmpty(ids)) {
			// 归属信息
			ascriptionService
					.remove(new QueryWrapper<PersonAscription>().lambda().in(PersonAscription::getPersonId, ids));
			// 技能学历
			skillEducationService.remove(
					new QueryWrapper<PersonSkillEducation>().lambda().in(PersonSkillEducation::getPersonId, ids));
			// 资质信息
			qualificationService.remove(
					new QueryWrapper<PersonQualifications>().lambda().in(PersonQualifications::getPersonId, ids));
			// 合同信息
			contractService.remove(new QueryWrapper<PersonContract>().lambda().in(PersonContract::getPersonId, ids));
			// 体检信息
			examinnationService
					.remove(new QueryWrapper<PersonExamination>().lambda().in(PersonExamination::getPersonId, ids));
			// 保险信息
			insuranceService.remove(new QueryWrapper<PersonInsurance>().lambda().in(PersonInsurance::getPersonId, ids));
			// 注册信息
			userRegistrationService
					.remove(new LambdaQueryWrapper<UserRegistration>().in(UserRegistration::getPhoneNo, phones));
			// 积分信息
			try {
				integralFeign.deleteByUserIds(ids);
			} catch (Exception e) {
				e.printStackTrace();
				log.error(e.getMessage());
			}
			iPersonService.removeByIds(ids);
			return true;
		} else {
			throw new BaseException(BaseExceptionEnum.PARAMETER_ERROR);
		}
	}

	/**
	 * 根据id查询
	 *
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/{id}", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "根据id查询", notes = "根据id查询")
	public Object selectById(HttpServletRequest request, @PathVariable Long id) {
		return this.getPersonDtoById(id);
	}

	/**
	 * 列表分页查询
	 *
	 * @return
	 */
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "列表分页查询", notes = "列表分页查询")
	public Object listPage(CommonPageableDto pageable, PersonParam personParam) {
		long a = System.currentTimeMillis();
		// 分包商角色
		ReginParams reginParams = getReginInfo();
		if (personParam.getCompanyId() == null) {
			if (this.isFbsRole(reginParams)) {
				personParam.setCompanyId(this.getCompanyId(reginParams));
				personParam.setNoneOrgCode(true);
			}
		}
		long b = System.currentTimeMillis();
		new Thread(new Runnable() {
			@Override
			public void run() {
				SingBadManagementDto singBadManagementDto = new SingBadManagementDto();
				singBadManagementDto.setNature("一类违章");
				singBadManagementDto.setId(1L);
				try {
					ruleTrigger.publish(singBadManagementDto, "施工安全预控/award", new String[0]);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}).start();

//		ResponseModel<Object> reponse = KnowledgeBaseFeign.getDocListByCategoryId(false,
//				1356609229319413761L, 0, 99, "electrical_engineering");
//		Object obj = reponse.getResult();
		// List<Map<String,Object>> list = (List<Map<String, Object>>) obj;

		Object result = iPersonService.pageInfo(personParam, pageable);
		long c = System.currentTimeMillis();
		System.out.println("1:" + (b - a));
		System.out.println("2:" + (c - b));
		return result;
	}

	/**
	 * 查询所有安全员
	 *
	 * @return
	 */
	@RequestMapping(value = "/securityPerson/list", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "查询所有安全员", notes = "查询所有安全员")
	public List<Person> listAllSecurityPerson(Long projectId) {
		// Person person = getPerson();
		return iPersonService.listAllSecurityPerson(projectId);
	}

	/**
	 * 查询所有技术员
	 *
	 * @return
	 */
	@RequestMapping(value = "/technicianPerson/list", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "查询所有技术员", notes = "查询所有技术员")
	public List<Person> listAllTechnicianPerson(Long projectId) {
		// Person person = getPerson();
		return iPersonService.listAllTechnicianPerson(projectId);
	}

	/**
	 * 人员二维码
	 *
	 * @return
	 */
	@RequestMapping(value = "/personQrCode", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "人员二维码", notes = "人员二维码")
	public void personQrCode(HttpServletResponse response, @RequestParam(required = true) Long personId,
			@RequestParam(value = "type", required = false, defaultValue = "png") String type) {
		Person person = iPersonService.getById(personId);
		if (person != null) {
			String fileName = System.currentTimeMillis() + "_" + personId;
			String smallProToken = smallProService.getSmallProToken();
			String scene = personId.toString();
			String page = SmallProPageEnum.personDetail.getPath();
			iPersonService.getQrCodeColorByPersonId(personId);
			JSONObject color = iPersonService.getQrCodeColorByPersonId(personId);
			smallProService.getSmallProQrCodeResponse(smallProToken, scene, page, 280L, false, color, false, response,
					fileName, type);
		} else {
			throw new BaseException("该人员不存在");
		}
	}

	/**
	 * 离职
	 *
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/departure/{id}", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "离职", notes = "离职")
	public Object departureByPersonId(@PathVariable Long id) {
		iPersonService.departureByPersonId(id);
		return true;
	}

	/**
	 * 导出简历
	 *
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/resume/{id}", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "导出简历", notes = "导出简历")
	public synchronized void resume(HttpServletRequest request, HttpServletResponse response, @PathVariable Long id) {
		try {
			PersonDto person = this.getPersonDtoById(id);
			WordTemplateUtils instance = WordTemplateUtils.getInstance();

			if (person.getHeadPhoto() != null) {
				person.setHeadPhoto(fileService.getImageBase64(person.getHeadPhoto()));
			}
			if (person.getFrontCertificatePhoto() != null) {
				person.setFrontCertificatePhoto(fileService.getImageBase64(person.getFrontCertificatePhoto()));
			}
			if (person.getBackCertificatePhoto() != null) {
				person.setBackCertificatePhoto(fileService.getImageBase64(person.getBackCertificatePhoto()));
			}
			// 资质图片转换
			List<PersonQualifications> qualifications = person.getPersonQualifications();
			if (qualifications != null && !qualifications.isEmpty()) {
				qualifications.forEach(q -> {
					// 附件
					List<PersonQualificationsAttachment> attachment = q.getAttachment();
					if (attachment != null && !attachment.isEmpty()) {
						attachment.forEach(a -> {
							// 附件地址
							String path = a.getAttachment();
							if (path != null) {
								a.setAttachment(fileService.getImageBase64(path));
							}
						});
					}
				});
			}
			// 合同图片转换
			PersonContract contract = person.getPersonContract();
			if (contract != null) {
				List<PersonContractAttachment> attachment = contract.getAttachment();
				if (attachment != null && !attachment.isEmpty()) {
					attachment.forEach(a -> {
						String path = a.getAttachment();
						if (path != null) {
							a.setAttachment(fileService.getImageBase64(path));
						}
					});
				}
			}
			// 保险信息图片转换
			PersonInsurance insurance = person.getPersonInsurance();
			if (insurance != null) {
				List<PersonInsuranceAttachment> attachment = insurance.getAttachment();
				if (attachment != null && !attachment.isEmpty()) {
					attachment.forEach(a -> {
						String path = a.getAttachment();
						if (path != null) {
							a.setAttachment(fileService.getImageBase64(path));
						}
					});
				}
			}
			// 体检信息图片转换
			PersonExamination examination = person.getPersonExamination();
			if (examination != null) {
				List<PersonExaminationAttachment> attachment = examination.getAttachment();
				if (attachment != null && !attachment.isEmpty()) {
					attachment.forEach(a -> {
						String path = a.getAttachment();
						if (path != null) {
							a.setAttachment(fileService.getImageBase64(path));
						}
					});
				}
			}
			Date birthday = person.getBirthday();
			Map<String, Object> map = WordTemplateUtils.beanToMap(person);

			// 获取人员二维码
			Long personId = person.getId();
			String fileName = String.valueOf(personId);
			String smallProToken = smallProService.getSmallProToken();
			String scene = "personId=" + personId;
			String page = SmallProPageEnum.personDetail.getPath();
			JSONObject color = iPersonService.getQrCodeColorByPersonId(personId);
			page = "";
			byte[] qrCode = smallProService.getSmallProQrCodeByte(smallProToken, scene, page, 1280L, false, color,
					false);
			BASE64Encoder encoder = new BASE64Encoder();

			map.put("personQrCode", encoder.encode(qrCode));

			instance.exportMillCertificateWord(request, response, map, person.getName(),
					WordTemplateTypeEum.resume.getTemplateFile());

		} catch (Exception e) {
			e.printStackTrace();
			throw new BaseException("用户信息不完整，无法导出简历");
		}
	}

	/**
	 * 民族下拉框
	 *
	 * @return
	 */
	@RequestMapping(value = "/nation", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "民族下拉框", notes = "民族下拉框")
	public Object nationSelect() {
		return iPersonService.nationSelect();
	}

	/**
	 * 分包商-人树查询（技术库用）
	 *
	 * @return
	 */
	@RequestMapping(value = "/tree", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "分包商-人树查询", notes = "分包商-人树查询")
	public Object tree() {
		// Map<String, Object> map = new HashMap<String, Object>();
		// map.put("name", "江西电建");
		// map.put("type", "group");
		List<Map<String, Object>> companyList = new ArrayList<Map<String, Object>>();
		// map.put("children", companyList);
		List<Company> clist = companyService.list();
		for (Company company : clist) {
			Map<String, Object> cmap = new HashMap<String, Object>();
			cmap.put("name", company.getName());
			cmap.put("type", "group");
			cmap.put("id", company.getId());
			List<Map<String, Object>> personList = new ArrayList<Map<String, Object>>();
			cmap.put("children", personList);
			companyList.add(cmap);
			List<PersonAscription> personAscriptionList = ascriptionService.list(
					new LambdaQueryWrapper<PersonAscription>().eq(PersonAscription::getCompanyId, company.getId()));
			Set<Long> personIds = personAscriptionList.stream().map(p -> p.getPersonId()).collect(Collectors.toSet());
			if (!personIds.isEmpty()) {
				List<Person> pList = iPersonService.list(new LambdaQueryWrapper<Person>().in(Person::getId, personIds));
				for (Person person : pList) {
					Map<String, Object> pmap = new HashMap<String, Object>();
					pmap.put("name", person.getName());
					pmap.put("type", "user");
					pmap.put("id", person.getId());
					personList.add(pmap);
				}
			}

		}
		return companyList;
	}

	/**
	 * 人列表名称搜索（技术库用）
	 *
	 * @return
	 */
	@RequestMapping(value = "/search", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "人列表名称搜索", notes = "人列表名称搜索")
	public Object search(String name) {
		List<Map<String, Object>> personList = new ArrayList<Map<String, Object>>();
		List<PersonAscription> personAscriptionList = ascriptionService
				.list(new LambdaQueryWrapper<PersonAscription>());
		Set<Long> personIds = personAscriptionList.stream().map(p -> p.getPersonId()).collect(Collectors.toSet());
		if (!personIds.isEmpty()) {
			LambdaQueryWrapper<Person> wapper = new LambdaQueryWrapper<Person>();
			wapper.in(Person::getId, personIds);
			if (name != null) {
				wapper.like(Person::getName, name);
			}
			List<Person> pList = iPersonService.list(wapper);
			for (Person person : pList) {
				Map<String, Object> pmap = new HashMap<String, Object>();
				pmap.put("name", person.getName());
				pmap.put("type", "user");
				pmap.put("id", person.getId());
				personList.add(pmap);
			}
		}
		return personList;
	}

	/**
	 * 入职
	 *
	 * @return
	 */
	@RequestMapping(value = "/inOccupation", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "入职", notes = "入职")
	public Object inOccupation(PersonAccount personAccount) {
		setPlatFormAccess();
		iPersonService.inOccupation(personAccount);
		return true;
	}

	/**
	 * 离职
	 *
	 * @return
	 */
	@RequestMapping(value = "/outOccupation", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "离职", notes = "离职")
	public Object outOccupation(OutOccupationDto outOccupationDto) {
		Long userId = outOccupationDto.getUserId();
		Person person = iPersonService.getOne(new LambdaQueryWrapper<Person>().eq(Person::getUserId, userId));
		if (person == null) {
			throw new BaseException("用户不存在,请检查是否与平台同步!");
		}
		PersonAscription personAscription = iPersonAscriptionService
				.getOne(new LambdaQueryWrapper<PersonAscription>().eq(PersonAscription::getPersonId, person.getId()));
		if (personAscription != null) {
			Long projectId = personAscription.getProjectId();
			if (projectId != null) {
				Project project = projectService.getById(projectId);
				throw new BaseException("您已经加入到" + (project != null ? project.getName() : "已被删除的") + "项目中,请先离岗");
			}
		}
		setPlatFormAccess();
		FeignClientResult<AgencyUserModel> agencyUserModelFeignClientResult = Privilege.agencyUserClient
				.queryByUserId(String.valueOf(outOccupationDto.getUserId()));
		AgencyUserModel userModel = agencyUserModelFeignClientResult.getResult();
		Map<Long, List<Long>> maps = new HashMap<>();
		Map<Long, List<DepartmentModel>> depts = new HashMap<>();
		userModel.setOrgRoleSeqs(maps);
		userModel.setCompanyDepartments(depts);
		userModel.setLockStatus("LOCK");
		FeignClientResult<AgencyUserModel> update = Privilege.agencyUserClient.update(userModel,
				String.valueOf(userId));
		int status = update.getStatus();
		if (status == 200) {
			// sequenceNbr代表我们系统的userId
			Long sequenceNbr = update.getResult().getSequenceNbr();
			if (sequenceNbr != null) {
				if (personAscription != null) {
					iPersonAscriptionService.update(null,
							Wrappers.<PersonAscription>lambdaUpdate().set(PersonAscription::getCompanyId, null)
									.set(PersonAscription::getPostName, null)
									.set(PersonAscription::getDepartmentId, null)
									.eq(PersonAscription::getId, personAscription.getId()));
				}
				// 当前合同作废
				PersonContract contract = new PersonContract();
				contract.setUseful(ContractUsefulEum.作废.getValue());
				contract.setDepartureTime(new Date());
				contractService.update(contract,
						new LambdaQueryWrapper<PersonContract>().eq(PersonContract::getPersonId, sequenceNbr)
								.eq(PersonContract::getUseful, ContractUsefulEum.生效.getValue()));

				// 资质信息
				List<PersonQualifications> qList = qualificationService
						.list(new LambdaQueryWrapper<PersonQualifications>().eq(PersonQualifications::getPersonId,
								person.getId()));
				List<Long> qidList = qList.stream().map(i -> i.getId()).collect(Collectors.toList());
				if (!qidList.isEmpty()) {
					qualificAttachService.remove(new LambdaQueryWrapper<PersonQualificationsAttachment>()
							.in(PersonQualificationsAttachment::getPersonQualificationsId, qidList));
				}
				// 体检信息
				List<PersonExamination> eList = examinnationService.list(
						new LambdaQueryWrapper<PersonExamination>().eq(PersonExamination::getPersonId, person.getId()));
				List<Long> eidList = eList.stream().map(i -> i.getId()).collect(Collectors.toList());
				if (!eidList.isEmpty()) {
					examinatiAttachService.remove(new LambdaQueryWrapper<PersonExaminationAttachment>()
							.in(PersonExaminationAttachment::getPersonExaminationId, eidList));
				}
				// 保险信息
				List<PersonInsurance> iList = insuranceService.list(
						new LambdaQueryWrapper<PersonInsurance>().eq(PersonInsurance::getPersonId, person.getId()));
				List<Long> iidList = iList.stream().map(i -> i.getId()).collect(Collectors.toList());
				if (!iidList.isEmpty()) {
					insuranceAttachService.remove(new LambdaQueryWrapper<PersonInsuranceAttachment>()
							.in(PersonInsuranceAttachment::getPersonInsuranceId, iidList));
				}
			}

		}
//		try {
//			FeignClientResult<List<String>> result= Privilege.agencyUserClient.lockUsers(outOccupationDto.getUserId().toString());
//		} catch (Exception e) {
//			throw new BaseException(e.getMessage());
//		}
		return true;
	}

	/**
	 * 根据分包商查询部门 （查询人员 分两步 写成2个接口的原因是平台调用的接口是两个）
	 *
	 * @return
	 */
	@RequestMapping(value = "/deptQuery", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "根据分包商查询部门", notes = "根据分包商查询部门")
	public Object deptQuery(Long companyId, String roleName, Long projectId) {
		List<String> roleNames = new ArrayList<>();
		if (StringUtil.isNotEmpty(roleName)) {
			String[] split = roleName.split(",");
			for (String s : split) {
				roleNames.add(s);
			}
		}
		setPlatFormAccess();

		Map<String, Object> map = new HashMap<>();
//		// 根据分包商查询人员
//		List<AgencyUserModel> queryUser = (List<AgencyUserModel>) redisUtil.get(Constant.COMPANY_LIST + companyId);
//		if (queryUser == null) {
//			FeignClientResult<List<AgencyUserModel>> companyList = Privilege.agencyUserClient
//					.queryByCompanyId(companyId, null, null, true);
//			queryUser = companyList.getResult();
//			redisUtil.set(Constant.COMPANY_LIST + companyId, queryUser);
//		}
//		Set<Long> companyUserIds = new HashSet<>();
//		
//		// 将人员数据组装
//		for (AgencyUserModel agencyUserModel : queryUser) {
//			Map<Long, List<RoleModel>> orgRoles = agencyUserModel.getOrgRoles();
//			if (StringUtil.isNotEmpty(orgRoles)) {
//				for (Map.Entry<Long, List<RoleModel>> m : orgRoles.entrySet()) {
//					Long key = m.getKey();
//					List<RoleModel> value = m.getValue();
//					for (RoleModel roleModel : value) {
//						// 过滤到当前部门的 否则会查询到子部门
//						if (key.equals(companyId)) {
//							for (String s : roleNames) {
//								if (null == roleNames) {
//									companyUserIds.add(agencyUserModel.getSequenceNbr());
//									continue;
//								}
//								if (roleModel.getRoleName().equals(s)) {
//									companyUserIds.add(agencyUserModel.getSequenceNbr());
//								}
//							}
//						}
//					}
//				}
//			}
//		}
//		// 获取部门的人员信息
//		List<PersonVo> companyPersonVoList = new ArrayList<>();
//		if (StringUtil.isNotEmpty(companyUserIds)) {
//			Collection<Person> companyUser = iPersonService.listByIds(companyUserIds);
//			if (StringUtil.isNotEmpty(companyUser)) {
//				for (Person person : companyUser) {
//					List<PersonAscription> isExit = getPersonAscriptions(projectId, person);
//					if (StringUtil.isNotEmpty(isExit)) {
//						PersonVo personVo = getCompanyPersonVo(person);
//						companyPersonVoList.add(personVo);
//					}
//				}
//			}
//		}
		map.put("companyPersonVoList", new ArrayList<>());
		Set<String> ids = new HashSet<>();
		List<RoleModel> roleModels = (List<RoleModel>) redisUtil.get(Constant.ROLE_LIST);
		if (roleModels == null) {
			FeignClientResult<List<RoleModel>> roles = Privilege.roleClient.queryRoleList(null, null);
			roleModels = roles.getResult();
			redisUtil.set(Constant.ROLE_LIST, roleModels);
		}
		if (StringUtil.isNotEmpty(roleNames)) {
			if (StringUtil.isNotEmpty(roleModels)) {
				roleModels.forEach(role -> {
					if (roleNames.contains(role.getRoleName())) {
						ids.add(String.valueOf(role.getSequenceNbr()));
					}
				});
			}
		} else {
			if (StringUtil.isNotEmpty(roleModels)) {
				roleModels.forEach(role -> ids.add(String.valueOf(role.getSequenceNbr())));
			}
		}
		List<TeamVo> teamVos = new ArrayList<>();
		CompanyModel companyModel = (CompanyModel) redisUtil.get(Constant.COMPANY_CHILDRES_LIST + companyId);
		if (companyModel == null) {
			FeignClientResult<CompanyModel> companyChildres = Privilege.departmentClient
					.queryByCompanyChilds(companyId);
			companyModel = companyChildres.getResult();
			redisUtil.set(Constant.COMPANY_CHILDRES_LIST + companyId, companyModel);
		}
		Collection dept = null;
		if (companyModel != null) {
			dept = companyModel.getChildren();
		}
		if (dept != null) {
			List<Map> children = (List<Map>) dept;
			// List<Map> children=new ArrayList<>();
			for (Map child : children) {
				DepartmentModel departmentModel = JSONObject.parseObject(JSONObject.toJSONString(child),
						DepartmentModel.class);
				List<PersonVo> personVoList = new ArrayList<>();
				TeamVo teamVo = new TeamVo();
				String departmentName = departmentModel.getDepartmentName();
				Long sequenceNbr = departmentModel.getSequenceNbr();
				String orgCode = departmentModel.getOrgCode();
				teamVo.setId(sequenceNbr);
				teamVo.setName(departmentName);
				teamVo.setOrgCode(orgCode);
				List<AgencyUserModel> userListWithChildren = departmentModel.getUserListWithChildren();
				if (StringUtil.isNotEmpty(userListWithChildren)) {
					List<Long> userIds = userListWithChildren.stream().map(m -> m.getSequenceNbr())
							.collect(Collectors.toList());
					personVoList = iPersonAscriptionService.getUsers(ids, userIds, projectId);
				}
				teamVo.setPersonVo(personVoList);
				teamVo.setNumber(personVoList.size());
				teamVos.add(teamVo);
			}
		}
		if (StringUtil.isNotEmpty(teamVos)) {
			List<CompanyAcount> companyAcountList = iCompanyAcountService.list();
			teamVos.forEach(teamVo -> {
				String teamName = teamVo.getName();
				CompanyAcount companyAcount = null;
				if (companyAcountList != null && companyAcountList.size() > 0) {
					List<CompanyAcount> list = companyAcountList.stream()
							.filter(company -> companyId.equals(company.getCompanyId())
									&& teamName.equals(company.getTeamName()))
							.collect(Collectors.toList());
					if (list != null && list.size() == 1) {
						companyAcount = list.get(0);
					}
				}
				if (companyAcount != null) {
					teamVo.setAcountNumber(companyAcount.getAcountNumber());
					teamVo.setBankName(companyAcount.getBankName());
					teamVo.setRemark(companyAcount.getRemark());
				}
			});
		}
		map.put("teamPersonVoList", teamVos);
		return map;
	}

	private List<PersonVo> getUserList(Set<String> ids, Long deptId, Long projectId) {
		// 查询部门下的所有人员数量 暂时不确定是否包含当前部门
		FeignClientResult<Collection<DepartmentModel>> collectionFeignClientResult1 = Privilege.departmentClient
				.querySubAgencyTreeWithUser(deptId);
		List<DepartmentModel> departmentModels = (List<DepartmentModel>) collectionFeignClientResult1.getResult();
		List<AgencyUserModel> userList = new ArrayList<>();
		if (StringUtil.isNotEmpty(departmentModels)) {
			List<AgencyUserModel> userListWithChildren = departmentModels.get(0).getUserListWithChildren();
			userList.addAll(userListWithChildren);
		}
		// 得到的用户
		List<Long> userListIds = userList.stream().map(user -> user.getSequenceNbr()).collect(Collectors.toList());
		List<PersonVo> users;
		if (StringUtil.isNotEmpty(userListIds)) {
			return iPersonAscriptionService.getUsers(ids, userListIds, projectId);
		} else {
			return null;
		}

	}

	/**
	 * 根据部门查询班组
	 *
	 * @return
	 */
	@RequestMapping(value = "/teamQuery", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "根据部门查询班组", notes = "根据部门查询班组")
	public Object teamQuery(Long deptId, String roleName, Long projectId, boolean fbs) {
		setPlatFormAccess();
		List<String> roleNames = new ArrayList<>();
		if (StringUtils.isNotEmpty(roleName)) {
			String[] split = roleName.split(",");
			for (String s : split) {
				roleNames.add(s);
			}
		}
		// 前端传递过来的是平台的roleName
		Set<String> ids = new HashSet<>();
		if (StringUtil.isNotEmpty(roleNames)) {
			for (String name : roleNames) {
				getRoleIdByName(ids, name);
			}
		} else {
			getRoleIdByName(ids, null);
		}
		String roleIds = getRoleIds(ids);
		Map<String, Object> map = new HashMap<>();
		// 查询部门的人
		FeignClientResult<List<AgencyUserModel>> queryByDepartmentData = Privilege.agencyUserClient
				.queryByDeptRoles(deptId, roleIds, null, null);
		List<AgencyUserModel> queryByDepartmentUser = queryByDepartmentData.getResult();
		Set<Long> companyUserIds = new HashSet<>();
		// 过滤部门的人
		for (AgencyUserModel agencyUserModel : queryByDepartmentUser) {
			companyUserIds.add(agencyUserModel.getSequenceNbr());
		}
		List<PersonVo> companyPersonVoList = new ArrayList<>();
		if (StringUtil.isNotEmpty(companyUserIds)) {
			Collection<Person> companyUser = iPersonService.listByIds(companyUserIds);
			if (StringUtil.isNotEmpty(companyUser)) {
				for (Person person : companyUser) {
					List<PersonAscription> isExit = getPersonAscriptions(projectId, person);
					if (StringUtil.isNotEmpty(isExit)) {
						PersonVo personVo = getCompanyPersonVo(person);
						companyPersonVoList.add(personVo);
					}
				}
			}
		}
		map.put("companyPersonVoList", companyPersonVoList);
		// 查询班组的人
		FeignClientResult<Collection<DepartmentModel>> collectionFeignClientResult = Privilege.departmentClient
				.querySubAgencyTree(deptId);
		Collection<DepartmentModel> result = collectionFeignClientResult.getResult();
		List<TeamVo> teamVos = new ArrayList<>();
		if (StringUtil.isNotEmpty(result)) {
			result.forEach(r -> {
				if (!fbs && "fbs".equals(r.getLevel())) {
				} else {
					List<PersonVo> personVoList = getUserList(ids, r.getSequenceNbr(), projectId);
					TeamVo teamVo = new TeamVo();
					String departmentName = r.getDepartmentName();
					teamVo.setId(r.getSequenceNbr());
					teamVo.setName(departmentName);
					if (StringUtil.isNotEmpty(personVoList)) {
						teamVo.setNumber(personVoList.size());
					} else {
						teamVo.setNumber(0);
					}
					teamVo.setOrgCode(r.getOrgCode());
					teamVo.setPersonVo(personVoList);
					teamVos.add(teamVo);
				}

			});
		}
		map.put("teamPersonVoList", teamVos);
		return map;
	}

	/**
	 * 根据名称获取roleId
	 *
	 * @param ids
	 * @param name
	 */
	private void getRoleIdByName(Set<String> ids, String name) {
//		if (name == null) {
//			return;
//		}
		FeignClientResult<List<RoleModel>> listFeignClientResult = Privilege.roleClient.queryRoleList(name, null);
		List<RoleModel> roleModels = listFeignClientResult.getResult();
		if (StringUtil.isNotEmpty(roleModels)) {
			roleModels.forEach(role -> {
				if (name == null) {
					ids.add(String.valueOf(role.getSequenceNbr()));
				} else {
					if (name.equals(role.getRoleName())) {
						ids.add(String.valueOf(role.getSequenceNbr()));
					}
				}
			});
		}
	}

	/**
	 * 查询人员-通过平台
	 *
	 * @return
	 */
	@RequestMapping(value = "/teamPersonSearch", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "查询人员-通过平台", notes = "查询人员-通过平台")
	public Object teamQuery(TeamPersonSearchDto teamPersonSearchDto, CommonPageableDto pageable) {
		setPlatFormAccess();
		List<String> ids = new ArrayList<>();
		if (pageable.getIsAll() == 1) {
			pageable.setPageNumber(0);
			pageable.setPageSize(Integer.MAX_VALUE);
		}
		Page<Person> page = new Page<>(pageable.getPageNumber(), pageable.getPageSize());
		List<Long> userIds = new ArrayList<>();
		IPage<PersonVo> personVos = null;
		LambdaQueryWrapper<PersonAscription> personAscriptionLambdaQueryWrapper = new LambdaQueryWrapper<>();
		personAscriptionLambdaQueryWrapper.select(PersonAscription::getPersonId);
		if (StringUtil.isNotEmpty(teamPersonSearchDto.getProjectId())) {
			personAscriptionLambdaQueryWrapper.eq(PersonAscription::getProjectId, teamPersonSearchDto.getProjectId());
		}
		if (StringUtil.isNotEmpty(teamPersonSearchDto.getCompanyId())) {
			personAscriptionLambdaQueryWrapper.eq(PersonAscription::getCompanyId, teamPersonSearchDto.getCompanyId());

			// 违章人员列表搜索 如果传过来两个roleName,请求平台接口会返回空,根据公司是否分包商进行区分后
			Company company = companyService.getById(teamPersonSearchDto.getCompanyId());
			// 技术交底安全员的角色进行处理
			if (StringUtil.isNotEmpty(teamPersonSearchDto.getRoleName())
					&& teamPersonSearchDto.getRoleName().contains("security")) {
				if (company.getTypeKey().equals(TypeKeyEnum.JXDJ.getLongType() + "")) {
					teamPersonSearchDto.setRoleName("security");
				} else if (company.getTypeKey().equals(TypeKeyEnum.COMPANY.getLongType() + "")) {
					teamPersonSearchDto.setRoleName(RoleEnum.FBS_SECURITY.getValue());
				}
			}
			// 三交三查技术员的角色进行处理
			if (StringUtil.isNotEmpty(teamPersonSearchDto.getRoleName())
					&& teamPersonSearchDto.getRoleName().contains("technician")) {
				if (company.getTypeKey().equals(TypeKeyEnum.JXDJ.getLongType() + "")) {
					teamPersonSearchDto.setRoleName("technician");
				} else if (company.getTypeKey().equals(TypeKeyEnum.COMPANY.getLongType() + "")) {
					teamPersonSearchDto.setRoleName(RoleEnum.FBS_TECHNICIAN.getValue());
				}
			}
			// 三交三查工程人员的角色进行处理
			if (StringUtil.isNotEmpty(teamPersonSearchDto.getRoleName())
					&& teamPersonSearchDto.getRoleName().contains("project")) {
				if (company.getTypeKey().equals(TypeKeyEnum.JXDJ.getLongType() + "")) {
					teamPersonSearchDto.setRoleName("project");
				} else if (company.getTypeKey().equals(TypeKeyEnum.COMPANY.getLongType() + "")) {
					teamPersonSearchDto.setRoleName(RoleEnum.FBS_DIRECTOR.getValue());
				}
			}
		}

		List<PersonAscription> personAscriptionList = iPersonAscriptionService.list(personAscriptionLambdaQueryWrapper);
		if (StringUtil.isNotEmpty(personAscriptionList)) {
			personAscriptionList.forEach(p -> userIds.add(p.getPersonId()));
			LambdaQueryWrapper<Person> personLambdaQueryWrapper = new LambdaQueryWrapper<>();
			personLambdaQueryWrapper.in(Person::getId, userIds);
			if (StringUtils.isNotEmpty(teamPersonSearchDto.getUserName())) {
				personLambdaQueryWrapper.like(Person::getName, teamPersonSearchDto.getUserName());
			}

			if (StringUtils.isNotEmpty(teamPersonSearchDto.getRoleName())) {
				personLambdaQueryWrapper.apply("FIND_IN_SET({0},role_key)", teamPersonSearchDto.getRoleName());
			}

			IPage<Person> personPageData = iPersonService.page(page, personLambdaQueryWrapper);

			List<Person> records = personPageData.getRecords();
			List<PersonVo> personVoList = new ArrayList<>();
			for (Person person : records) {
				PersonVo personVo = new PersonVo();
				BeanUtils.copyProperties(person, personVo);
				personVo.setJxdj(person.getIsJxdj() == 1L);
				if (person.getQualified() != null) {
					if (personVo.getQualified()) {
						personVo.setQualifiedName("已通过");
					} else {
						personVo.setQualifiedName("未通过");
					}
				} else {
					personVo.setQualifiedName("未通过");
				}
				List<PersonAscription> list = iPersonAscriptionService.list(
						new LambdaQueryWrapper<PersonAscription>().eq(PersonAscription::getPersonId, personVo.getId()));
				if (StringUtil.isNotEmpty(list)) {
					PersonAscription personAscription = list.get(0);
					if (personAscription != null) {
						Long companyId = personAscription.getCompanyId();
						if (companyId != null) {
							Company company = iCompanyService.getById(companyId);
							personVo.setCompanyName(company.getName());
						}
						personVo.setPostName(personAscription.getPostName());
					}
					personVo.setStatusLabel("在岗");
				} else {
					personVo.setStatusLabel("不在岗");
				}
				personVoList.add(personVo);
			}
			personVos = new Page<>();
			personVos.setRecords(personVoList);
			personVos.setTotal(personVoList.size());
			personVos.setSize(pageable.getPageSize());
			personVos.setCurrent(pageable.getPageNumber());
		}
		return personVos;
	}

	/**
	 * 拷贝获取人员数据
	 *
	 * @param person
	 * @return
	 */
	private PersonVo getCompanyPersonVo(Person person) {
		PersonVo personVo = new PersonVo();
		BeanUtils.copyProperties(person, personVo);
		personVo.setJxdj(person.getIsJxdj() == 1L);
		if (personVo.getHeadPhoto() != null) {
			personVo.setHeadPhoto(fileServerUrl + personVo.getHeadPhoto());
		}
		if (personVo.getQualified() != null) {
			if (personVo.getQualified()) {
				personVo.setQualifiedName("已通过");
			} else {
				personVo.setQualifiedName("未通过");
			}
		}
		List<PersonAscription> list = iPersonAscriptionService
				.list(new LambdaQueryWrapper<PersonAscription>().eq(PersonAscription::getPersonId, personVo.getId()));
		if (StringUtil.isNotEmpty(list)) {
			PersonAscription personAscription = list.get(0);
			if (personAscription != null) {
				personVo.setPostName(personAscription.getPostName());
			}
			Long queryCompanyId = personAscription.getCompanyId();
			if (queryCompanyId != null) {
				Company company = iCompanyService.getById(queryCompanyId);
				personVo.setCompanyName(company.getName());
			}
			personVo.setPostName(personAscription.getPostName());
			personVo.setStatusLabel("在岗");
		} else {
			personVo.setStatusLabel("不在岗");
		}
		return personVo;
	}

	/**
	 * 根据ids转换字符串
	 *
	 * @param ids
	 * @return
	 */
	private String getRoleIds(Set<String> ids) {
		String roleIds = null;
		if (StringUtil.isNotEmpty(ids)) {
			roleIds = "";
			for (String id : ids) {
				roleIds += id + ",";
			}
			roleIds = roleIds.substring(0, roleIds.length() - 1);
		}
		return roleIds;
	}

	/**
	 * 根据项目id和人员信息返回关系表对象
	 *
	 * @param person
	 * @return
	 */
	private List<PersonAscription> getPersonAscriptions(Long projectId, Person person) {
		Long personId = person.getId();
		LambdaQueryWrapper<PersonAscription> personAscriptionLambdaQueryWrapper = new LambdaQueryWrapper<>();
		personAscriptionLambdaQueryWrapper.eq(PersonAscription::getPersonId, personId);
		if (projectId != null) {
			personAscriptionLambdaQueryWrapper.eq(PersonAscription::getProjectId, projectId);
		}
		return iPersonAscriptionService.list(personAscriptionLambdaQueryWrapper);
	}

	/**
	 * 保存或者更新人员
	 *
	 * @param personDto
	 * @return
	 */
	private Person saveOrUpdatePerson(PersonDto personDto) {
		if (StringUtil.isNotEmpty(personDto.getIdNumber()) && personDto.getId() == null) {
			int idCount = iPersonService
					.count(new LambdaQueryWrapper<Person>().eq(Person::getIdNumber, personDto.getIdNumber()));
			if (idCount > 1) {
				throw new BaseException("无法编辑，人员身份证号重复");
			}
		}
		Person person = new Person();
		try {
			PropertyUtils.copyProperties(person, personDto);
		} catch (Exception e) {
			e.printStackTrace();
		}
//		// 0红 1黄 2绿
//		if (person.getQualified() == null) {
//			person.setColor(2L);
//		} else {
//			if (person.getQualified()) {
//				person.setColor(2L);
//			} else {
//				person.setColor(0L);
//			}
//		}
//		boolean saveFlag = personDto.getId() == null;

		Long userId = person.getUserId();
		if (userId != null) {
			Person one = iPersonService.getOne(new QueryWrapper<Person>().lambda().eq(Person::getUserId, userId));
			// 修改用户
			if (one != null && person.getId() != null && one.getId().longValue() != person.getId().longValue()) {
				throw new BaseException("该平台账号已被绑定");
			}
			// 新增用户
			if (one != null && person.getId() == null) {
				throw new BaseException("该平台账号已被绑定");
			}
		}

		Person oldPerson = iPersonService.getById(personDto.getId());
		// 账户信息
		PersonAccount personAccount = personDto.getPersonAccount();
		// 判断角色是否改变
		if (!oldPerson.getRoles().equals(Arrays.toString(personAccount.getRoleIdList().toArray()))) {
			int count = taskPersonService.count(new LambdaQueryWrapper<TaskPerson>()
					.eq(TaskPerson::getPersonId, oldPerson.getId()).eq(TaskPerson::getReadStatus, 0L));
			if (count > 0) {
				throw new BaseException("存在未处理的任务,无法进行角色变更");
			}
		}

		// 基本信息
		if (person.getHeadPhoto() != null) {
			person.setHeadPhoto(person.getHeadPhoto().replace(fileServerUrl, ""));
		}
		if (person.getBackCertificatePhoto() != null) {
			person.setBackCertificatePhoto(person.getBackCertificatePhoto().replace(fileServerUrl, ""));
		}
		if (person.getFrontCertificatePhoto() != null) {
			person.setFrontCertificatePhoto(person.getFrontCertificatePhoto().replace(fileServerUrl, ""));
		}

		iPersonService.saveOrUpdate(person);
		// 如果图片是null 至为null
		iPersonService.updatePhoto(person);
		Long personId = person.getId();

		PersonAscription ascription = personDto.getPersonAscription();
		// 归属信息
		if (ascription != null) {
			ascription.setPersonId(personId);
			if (ascription.getProjectId() != null) {
				ascription.setStatus(AscriptionStatusEum.在岗.getValue());
			} else {
				ascription.setStatus(AscriptionStatusEum.离岗.getValue());
			}
			// 修复bug 把>名称存进去了,导致重复
			if (ascription.getDepartmentName() != null && ascription.getDepartmentName().contains(">")
					&& oldPerson.getIsJxdj() == 1) {
				ascription.setDepartmentName(null);
			}
			ascriptionService.saveOrUpdate(ascription);
		}

		// 账户信息
		// PersonAccount personAccount = personDto.getPersonAccount();
		AgencyUserModel userModel = new AgencyUserModel();
		userModel.setAppCodes(personAccount.getApplicationList());
		Map<Long, List<Long>> map = new HashMap<>();
		map.put(personAccount.getPlatformDepartmentId(), personAccount.getRoleIdList());
		userModel.setOrgRoleSeqs(map);
		userModel.setLockStatus("UNLOCK");
		person.setRoles(Arrays.toString(personAccount.getRoleIdList().toArray()));
		iPersonService.setNewRoleName(person, personAccount.getRoleList());
		person.setDeptType(personAccount.getPlatformDepartmentType());
		iPersonService.updateById(person);

		try {
			platformUtils.setPlatFormAccess();
			FeignClientResult<AgencyUserModel> result = Privilege.agencyUserClient.update(userModel,
					oldPerson.getUserId().toString());
		} catch (Exception e) {
			log.error(e.getMessage());
			throw new BaseException("平台更新账户失败");
		}

		// 如果是江西电建人员不做后面处理
		if (oldPerson != null && oldPerson.getIsJxdj() == TypeKeyEnum.JXDJ.getLongType()) {
			return oldPerson;
		}

		Long companyId = ascription != null ? ascription.getCompanyId() : null;
		if (companyId != null) {
			PersonContract contract = personDto.getPersonContract();
			// 合同信息
			if (contract != null) {
				contract.setPersonId(personId);
				// 合同归属公司
				Long oldContractCompanyId = contract.getContractCompanyId();

				// 公司没变或入职，进行新增/更改合同信息
				if (companyId.equals(oldContractCompanyId) || oldContractCompanyId == null) {
					contract.setUseful(ContractUsefulEum.生效.getValue());
					contract.setContractCompanyId(companyId);
					contractService.saveOrUpdate(contract);
					contractAttachService.saveAttach(contract.getId(), contract.getAttachment());
				} else {
					throw new BaseException("合同的公司名称与所在单位不一致！");
				}

			}
		} else {
			throw new BaseException("请选择所在单位！");
		}

		PersonSkillEducation skillEducation = personDto.getPersonSkillEducation();
		// 技能学历
		if (skillEducation != null) {
			skillEducation.setPersonId(personId);
			skillEducationService.saveOrUpdate(skillEducation);
		}

		qualificationService
				.remove(new LambdaQueryWrapper<PersonQualifications>().eq(PersonQualifications::getPersonId, personId));
		List<PersonQualifications> qualifications = personDto.getPersonQualifications();
		// 资质信息
		if (qualifications != null) {
			qualifications.forEach(q -> {
				q.setPersonId(personId);
				qualificationService.saveOrUpdate(q);
				qualificAttachService.saveAttach(q.getId(), q.getAttachment());
			});
		}

		PersonExamination examination = personDto.getPersonExamination();
		// 体检信息
		if (examination != null) {
			examination.setPersonId(personId);
			examinnationService.saveOrUpdate(examination);
			examinatiAttachService.saveAttach(examination.getId(), examination.getAttachment());
		}

		PersonInsurance insurance = personDto.getPersonInsurance();
		// 保险信息
		if (insurance != null) {
			insurance.setPersonId(personId);
			insuranceService.saveOrUpdate(insurance);
			insuranceAttachService.saveAttach(insurance.getId(), insurance.getAttachment());
		}
		// 如果最新安全考试通过则变为绿码 如果不通过则变为红码
		List<PersonExam> exams = personDto.getPersonExams();
		List<PersonExam> oldExams = iPersonExamService
				.list(new LambdaQueryWrapper<PersonExam>().eq(PersonExam::getPersonId, personId));
		exams.removeAll(oldExams);
		boolean reEduQualified = false;
		if (exams.size() > 0) {
			PersonExam item = exams.get(exams.size() - 1);
			if (item.getType().equals(OfflineExamEnum.THREE_SEC.getLabel())) {
				if (item.getQualified()) {
					person.setColor(SmallProQrColorEum.green.getSqlCode());
				} else {
					person.setColor(SmallProQrColorEum.red.getSqlCode());
				}
			} else if (item.getType().equals(OfflineExamEnum.SEC_RE_TRAIN.getLabel())) {
				if (item.getQualified()) {
					reEduQualified = true;
					person.setColor(SmallProQrColorEum.green.getSqlCode());
				} else {
					person.setColor(SmallProQrColorEum.red.getSqlCode());
				}
			}
			person.setQualified(item.getQualified());
			person.setExamineScore(Long.valueOf(item.getScore()));
		}

		iPersonService.saveOrUpdate(person);
		// 更新推送
		if (oldPerson.getColor() != person.getColor()) {
			statisticsService.initWs(oldPerson.getOrgCode(), Constant.WS_REDORGREENCODE);
		}

		// 如果有再教育考试合格使红码变绿 并且有三次以上违章 则修改之前的违章为失效统计违章
		int count = iBadManagementPersonService.count(new LambdaQueryWrapper<BadManagementPerson>()
				.eq(BadManagementPerson::getPersonId, person.getId()).eq(BadManagementPerson::getValid, true));

		if (reEduQualified && SmallProQrColorEum.green.getSqlCode() == person.getColor() && count >= 3) {
			BadManagementPerson badManagementPerson = new BadManagementPerson();
			badManagementPerson.setValid(false);
			iBadManagementPersonService.update(badManagementPerson,
					new LambdaQueryWrapper<BadManagementPerson>().eq(BadManagementPerson::getPersonId, person.getId()));
		}

		// 考试信息
		if (exams != null) {
			exams.forEach(exam -> {
				if ("ThreeLevelSafety".equals(exam.getExamSubjectType())) {
					exam.setExamSubjectType(OfflineExamEnum.THREE_SEC.getType());
				}
				exam.setPersonId(personId);
				iPersonExamService.saveOrUpdate(exam);
			});
		}

		// 同步门禁人脸数据
		Person newPerson = iPersonService.getById(person.getId());
		PersonAscription personAscription = ascriptionService
				.getOne(new LambdaQueryWrapper<PersonAscription>().eq(PersonAscription::getPersonId, person.getId()));
		List<ProjectDevice> list = iProjectDeviceService.list(new LambdaQueryWrapper<ProjectDevice>()
				.eq(ProjectDevice::getProjectId, personAscription.getProjectId()));
		List<String> sessonNames = list.stream().map(ProjectDevice::getNumber).collect(Collectors.toList());
		if (StringUtil.isNotEmpty(sessonNames)) {
			WebSocket.addPerson(newPerson, sessonNames);
		}
		return person;
	}

	/**
	 * 根据id获取人员
	 *
	 * @param id
	 * @return
	 */
	private PersonDto getPersonDtoById(Long id) {
		Person person = iPersonService.getById(id);
		PersonDto personDto = new PersonDto();
		if (person != null) {
			if (person.getSex() != null) {
				person.setSexLabel(SexEum.getLabelByValue(person.getSex()));
			}
			if (person.getIdType() != null) {
				person.setIdTypeLabel(IdTypeEum.getLabelByValue(person.getIdType()));
			}
			String nativePlace = person.getNativePlace();
			if (nativePlace != null) {
				person.setNativePlaceLabel(districtsService.selectLabelByIds(nativePlace.split(",")));
			}
			String employPlaceLabel = person.getEmployPlace();
			if (employPlaceLabel != null) {
				person.setEmployPlaceLabel(districtsService.selectLabelByIds(employPlaceLabel.split(",")));
			}
			BeanUtils.copyProperties(person, personDto);
			personDto.setJxdj(person.getIsJxdj() == 1L);
			personDto.setActiveStatusLabel(PersonActiveStatusEnum
					.getNameByType(personDto.getActiveStatus() != null ? personDto.getActiveStatus().intValue() : 0));
			String filterColum = "person_id";
			PersonAscription ascription = ascriptionService
					.getOne(new QueryWrapper<PersonAscription>().eq(filterColum, id));
			if (ascription != null) {
				String workPlaceKey = ascription.getWorkPlaceKey();
				if (workPlaceKey != null) {
					if ("0".equals(workPlaceKey)) {
						ascription.setWorkPlaceKeyLabel("国内");
					}
					if ("1".equals(workPlaceKey)) {
						ascription.setWorkPlaceKeyLabel("国外");
					}
				}
				Integer status = ascription.getStatus();
				if (status != null) {
					ascription.setStatusLabel(AscriptionStatusEum.getLabelByValue(status));
				} else {
					ascription.setStatus(AscriptionStatusEum.离岗.getValue());
					ascription.setStatusLabel(AscriptionStatusEum.离岗.getLabel());
				}

				Long companyId = ascription.getCompanyId();
				if (companyId != null) {
					Company company = companyService.getById(companyId);
					personDto.setCompany(company);
					ascription.setCompanyName(company != null ? company.getName() : null);
				}
				Long projectId = ascription.getProjectId();
				if (projectId != null) {
					Project project = projectService.getById(projectId);
					personDto.setProject(project);
					ascription.setProjectName(project != null ? project.getName() : null);
				}
				Long departmentId = ascription.getDepartmentId();
				if (departmentId != null) {
//					DepartmentModel department = getDepartment(departmentId);
					if (person.getIsJxdj() == 0) {
						CompanyDepartment companyDepartment = companyDepartmentService.getById(departmentId);
						String departmentName = companyDepartment != null ? companyDepartment.getName() : null;
						ascription.setDepartmentName(departmentName);
					} else {
						StringBuffer sb = new StringBuffer();
						FeignClientResult<Collection<DepartmentModel>> fr = Privilege.departmentClient
								.queryListByChild(departmentId);
						Collection<DepartmentModel> collection = fr.getResult();
						List<DepartmentModel> list = new ArrayList<DepartmentModel>(collection);
						Collections.reverse(list);
						if (!list.isEmpty()) {
							for (DepartmentModel departmentModel : list) {
								sb.append(departmentModel.getDepartmentName()).append(">");
							}
						}
						sb.append(ascription.getDepartmentName());
						ascription.setDepartmentName(sb.toString());
					}
				} else {
					ascription.setDepartmentName(null);
				}
			}

			// 归属信息
			personDto.setPersonAscription(ascription);

			// 技能学历
			PersonSkillEducation skillEducation = skillEducationService
					.getOne(new QueryWrapper<PersonSkillEducation>().eq(filterColum, id));
//            if (skillEducation == null) {
//                skillEducation = new PersonSkillEducation();
//            }
			personDto.setPersonSkillEducation(skillEducation);
			// 资质信息
			List<PersonQualifications> qualifications = qualificationService
					.list(new QueryWrapper<PersonQualifications>().eq(filterColum, id));
			if (qualifications != null) {
				qualifications.forEach(q -> {
					List<PersonQualificationsAttachment> list = qualificAttachService
							.list(new QueryWrapper<PersonQualificationsAttachment>().eq("person_qualifications_id",
									q.getId()));
					q.setAttachment(list);
				});
			}
//            if (qualifications == null) {
//                qualifications = new ArrayList<PersonQualifications>();
//            }
			personDto.setPersonQualifications(qualifications);
			// 合同信息
			PersonContract contract = contractService.getOne(new QueryWrapper<PersonContract>().eq(filterColum, id)
					.eq("useful", ContractUsefulEum.生效.getValue()));
			if (contract != null) {
				String contractTypeKey = contract.getContractTypeKey();
				if (contractTypeKey != null) {
					contract.setContractTypeKeyLabel(ContractTypeEum.getLabelByValue(contractTypeKey));
				}
				String expiryTypeKey = contract.getExpiryTypeKey();
				if (expiryTypeKey != null) {
					contract.setExpiryTypeKeyLabel(ExpiryTypeEum.getLabelByValue(expiryTypeKey));
				}
				List<PersonContractAttachment> list = contractAttachService
						.list(new QueryWrapper<PersonContractAttachment>().eq("person_contract_id", contract.getId()));
				contract.setAttachment(list);
				Long companyId = contract.getContractCompanyId();
				if (companyId != null) {
					Company company = companyService.getById(companyId);
					contract.setContractCompanyName(company != null ? company.getName() : null);
				}
			}
//            if (contract == null) {
//                contract = new PersonContract();
//            }
			personDto.setPersonContract(contract);
			// 体检信息
			PersonExamination examination = examinnationService
					.getOne(new QueryWrapper<PersonExamination>().eq(filterColum, id));
			if (examination != null) {
				String healthStatus = examination.getHealthStatus();
				if (healthStatus != null) {
					examination.setHealthStatusLabel(HealthStatusEum.getLabelByValue(healthStatus));
				}

				List<PersonExaminationAttachment> list = examinatiAttachService
						.list(new QueryWrapper<PersonExaminationAttachment>().eq("person_examination_id",
								examination.getId()));
				examination.setAttachment(list);
			}
//            if (examination == null) {
//                examination = new PersonExamination();
//            }
			personDto.setPersonExamination(examination);
			// 保险信息
			PersonInsurance insurance = insuranceService
					.getOne(new QueryWrapper<PersonInsurance>().eq(filterColum, id));
			if (insurance != null) {
				List<PersonInsuranceAttachment> list = insuranceAttachService.list(
						new QueryWrapper<PersonInsuranceAttachment>().eq("person_insurance_id", insurance.getId()));
				insurance.setAttachment(list);
			}
//            if (insurance == null) {
//                insurance = new PersonInsurance();
//            }
			personDto.setPersonInsurance(insurance);
			// 考试信息
			List<PersonExam> exams = iPersonExamService.list(new QueryWrapper<PersonExam>().eq(filterColum, id));
			personDto.setPersonExams(exams);
			// 调用积分系统 获取个人积分
//			try {
//				ResponseModel<Double> personIntegral = integralFeign.getPersonIntegral(person.getId());
//				if (personIntegral != null && personIntegral.getResult() != null) {
//					Double result = personIntegral.getResult();
//					personDto.setIntegral(result);
//				}
//			} catch (Exception e) {
//				log.error("积分系统 调用失败", e);
//			}
			// 账户信息
			FeignClientResult<AgencyUserModel> result = Privilege.agencyUserClient
					.queryByUserId(person.getUserId().toString());
			if (result == null || result.getResult() == null) {
				throw new BaseException("平台账户不存在！");
			}
			PersonAccount personAccount = new PersonAccount();
			result.getResult().getOrgRoleSeqs().forEach((key, value) -> {
				personAccount.setPlatformDepartmentId(key);
			});
			personAccount.setAccount(person.getAccountName());
			personAccount.setApplicationList(result.getResult().getAppCodes());
			Map<Long, List<Long>> map = result.getResult().getOrgRoleSeqs();
			map.forEach((key, value) -> {
				personAccount.setRoleIdList(value);
			});
			personDto.setPersonAccount(personAccount);
		} else {
			throw new BaseException("用户不存在！");
		}
		return personDto;
	}

	/**
	 * 积分记录
	 *
	 * @param personId
	 * @param pageSize
	 * @param pageNumber
	 * @return
	 */
	@RequestMapping(value = "/integral/page", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "积分记录", notes = "积分记录")
	public Object personIntegralPage(@RequestParam("personId") Long personId,
			@RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
			@RequestParam(value = "pageNumber", defaultValue = "1") Integer pageNumber) {
		ResponseModel<Object> personIntegralPage = integralFeign.getIntegralPage(personId, pageNumber, pageSize);
		Object result = personIntegralPage.getResult();
		return result;
	}

	/**
	 * 判断人员是否可以发起任务
	 *
	 * @return
	 */
	@RequestMapping(value = "/canSendTask/{type}", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "判断人员是否可以发起任务", notes = "判断人员是否可以发起任务")
	public Object canSend(@PathVariable Long type) {
		Person person = iPersonService.getById(getPerson().getId());
		PersonAscription personAscription = iPersonAscriptionService
				.getOne(new LambdaQueryWrapper<PersonAscription>().eq(PersonAscription::getPersonId, person.getId()));
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("result", true);
		if (person.getIsJxdj() != 1L) {
			if (TaskTypeEnum.TASKPAYCHECK.getValue() == type) {
				if (person.getActiveStatus() == null || person.getActiveStatus() != 1L) {
					map.put("result", false);
					map.put("message", "分包商人员未入场，无法发起任务");
					return map;
				}
			} else {
				if (personAscription == null || personAscription.getProjectId() == null) {
					map.put("result", false);
					map.put("message", "分包商人员未上岗，无法发起任务");
					return map;
				}
			}
		} else {
			if (personAscription == null || personAscription.getProjectId() == null) {
				map.put("result", false);
				map.put("message", "江西电建人员未上岗，无法发起任务");
				return map;
			}
		}
		return map;
	}

	/**
	 * 查询时间段内参与考勤的人
	 *
	 * @return
	 */
	@RequestMapping(value = "/period", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = " 查询时间段内参与考勤的人", notes = "查询时间段内参与考勤的人")
	public Object period(CommonPageableDto pageable, PersonParam personParam,
			@DateTimeFormat(pattern = "yyyy-MM-dd") Date payStartTime,
			@DateTimeFormat(pattern = "yyyy-MM-dd") Date payEndTime, Long operType, HttpServletResponse response) {

		IPage<PersonVo> page = new Page<PersonVo>();
		if (personParam.getCompanyId() == null || personParam.getProjectId() == null || payStartTime == null
				|| payEndTime == null) {

		} else {
			page = iPersonService.period(pageable, personParam, payStartTime, payEndTime);
		}
		if (operType == 1) {
			String fileName = UUID.randomUUID().toString() + ".xls";
			List<PersonVo> excelList = page.getRecords();
			List<PersonSalaryExcelVo> list = new ArrayList<PersonSalaryExcelVo>();
			excelList.forEach(item -> {
				PersonSalaryExcelVo personSalaryExcelVo = new PersonSalaryExcelVo();
				BeanUtils.copyProperties(item, personSalaryExcelVo);
				list.add(personSalaryExcelVo);
			});
			FileHelper.exportExcel(list, "薪资人员信息", "薪资人员信息", PersonSalaryExcelVo.class, fileName, response);
			return null;
		} else {
			return page;
		}
	}

	@ApiOperation("待审核列表")
	@GetMapping(value = "/waitVerity/list")
	public Page<ApprovalPersonVo> getWaitVerityList(@RequestParam int pageSize, @RequestParam int pageNumber,
			@RequestParam Long companyId, @RequestParam Long projectId, @RequestParam(required = false) String name) {
		// 1.特殊處理,為空不然查詢
		if (companyId == null || projectId == null) {
			return new Page<>(pageSize, pageNumber);
		}
		Person person = getPerson();
		return iPersonService.verityPageList(pageSize, pageNumber, name, companyId, projectId, person);
	}

	@ApiOperation("人员审核")
	@PostMapping(value = "/verity")
	public boolean verityPersonInfo(@RequestBody VerityPersonParam param) {
		buildRequestContext();
		Person verifyPerson = getPerson();
		boolean b = iPersonService.verityPersonInfo(param, verifyPerson);
//		if (Boolean.TRUE.equals(b) && param.getStatus() == PersonCheckStatus.INITED.getStatus()) {
//			UserRegistration userRegistration = userRegistrationService.getById(param.getId());
//			iPersonService.updatePlatformUser(userRegistration);
//		}
		return b;
	}

	@ApiOperation("人员简单信息")
	@GetMapping(value = "/simple")
	public Object simple(Person person) {
		LambdaQueryWrapper<Person> wrapper = new LambdaQueryWrapper<>();
		if (StringUtil.isNotEmpty(person.getId()) || StringUtil.isNotEmpty(person.getIdNumber())) {
			if (StringUtil.isNotEmpty(person.getId())) {
				wrapper.eq(Person::getId, person.getId());
			}
			if (StringUtil.isNotEmpty(person.getIdNumber())) {
				wrapper.eq(Person::getIdNumber, person.getIdNumber());
			}
			return iPersonService.getOne(wrapper);
		} else {
			return null;
		}
	}

	/**
	 * @param
	 * @Description 檢查人員信息是否完成
	 * @Return Boolean
	 * @Date 2021/4/8 15:08
	 */
	@ApiOperation("檢查人員信息是否完成")
	@GetMapping("/checkPersonMessage")
	public Boolean checkPersonMessageIsFinish() {
		return iPersonService.checkPersonMessageIsFinish(getPerson().getId());
	}

	@GetMapping("/personMsg/{userId}")
	public PersonMsgVo personMsg(@PathVariable Long userId) {
		return iPersonService.personMsg(userId);
	}

	@GetMapping("/personTree")
	public Object personTree() {
		AgencyUserModel agencyUserModel = getUserInfo();
		String userId = agencyUserModel.getUserId();
		return iPersonService.personTree(userId);
	}

	/**
	 * 获取监控屏-安全 菜单权限
	 *
	 * @return
	 */
	@GetMapping(value = "menu/list")
	@ApiOperation(value = "获取监控屏-安全 菜单权限", notes = "获取监控屏-安全 菜单权限")
	public Object getMenuList() {
		RequestContext.setToken(getToken());
		RequestContext.setProduct("AMOS_STUDIO_WEB");
		RequestContext.setAppKey("studio_normalapp_2941403");
		List<PermissionModel> permissionModels = (List) Privilege.permissionClient
				.currentPermissionTree("WEB", null, null, null).getResult();
		Collection<PermissionModel> children = permissionModels.get(0).getChildren();
		return CommonResponseUtil.success(children);
	}

	/**
	 * 新增人员账号信息
	 *
	 * @return
	 */
	@RequestMapping(value = "/saveNew", method = RequestMethod.POST)
	@ApiOperation(httpMethod = "POST", value = "新增人员账号信息", notes = "新增人员账号信息")
	public Object savePersonNew(@RequestBody PersonAccount personAccount) {
		return iPersonService.savePersonNew(personAccount);
	}

	/**
	 * 新增人员账号信息
	 *
	 * @return
	 */
	@RequestMapping(value = "/updateDept", method = RequestMethod.POST)
	@ApiOperation(httpMethod = "POST", value = "新增人员账号信息", notes = "新增人员账号信息")
	public Object updateDept(@RequestBody PersonAccount personAccount) {
		return iPersonService.updateDept(personAccount);
	}

	/**
	 * 获取人员是否入岗
	 *
	 * @return
	 */
	@RequestMapping(value = "/isInProject", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "获取人员是否入岗", notes = "获取人员是否入岗")
	public Object updateDept() {
		Person person = getPerson();
		PersonAscription pa = iPersonAscriptionService
				.getOne(new LambdaQueryWrapper<PersonAscription>().eq(PersonAscription::getPersonId, person.getId()));
		if (pa == null) {
			throw new BaseException("人员信息有错误,无归属数据");
		}
		if (pa.getProjectId() != null) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 获取人员orgcode
	 * 
	 * @return
	 */
	@RequestMapping(value = "/orgcode", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "获取人员orgcode", notes = "获取人员orgcode")
	public Object getPrecontrolOrgCode() {
		Person person = getPerson();
		return person.getOrgCode() != null ? person.getOrgCode() : "";
	}
}
