package com.yeejoin.precontrol.controller;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

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

import org.apache.commons.lang3.StringUtils;
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.PathVariable;
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 com.alibaba.fastjson.JSON;
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.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yeejoin.amos.component.feign.model.FeignClientResult;
import com.yeejoin.amos.feign.privilege.Privilege;
import com.yeejoin.amos.feign.privilege.model.AgencyUserModel;
import com.yeejoin.amos.feign.privilege.model.DepartmentModel;
import com.yeejoin.amos.feign.privilege.model.RoleModel;
import com.yeejoin.amos.feign.systemctl.Systemctl;
import com.yeejoin.precontrol.common.constant.Constant;
import com.yeejoin.precontrol.common.dto.CommonPageableDto;
import com.yeejoin.precontrol.common.dto.IsClockOkDto;
import com.yeejoin.precontrol.common.entity.BadManagement;
import com.yeejoin.precontrol.common.entity.BadManagementPerson;
import com.yeejoin.precontrol.common.entity.Company;
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.PersonClock;
import com.yeejoin.precontrol.common.entity.PersonContract;
import com.yeejoin.precontrol.common.entity.PersonWorkingHours;
import com.yeejoin.precontrol.common.entity.Project;
import com.yeejoin.precontrol.common.entity.ProjectClock;
import com.yeejoin.precontrol.common.entity.ProjectCompany;
import com.yeejoin.precontrol.common.entity.ProjectCoordinate;
import com.yeejoin.precontrol.common.entity.ProjectDevice;
import com.yeejoin.precontrol.common.entity.ProjectHistory;
import com.yeejoin.precontrol.common.entity.ProjectQrcode;
import com.yeejoin.precontrol.common.entity.Task;
import com.yeejoin.precontrol.common.entity.TaskPerson;
import com.yeejoin.precontrol.common.entity.TaskPersonFile;
import com.yeejoin.precontrol.common.enums.ContractUsefulEum;
import com.yeejoin.precontrol.common.enums.DeptTypeEnum;
import com.yeejoin.precontrol.common.enums.InRiskRegionEnum;
import com.yeejoin.precontrol.common.enums.TypeKeyEnum;
import com.yeejoin.precontrol.common.exception.BaseException;
import com.yeejoin.precontrol.common.exception.errorEnum.BaseExceptionEnum;
import com.yeejoin.precontrol.common.service.IBadManagementPersonService;
import com.yeejoin.precontrol.common.service.IBadManagementService;
import com.yeejoin.precontrol.common.service.ICompanyService;
import com.yeejoin.precontrol.common.service.IPersonAccessService;
import com.yeejoin.precontrol.common.service.IPersonAscriptionService;
import com.yeejoin.precontrol.common.service.IPersonClockService;
import com.yeejoin.precontrol.common.service.IPersonExamService;
import com.yeejoin.precontrol.common.service.IPersonService;
import com.yeejoin.precontrol.common.service.IPersonWorkingHoursService;
import com.yeejoin.precontrol.common.service.IProjectClockService;
import com.yeejoin.precontrol.common.service.IProjectCompanyService;
import com.yeejoin.precontrol.common.service.IProjectCoordinateService;
import com.yeejoin.precontrol.common.service.IProjectDeviceService;
import com.yeejoin.precontrol.common.service.IProjectHistoryService;
import com.yeejoin.precontrol.common.service.IProjectQrcodeService;
import com.yeejoin.precontrol.common.service.IProjectService;
import com.yeejoin.precontrol.common.service.IStatisticsService;
import com.yeejoin.precontrol.common.service.ITaskPersonFileService;
import com.yeejoin.precontrol.common.service.ITaskPersonService;
import com.yeejoin.precontrol.common.service.ITaskRiskControlService;
import com.yeejoin.precontrol.common.service.ITaskService;
import com.yeejoin.precontrol.common.service.SmallProService;
import com.yeejoin.precontrol.common.utils.DateTools;
import com.yeejoin.precontrol.common.utils.DistanceUtil;
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.vo.AdmissionVo;
import com.yeejoin.precontrol.common.vo.DepartureVo;
import com.yeejoin.precontrol.common.vo.EntryVo;
import com.yeejoin.precontrol.common.vo.IsClockOkVo;
import com.yeejoin.precontrol.common.vo.LeaveJobVo;
import com.yeejoin.precontrol.common.vo.MyClockExceptionVo;
import com.yeejoin.precontrol.common.vo.MyClockVo;
import com.yeejoin.precontrol.common.vo.MyHoursClockVo;
import com.yeejoin.precontrol.common.vo.ProjectQrBaseVo;
import com.yeejoin.precontrol.common.vo.ProjectQrCodeClockVo;
import com.yeejoin.precontrol.common.vo.UserBadManangerVo;
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 io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;

/**
 * 项目出入场二维码
 *
 * @author duanwei
 * @date 2020-06-30
 */
@RestController
@Api(tags = "项目出入场二维码Api")
@RequestMapping(value = "/project-qrcode", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@Slf4j
public class ProjectQrcodeController extends BaseController {
	/**
	 * 项目二维码服务
	 */
	@Autowired
	IProjectQrcodeService iProjectQrcodeService;
	/**
	 * 人员打卡服务
	 */
	@Autowired
	IPersonClockService iPersonClockService;
	/**
	 * 小程序二维码服务
	 */
	@Autowired
	SmallProService smallProService;
	/**
	 * 项目历史服务
	 */
	@Autowired
	IProjectHistoryService iProjectHistoryService;
	/**
	 * 项目服务
	 */
	@Autowired
	IProjectService iProjectService;
	/**
	 * 项目坐标信息服务
	 */
	@Autowired
	IProjectCoordinateService iProjectCoordinateService;
	/**
	 * 人员服务
	 */
	@Autowired
	IPersonService iPersonService;
	/**
	 * 人员关系表服务
	 */
	@Autowired
	IPersonAscriptionService iPersonAscriptionService;
	/**
	 * 项目打卡服务
	 */
	@Autowired
	IProjectClockService iProjectClockService;
	/**
	 * 任务与附件服务
	 */
	@Autowired
	ITaskPersonFileService iTaskPersonFileService;
	/**
	 * 任务与人员服务
	 */
	@Autowired
	ITaskPersonService iTaskPersonService;
	/**
	 * 任务服务
	 */
	@Autowired
	ITaskService iTaskService;
	/**
	 * 违规管理服务
	 */
	@Autowired
	IBadManagementService iBadManagementService;

	@Autowired
	IBadManagementPersonService iBadManagementPersonService;
	/**
	 * 人员与工时服务
	 */
	@Autowired
	IPersonWorkingHoursService iPersonWorkingHoursService;
	/**
	 * 缓存服务
	 */
	@Autowired
	RedisUtil redisUtil;
	/**
	 * 考试服务
	 */
	@Autowired
	IPersonExamService iPersonExamService;

	@Autowired
	ICompanyService icompanyService;

	@Autowired
	PlatformUtils platformUtils;

	@Autowired
	IProjectCompanyService iProjectCompanyService;

	@Autowired
	ITaskRiskControlService iTaskRiskControlService;

	@Autowired
	IPersonAccessService iPersonAccessService;

	@Autowired
	IProjectDeviceService iProjectDeviceService;

	@Autowired
	IStatisticsService statisticsService;
	/**
	 * 江西电建公司id
	 */
	@Value("${jxdj.id}")
	private String companyId;

	/**
	 * 新增项目出入场二维码
	 *
	 * @return
	 */
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	@ApiOperation(httpMethod = "POST", value = "新增项目出入场二维码", notes = "新增项目出入场二维码")
	public Object saveProjectQrcode(HttpServletRequest request, @RequestBody ProjectQrcode projectQrcode) {
		return iProjectQrcodeService.save(projectQrcode);
	}

	/**
	 * 根据id删除
	 *
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
	@ApiOperation(httpMethod = "DELETE", value = "根据id删除", notes = "根据id删除")
	public boolean deleteById(HttpServletRequest request, @PathVariable Long id) {
		return iProjectQrcodeService.removeById(id);
	}

	/**
	 * 修改项目出入场二维码
	 *
	 * @return
	 */
	@RequestMapping(value = "/updateById", method = RequestMethod.PUT)
	@ApiOperation(httpMethod = "PUT", value = "修改项目出入场二维码", notes = "修改项目出入场二维码")
	public boolean updateByIdProjectQrcode(HttpServletRequest request, @RequestBody ProjectQrcode projectQrcode) {
		return iProjectQrcodeService.updateById(projectQrcode);
	}

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

	/**
	 * 获取项目二维码 type = "0 入场 1离场 2入岗 3离岗",
	 *
	 * @return
	 */
	@RequestMapping(value = "/getQrCode", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "获取项目二维码", notes = "获取项目二维码")
	public void getQrCode(@RequestParam(value = "type") String type,
			@RequestParam(value = "fileType", required = false, defaultValue = "png") String fileType,
			@RequestParam(value = "width", required = false) String width,
			@RequestParam(value = "projectId") Long projectId, HttpServletResponse response) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(new Date());
		String token = smallProService.getSmallProToken();
		ProjectQrBaseVo projectQrBaseVo = getProjectQrCodeVo(type, projectId, "", cal, token);
		String uuid = String.valueOf(projectId) + "_" + type;
		redisUtil.set(Constant.SMALL_PRO_PRCODE + uuid, projectQrBaseVo);
		String page = "view/mine/ClockIn";
		smallProService.getSmallProQrCodeResponse(token, uuid, page, Long.valueOf(width), null, null, null, response,
				String.valueOf(projectId), fileType);
	}

	/**
	 * 获取分包商二维码
	 *
	 * @return
	 */
	@RequestMapping(value = "/getCompanyQrCode", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = " 获取分包商二维码", notes = " 获取分包商二维码")
	public void getCompanyQrCode(
			@RequestParam(value = "fileType", required = false, defaultValue = "png") String fileType,
			@RequestParam(value = "width", required = false) String width,
			@RequestParam(value = "projectId") Long projectId, @RequestParam(value = "companyId") Long companyId,
			HttpServletResponse response) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(new Date());
		String token = smallProService.getSmallProToken();
		Project project = iProjectService.getById(projectId);
		Company company = icompanyService.getById(companyId);
		Map<String, Object> map = new HashMap<>();
		map.put("projectId", projectId.toString());
		map.put("projectName", project != null ? project.getName() : "");
		map.put("companyId", companyId.toString());
		map.put("companyName", company != null ? company.getName() : "");
		String proAndCom = JSON.toJSONString(map);
		String projectPre = projectId.toString().substring(projectId.toString().length() - 3,
				projectId.toString().length());
		String uuid = String.valueOf(projectId + companyId) + "_" + projectPre;
		redisUtil.set(Constant.SMALL_PRO_COMPANY_PRCODE + uuid, proAndCom);
		String page = "view/mine/minepage/Login";
		smallProService.getSmallProQrCodeResponse(token, uuid, page, Long.valueOf(width), null, null, null, response,
				String.valueOf(projectId + "-" + companyId), fileType);
	}

	/**
	 * 根据随机数来查询二维码信息
	 *
	 * @return
	 */
	@RequestMapping(value = "/getPrCodeInfo", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "根据随机数来查询二维码信息", notes = "根据随机数来查询二维码信息")
	public Object listPage(String pId) {
		if (redisUtil.hasKey(Constant.SMALL_PRO_PRCODE + pId)) {
			ProjectQrBaseVo projectQrBaseVo = (ProjectQrBaseVo) redisUtil.get(Constant.SMALL_PRO_PRCODE + pId);
			Project project = iProjectService.getById(projectQrBaseVo.getPId());
			projectQrBaseVo.setProjectName(project.getName());
			return projectQrBaseVo;
		} else if (redisUtil.hasKey(Constant.SMALL_PRO_COMPANY_PRCODE + pId)) {
			return redisUtil.get(Constant.SMALL_PRO_COMPANY_PRCODE + pId);
		} else {
			throw new BaseException(BaseExceptionEnum.DATA_NOT_EXISTS);
		}
	}

	/**
	 * 判断是否处于打卡范围
	 *
	 * @return
	 */
	@RequestMapping(value = "/isClockOk", method = RequestMethod.POST)
	@ApiOperation(httpMethod = "POST", value = "判断是否处于打卡范围", notes = "判断是否处于打卡范围")
	public Object isClockOk(@RequestBody IsClockOkDto isClockOkDto) {
		String clockAddress = isClockOkDto.getClockAddress();
		Double longitude = isClockOkDto.getLongitude();
		Double latitude = isClockOkDto.getLatitude();
		Long projectId = isClockOkDto.getProjectId();

		List<ProjectCoordinate> projectCoordinateList = iProjectCoordinateService
				.list(new QueryWrapper<ProjectCoordinate>().lambda().eq(ProjectCoordinate::getProjectId, projectId));

		IsClockOkVo isClockOkVo = new IsClockOkVo();
		AtomicInteger result = new AtomicInteger();
		log.info("打卡位置" + longitude + "," + latitude);
		projectCoordinateList.forEach(projectCoordinate -> {
			String distance = DistanceUtil.getDistance(latitude, longitude, projectCoordinate.getLatitude(),
					projectCoordinate.getLongitude());
			if (Double.valueOf(distance) < projectCoordinate.getClockScope()) {
				result.addAndGet(1);
			}
		});

		if (result.get() > 0) {
			isClockOkVo.setStatus(true);
			isClockOkVo.setClockAdrress(clockAddress);
		} else {
			// 当前位置大于范围
			isClockOkVo.setStatus(false);
			isClockOkVo.setClockAdrress(clockAddress);
		}
		return isClockOkVo;
	}

	/**
	 * 打卡类型 0 入场 1 离场 2上岗 3离岗
	 *
	 * @return
	 */
	@RequestMapping(value = "/parseQrCode", method = RequestMethod.POST)
	@ApiOperation(httpMethod = "POST", value = "项目打卡", notes = "项目打卡")
	public Object parseQrCode(@RequestBody ProjectQrCodeClockVo projectQrCodeClockVo) {
		Person person = getPerson();
		Long personId = person.getId();
		Person curPerson = iPersonService.getById(personId);
		Long projectId = projectQrCodeClockVo.getPId();
		String type = projectQrCodeClockVo.getType();
		Project project = iProjectService.getById(projectId);
		if (project == null) {
			throw new BaseException("项目不存在");
		}
		String addressName = projectQrCodeClockVo.getClockAddress();
		if (Constant.ZERO.equals(type)) {
			// 入场打卡
			iPersonAccessService.enterJudge(curPerson,projectId);
			clockByTypeAndProject(personId, projectQrCodeClockVo);
		} else if (Constant.ONE.equals(type)) {
			// 离场打卡
			// 加判断 判断当前项目 如果离岗了 不准打卡
			List<ProjectHistory> list = iProjectHistoryService.list(new LambdaQueryWrapper<ProjectHistory>()
					.eq(ProjectHistory::getPersonId, personId).eq(ProjectHistory::getProjectId, projectId));
			AtomicBoolean isJob = new AtomicBoolean(false);
			if (StringUtil.isNotEmpty(list)) {
				list.forEach(projectHistory -> {
					Date endTime = projectHistory.getEndTime();
					if (endTime == null) {
						isJob.set(true);
					}
				});
			} else {
				throw new BaseException("离场失败，请先入岗打卡");
			}
			// 企业轨迹中有数据 没有离岗 说明可以打卡
			if (isJob.get()) {
				clockByTypeAndProject(personId, projectQrCodeClockVo);
			} else {
				throw new BaseException("离场失败，请先入岗打卡");
			}
			// 退出风险作业区域
			List<TaskPerson> taskPersonlist = iTaskPersonService
					.list(new LambdaQueryWrapper<TaskPerson>().eq(TaskPerson::getPersonId, personId)
							.eq(TaskPerson::getInRiskRegion, InRiskRegionEnum.inRiskRegion.getStatus()));
			if (StringUtil.isNotEmpty(taskPersonlist)) {
				taskPersonlist.forEach(i -> i.setInRiskRegion(InRiskRegionEnum.outRiskRegion.getStatus()));
				iTaskPersonService.updateBatchById(taskPersonlist);
			}
		} else if (Constant.TWO.equals(type)) {
			platformUtils.setPlatFormAccess();
			// 入岗打卡
			if (curPerson.getIsBlack() == 1L) {
				throw new BaseException("黑名单人员，禁止上岗");
			}
			// 如果有数据查询一下 项目历史轨迹 如果轨迹中 确实离岗了 才能再入岗
			List<ProjectHistory> list = iProjectHistoryService
					.list(new LambdaQueryWrapper<ProjectHistory>().eq(ProjectHistory::getPersonId, personId));
			if (StringUtil.isNotEmpty(list)) {
				list.forEach(projectHistory -> { 
					Date endTime = projectHistory.getEndTime();
					if (endTime == null) {
						Project p = iProjectService.getById(projectHistory.getProjectId());
						String name = "";
						if (p != null) {
							name = p.getName().length() > 6 ? p.getName().substring(0, 6) + "..." : p.getName();
						}
						throw new BaseException("入岗失败,仍处于" + name + "项目中,请先离岗!");
					}
				});
			}
			PersonAscription ascription = iPersonAscriptionService
					.getOne(new LambdaQueryWrapper<PersonAscription>().eq(PersonAscription::getPersonId, personId));
			Company company = icompanyService.getById(ascription.getCompanyId());
			// 判断是否是当前人的所在的分包商 是否属于这个项目
			int count = iProjectCompanyService.count(
					new LambdaQueryWrapper<ProjectCompany>().eq(ProjectCompany::getCompanyId, ascription.getCompanyId())
							.eq(ProjectCompany::getProjectId, projectId));
			if (company != null) {
				if (TypeKeyEnum.COMPANY.getType() == Integer.valueOf(company.getTypeKey()) && count == 0) {
					throw new BaseException("入岗失败,该项目没有关联当前人员的分包商");
				}
			} else {
				throw new BaseException("入岗失败,当前人员没有所属分包商");
			}
//			// 判断是否是当前项目部的项目
//			if (!iPersonService.canJoinProject(personId, projectId)) {
//				throw new BaseException("入岗失败,该项目不属于当前人员所在的项目部");
//			}

			// 修改身份配置

			PersonAccount personAccount = projectQrCodeClockVo.getPersonAccount();
			if (personAccount != null) {
				String orgCode = project.getOrgCode();
				if (orgCode == null) {
					throw new BaseException("入岗失败,该项目没有所属项目部");
				}

				String userId = String.valueOf(curPerson.getUserId());
				FeignClientResult<AgencyUserModel> agencyUserModelFeignClientResult = Privilege.agencyUserClient
						.queryByUserId(userId);
				AgencyUserModel userModel = agencyUserModelFeignClientResult.getResult();
				Long companySeq = Long.valueOf(companyId);
				Map<Long, List<Long>> map = new HashMap<>();
				if (curPerson.getIsJxdj() == TypeKeyEnum.JXDJ.getLongType()) {
					map.put(personAccount.getPlatformDepartmentId(), personAccount.getRoleIdList());
				} else {
					Long newDeptId = null;
					FeignClientResult<DepartmentModel> fd = Privilege.departmentClient.queryByOrgcode(orgCode);
					DepartmentModel dept = fd.getResult();
					FeignClientResult<Collection<DepartmentModel>> fc = Privilege.departmentClient
							.querySubAgencyTree(dept.getSequenceNbr());
					Collection<DepartmentModel> collect = fc.getResult();
					DepartmentModel fbs = null;
					for (DepartmentModel departmentModel : collect) {
						if ("fbs".equals(departmentModel.getLevel())) {
							fbs = departmentModel;
							break;
						}
					}
					if (fbs == null) {
						DepartmentModel newfbs = new DepartmentModel();
						newfbs.setCompanySeq(companySeq);
						newfbs.setDepartmentName("分包商");
						newfbs.setLevel("fbs");
						newfbs.setParentId(dept.getSequenceNbr());
						FeignClientResult<DepartmentModel> fdfbs = Privilege.departmentClient.create(newfbs);
						fbs = fdfbs.getResult();
					}
					newDeptId = fbs.getSequenceNbr();
					map.put(newDeptId, personAccount.getRoleIdList());
				}
				userModel.setOrgRoleSeqs(map);
				FeignClientResult<AgencyUserModel> result = new FeignClientResult<>();
				// 修改身份配置
				try {
					result = Privilege.agencyUserClient.update(userModel, userId);
				} catch (Exception e) {
					e.printStackTrace();
					log.error(e.getMessage());
					throw new BaseException("平台更新账户失败");
				}
				int status = result.getStatus();
				if (status == 200) {
					iPersonService.setRoleName(curPerson, Arrays.toString(personAccount.getRoleIdList().toArray()));
					iPersonService.updateById(curPerson);
					if (curPerson.getIsJxdj() == TypeKeyEnum.JXDJ.getLongType()) {
						PersonAscription personAscription = iPersonAscriptionService
								.getOne(new LambdaQueryWrapper<PersonAscription>().eq(PersonAscription::getPersonId,
										person.getId()));
						personAscription.setDepartmentId(personAccount.getPlatformDepartmentId());
						personAscription.setDepartmentName(personAccount.getPlatformDepartmentName());
						iPersonAscriptionService.updateById(personAscription);
					}
				}
			}

			iProjectQrcodeService.projectClock(personId, projectId, addressName);

			// 同步数据到新项目门禁
			List<ProjectDevice> devicelist = iProjectDeviceService
					.list(new LambdaQueryWrapper<ProjectDevice>().eq(ProjectDevice::getProjectId, projectId));
			List<String> sessonNames = devicelist.stream().map(ProjectDevice::getNumber).collect(Collectors.toList());
			if (StringUtil.isNotEmpty(sessonNames)) {
				WebSocket.addPerson(curPerson, sessonNames);
			}

		} else if (Constant.THREE.equals(type)) {
			// 离岗打卡
//			// 如果有人来打下岗卡 先查有没有上岗记录 有上岗才准打下岗
//			List<ProjectClock> projectClockList = iProjectClockService.list(new LambdaQueryWrapper<ProjectClock>()
//					.eq(ProjectClock::getType, Constant.TWO).eq(ProjectClock::getPersonId, personId));
//			if (StringUtil.isEmpty(projectClockList)) {
//				throw new BaseException("当前人员未存在上岗记录");
//			}
//			// 代办任务没做完 不准离岗
//			List<TaskPerson> task = iTaskPersonService.list(new LambdaQueryWrapper<TaskPerson>()
//					.eq(TaskPerson::getPersonId, personId).eq(TaskPerson::getReadStatus, 0));
//			if (StringUtil.isNotEmpty(task)) {
//				throw new BaseException("待办任务未完成,请先完成代办任务再离岗!");
//			}

			List<ProjectHistory> projectHistoryList = iProjectHistoryService.list(
					new LambdaQueryWrapper<ProjectHistory>().eq(ProjectHistory::getProjectId, Long.valueOf(projectId))
							.eq(ProjectHistory::getPersonId, personId).orderByDesc(ProjectHistory::getCreateDate));
			if (StringUtil.isNotEmpty(projectHistoryList)) {
				ProjectHistory projectHistory = projectHistoryList.get(0);
				if (projectHistory.getEndTime() != null) {
					throw new BaseException("请先上岗!");
				}
				projectHistory.setEndTime(new Date());
				iProjectHistoryService.updateById(projectHistory);

				ProjectClock projectClock = new ProjectClock();
				projectClock.setPersonId(personId);
				projectClock.setType(3);
				projectClock.setClockTime(new Date());
				projectClock.setClockProject(project.getName());
				projectClock.setClockProjectId(Long.valueOf(projectId));
				projectClock.setClockAddress(addressName);
				iProjectClockService.save(projectClock);

				// 离岗离开项目
				PersonAscription personAscription = iPersonAscriptionService
						.getOne(new LambdaQueryWrapper<PersonAscription>().eq(PersonAscription::getPersonId, personId));
				if (personAscription == null) {
					throw new BaseException("人员的关联信息不存在");
				}
				iPersonAscriptionService.update(null,
						Wrappers.<PersonAscription>lambdaUpdate().set(PersonAscription::getProjectId, null)
								.set(PersonAscription::getOrgCode, null).set(PersonAscription::getStatus, 1)
								.eq(PersonAscription::getId, personAscription.getId()));

				boolean jxdj = person.getIsJxdj().equals(1L) ? true : false;
				String currentOrgCode = jxdjLeave(person, jxdj);
				// 设置人员orgCode为空 江西电建的人特殊处理 暂时没处理
				iPersonService.update(null, Wrappers.<Person>lambdaUpdate().set(Person::getOrgCode, currentOrgCode)
						.eq(Person::getId, personAscription.getPersonId()));

				// 江西电建激活状态入岗就调整为1
				if (jxdj) {
					// 如果人员的部门类型是公共部门，org_code设置为null
					if (DeptTypeEnum.PUBLIC.getLabel().equals(person.getDeptType())) {
						person.setOrgCode(null);
					}
					person.setActiveStatus(1L);
					iPersonService.updateById(person);
				}

				// 同步数据到新项目门禁
				List<ProjectDevice> devicelist = iProjectDeviceService
						.list(new LambdaQueryWrapper<ProjectDevice>().eq(ProjectDevice::getProjectId, projectId));
				List<String> sessonNames = devicelist.stream().map(ProjectDevice::getNumber)
						.collect(Collectors.toList());
				if (StringUtil.isNotEmpty(sessonNames)) {
					WebSocket.delPerson(Arrays.asList(curPerson.getUserId()));
				}
			} else {
				throw new BaseException("人员项目历史数据不存在");
			}
		} else {
			throw new BaseException(BaseExceptionEnum.PARAMETER_ERROR);
		}
		projectQrCodeClockVo.setClockTime(new Date());
		projectQrCodeClockVo.setClockAddress(addressName);

		Long pId = projectQrCodeClockVo.getPId();
		Project project1 = iProjectService.getById(pId);
		projectQrCodeClockVo.setProjectName(project1.getName());
		return projectQrCodeClockVo;
	}

	/**
	 * 打卡按月异常情况展示
	 *
	 * @return
	 */
	@RequestMapping(value = "/clockExcetionList", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "打卡按月异常情况展示", notes = "打卡按月异常情况展示")
	public Object clockExcetionList(@DateTimeFormat(pattern = "yyyy-MM") Date month) {
		Person person = getPerson();
		Long userId = person.getId();
		boolean thisTime = true;
		if (month != null) {
			thisTime = DateTools.isThisTime(month);
		}
		LinkedList<String> monthDays;
		if (thisTime) {
			// 是本月
			monthDays = DateTools.getMonthDays();
		} else {
			monthDays = DateTools.getMonthEveryDays(month);
		}
		LinkedHashMap<String, Object> maps = new LinkedHashMap<>();
		monthDays.forEach(day -> {
			// 查询每天的数据情况
			String start = day + " 00:00:00";
			String end = day + " 23:59:59";
			List<PersonClock> personClockStartList = iPersonClockService.list(new LambdaQueryWrapper<PersonClock>()
					.eq(PersonClock::getPersonId, userId).between(PersonClock::getClockTime, start, end)
					.eq(PersonClock::getInOrOut, 0).orderByAsc(PersonClock::getClockTime));
			List<PersonClock> personClockEndList = iPersonClockService.list(new LambdaQueryWrapper<PersonClock>()
					.eq(PersonClock::getPersonId, userId).between(PersonClock::getClockTime, start, end)
					.eq(PersonClock::getInOrOut, 1).orderByDesc(PersonClock::getClockTime));
			MyClockExceptionVo myClockExceptionVo = new MyClockExceptionVo();
			// 打卡数据必须一天有两次 才代表无异常
			if (StringUtil.isEmpty(personClockStartList) || StringUtil.isEmpty(personClockEndList)) {
				myClockExceptionVo.setStatus(0);
			} else {
				myClockExceptionVo.setStatus(1);
			}
			maps.put(day, myClockExceptionVo);
		});
		return maps;
	}

	/**
	 * 查询个人违章信息
	 *
	 * @return
	 */
	@RequestMapping(value = "/badList", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "查询个人违章信息", notes = "查询个人违章信息")
	public Object badList(@ApiParam(value = "分页条件 isAll=0 具体分页必传") CommonPageableDto pageable,
			@ApiParam(value = "人员id") Long personId, @ApiParam(value = "开始时间 举例 2020-07-01 00:00:00") String startDate,
			@ApiParam(value = "结束时间 举例 2020-07-30 23:59:59") String endDate) {
		// 获取用户id 创建人的
		if (pageable.getIsAll() == 1) {
			pageable.setPageNumber(0);
			pageable.setPageSize(Integer.MAX_VALUE);
		}
		Page<BadManagementPerson> page = new Page<>(pageable.getPageNumber(), pageable.getPageSize());

		if (personId == null) {
			Person person = getPerson();
			personId = person.getId();
		}

		LambdaQueryWrapper<BadManagementPerson> badManagementLambdaQueryWrapper = new LambdaQueryWrapper<BadManagementPerson>()
				.eq(BadManagementPerson::getPersonId, personId).orderByDesc(BadManagementPerson::getCreateDate);
		if (StringUtils.isNotEmpty(startDate) && StringUtil.isNotEmpty(endDate)) {
			badManagementLambdaQueryWrapper.between(BadManagementPerson::getCreateDate, startDate, endDate);
		}
		IPage<BadManagementPerson> badManagementList = iBadManagementPersonService.page(page,
				badManagementLambdaQueryWrapper);
		List<BadManagementPerson> records = badManagementList.getRecords();

		// 自己违规的情况
		List<UserBadManangerVo> userBadManangerVos = new ArrayList<>();
		if (StringUtil.isEmpty(records)) {
			return badManagementList;
		} else {
			records.forEach(badManagementPerson -> {
				Long taskId = badManagementPerson.getTaskId();
				Task task = iTaskService.getById(taskId);
				UserBadManangerVo userBadManangerVo = new UserBadManangerVo();
				userBadManangerVo.setTaskId(taskId);
				if (task != null) {
					userBadManangerVo.setProjectName(task.getProjectName());
				}
				BadManagement badManagement = iBadManagementService
						.getOne(new LambdaQueryWrapper<BadManagement>().eq(BadManagement::getTaskId, taskId));
				if (badManagement != null) {
					userBadManangerVo.setBody(badManagement.getBody());
				}
				List<TaskPersonFile> taskPersonFiles = iTaskPersonFileService
						.list(new LambdaQueryWrapper<TaskPersonFile>().eq(TaskPersonFile::getTaskId, taskId)
								.eq(TaskPersonFile::getPersonType, 99));
				if (StringUtil.isNotEmpty(taskPersonFiles)) {
					List<String> filePath = new ArrayList<>();
					for (TaskPersonFile taskPersonFile : taskPersonFiles) {
						filePath.add(taskPersonFile.getFilePath());
					}
					userBadManangerVo.setFilePath(filePath);
				}
				userBadManangerVo.setBadDate(badManagement.getCreateDate());
				userBadManangerVos.add(userBadManangerVo);
			});
		}
		IPage<UserBadManangerVo> userBadManangerVoIPage = new Page<>();
		userBadManangerVoIPage.setRecords(userBadManangerVos);
		userBadManangerVoIPage.setTotal(userBadManangerVos.size());
		userBadManangerVoIPage.setSize(pageable.getPageSize());
		userBadManangerVoIPage.setCurrent(pageable.getPageNumber());
		return userBadManangerVoIPage;

	}

	/**
	 * app端我的工时
	 *
	 * @return
	 */
	@RequestMapping(value = "/myHours", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "app端我的工时", notes = "app端我的工时")
	public Object myHours(@DateTimeFormat(pattern = "yyyy-MM-dd") Date day) {
		if (day == null) {
			day = new Date();
		}
		Person person = getPerson();
		// 获取用户id 创建人的
		Long userId = person.getId();
		Date startDayDate = day;
		Date endDayDate = day;
		SimpleDateFormat startFormat = new SimpleDateFormat("yyyy-MM-dd 00:00:00");
		SimpleDateFormat endFormat = new SimpleDateFormat("yyyy-MM-dd 23:59:59");
		String start = startFormat.format(startDayDate);
		String end = endFormat.format(endDayDate);

		// 当天的打卡记录
		List<PersonClock> list = iPersonClockService.list(new LambdaQueryWrapper<PersonClock>()
				.eq(PersonClock::getPersonId, userId).between(PersonClock::getClockTime, start, end));
		int size = list.size();
		MyHoursClockVo myHoursClockVo = new MyHoursClockVo();
		myHoursClockVo.setClockNum(String.valueOf(size));

		// 获取最早打卡时间
		List<PersonClock> personClockStartList = iPersonClockService.list(new LambdaQueryWrapper<PersonClock>()
				.eq(PersonClock::getPersonId, userId).between(PersonClock::getClockTime, start, end)
				.eq(PersonClock::getInOrOut, 0).orderByAsc(PersonClock::getClockTime));

		List<PersonClock> personClockEndList = iPersonClockService.list(new LambdaQueryWrapper<PersonClock>()
				.eq(PersonClock::getPersonId, userId).between(PersonClock::getClockTime, start, end)
				.eq(PersonClock::getInOrOut, 1).orderByDesc(PersonClock::getClockTime));

		List<MyClockVo> myClock = new ArrayList<>();
		MyClockVo endClockVo = new MyClockVo();
		MyClockVo startClockVo = new MyClockVo();
		// 如果没有对应时间的记录
		if (StringUtil.isEmpty(personClockStartList) && StringUtil.isNotEmpty(personClockEndList)) {
			PersonClock personClock2 = personClockEndList.get(0);
			// 最晚打卡
			endClockVo.setPersonId(userId);
			endClockVo.setInOrOut(personClock2.getInOrOut());
			endClockVo.setClockTime(personClock2.getClockTime());
			endClockVo.setClockProjectId(personClock2.getClockProjectId());
			endClockVo.setClockProject(personClock2.getClockProject());
			myClock.add(endClockVo);
			myHoursClockVo.setMyClock(myClock);
			return myHoursClockVo;
		} else if (StringUtil.isEmpty(personClockEndList) && StringUtil.isNotEmpty(personClockStartList)) {
			PersonClock personClock1 = personClockStartList.get(0);
			startClockVo.setPersonId(userId);
			startClockVo.setInOrOut(personClock1.getInOrOut());
			startClockVo.setClockTime(personClock1.getClockTime());
			startClockVo.setClockProjectId(personClock1.getClockProjectId());
			startClockVo.setClockProject(personClock1.getClockProject());
			myClock.add(startClockVo);
			myHoursClockVo.setMyClock(myClock);
			return myHoursClockVo;
		} else if (StringUtil.isEmpty(personClockEndList) && StringUtil.isEmpty(personClockStartList)) {
			return myHoursClockVo;
		} else {
			PersonClock personClock1 = personClockStartList.get(0);
			PersonClock personClock2 = personClockEndList.get(0);
			// 计算工时
			if (personClock1 != null && personClock2 != null) {
				Long hour = (personClock2.getClockTime().getTime() - personClock1.getClockTime().getTime()) / 1000 / 60
						/ 60;
				myHoursClockVo.setHour(hour);
			}
			startClockVo.setPersonId(userId);
			startClockVo.setInOrOut(personClock1.getInOrOut());
			startClockVo.setClockTime(personClock1.getClockTime());
			startClockVo.setClockProjectId(personClock1.getClockProjectId());
			startClockVo.setClockProject(personClock1.getClockProject());
			myClock.add(startClockVo);

			endClockVo.setPersonId(userId);
			endClockVo.setInOrOut(personClock2.getInOrOut());
			endClockVo.setClockTime(personClock2.getClockTime());
			endClockVo.setClockProjectId(personClock2.getClockProjectId());
			endClockVo.setClockProject(personClock2.getClockProject());
			myClock.add(endClockVo);
			myHoursClockVo.setMyClock(myClock);

		}

		return myHoursClockVo;
	}

	/**
	 * web端专用我的工时查询
	 *
	 * @param pageable
	 * @param startTime
	 * @param endTime
	 * @return
	 */
	@RequestMapping(value = "/workHourStatistical", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "web端专用我的工时查询", notes = "web专用我的工时查询")
	public Object workHourStatistical(@ApiParam(value = "分页条件 isAll=0 具体分页必传") CommonPageableDto pageable,
			@DateTimeFormat(pattern = "yyyy-MM-dd 00:00:00") String startTime,
			@DateTimeFormat(pattern = "yyyy-MM-dd 23:59:59") String endTime, @ApiParam(value = "用户id") Long id) {
		if (pageable.getIsAll() == 1) {
			pageable.setPageNumber(0);
			pageable.setPageSize(Integer.MAX_VALUE);
		}
		Page<PersonClock> page = new Page<>(pageable.getPageNumber(), pageable.getPageSize());
		IPage<PersonClock> pageData = null;
		if (startTime == null || endTime == null) {
			pageData = iPersonClockService.page(page,
					new LambdaQueryWrapper<PersonClock>().eq(PersonClock::getPersonId, id));
		} else {
			pageData = iPersonClockService.page(page, new LambdaQueryWrapper<PersonClock>()
					.eq(PersonClock::getPersonId, id).between(PersonClock::getClockTime, startTime, endTime));
		}
		if (!StringUtil.isEmpty(pageData.getRecords())) {
			pageData.getRecords().forEach(i -> i.setInOrOutLabel(i.getInOrOut() == 0 ? "入场" : "离场"));
		}
		return pageData;
	}

	/**
	 * web端专用我的工时数量查询
	 *
	 * @param startTime
	 * @param endTime
	 * @return
	 */
	@RequestMapping(value = "/workHourStatisticalNum", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "web端专用我的工时数量查询", notes = "web端专用我的工时数量查询")
	public Object workHourStatisticalNum(@DateTimeFormat(pattern = "yyyy-MM-dd 00:00:00") Date startTime,
			@DateTimeFormat(pattern = "yyyy-MM-dd 23:59:59") Date endTime, @ApiParam(value = "用户id") Long id) {

//		List<PersonWorkingHours> list;
//		if (startTime == null || endTime == null) {
//			list = iPersonWorkingHoursService
//					.list(new LambdaQueryWrapper<PersonWorkingHours>().eq(PersonWorkingHours::getPersonId, id));
//		} else {
//			list = iPersonWorkingHoursService.list(new LambdaQueryWrapper<PersonWorkingHours>()
//					.eq(PersonWorkingHours::getPersonId, id).between(PersonWorkingHours::getDate, startTime, endTime));
//		}
//
//		int day = 0;
//		AtomicReference<Double> hour = new AtomicReference<>(0.0);
//		if (StringUtil.isNotEmpty(list)) {
//			day = list.size();
//			list.forEach(l -> {
//				hour.updateAndGet(v -> v + l.getWorkingHours());
//			});
//		}
		CommonPageableDto pageable = new CommonPageableDto(0);
		pageable.setPageNumber(0);
		pageable.setPageSize(Integer.MAX_VALUE);
		Page<PersonClock> page = new Page<>(pageable.getPageNumber(), pageable.getPageSize());
		IPage<PersonClock> pageData = null;

		List<PersonClock> dayList = new ArrayList<PersonClock>();
		if (startTime == null || endTime == null) {
			dayList = iPersonClockService.list(new LambdaQueryWrapper<PersonClock>().eq(PersonClock::getPersonId, id)
					.groupBy(PersonClock::getClockDate));
		} else {
			dayList = iPersonClockService.list(new LambdaQueryWrapper<PersonClock>().eq(PersonClock::getPersonId, id)
					.between(PersonClock::getClockTime, startTime, endTime).groupBy(PersonClock::getClockDate));
		}
		Map<String, Object> map = new HashMap<>();
		map.put("day", dayList.size());
		List<PersonClock> inList = iPersonClockService.getEveryDayMinList(id, startTime, endTime);
		List<PersonClock> outList = iPersonClockService.getEveryDayMaxList(id, startTime, endTime);
		Map<Date, Date> dateMap = new HashMap<>();
		inList.forEach(i -> dateMap.put(i.getClockDate(), i.getClockTime()));
		Double hour = 0.0;
		// 一天的毫秒数
		Long nd = (long) (1000 * 60 * 60 * 24);
		// 一小时的毫秒数
		Long nh = (long) (1000 * 60 * 60);
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		for (PersonClock i : outList) {
			Date inTime = dateMap.get(i.getClockDate());
			Date outTime = i.getClockTime();
			if (inTime != null && outTime != null) {
				Long diff = (long) 0;
				diff = outTime.getTime() - inTime.getTime();
				hour += diff.doubleValue() % nd.doubleValue() / nh.doubleValue();
			}
		}
		BigDecimal b = new BigDecimal(hour);
		hour = b.setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
		map.put("hour", hour);
		return map;
	}

	/**
	 * 根据工程id和类型进行打卡
	 *
	 * @param personId             用户id
	 * @param projectQrCodeClockVo 打卡对象 类型 0 入场 1离场 2入岗 3离岗
	 */
	private void clockByTypeAndProject(Long personId, ProjectQrCodeClockVo projectQrCodeClockVo) {
		String type = projectQrCodeClockVo.getType();
		Long pId = projectQrCodeClockVo.getPId();
		Double longitude = projectQrCodeClockVo.getLongitude();
		Double latitude = projectQrCodeClockVo.getLatitude();
		String addressName = projectQrCodeClockVo.getClockAddress();
		Project project = iProjectService.getById(pId);

		log.info("打卡位置" + longitude + "," + latitude);
		List<ProjectCoordinate> projectCoordinateList = iProjectCoordinateService
				.list(new QueryWrapper<ProjectCoordinate>().lambda().eq(ProjectCoordinate::getProjectId, pId));
		AtomicInteger result = new AtomicInteger();
		projectCoordinateList.forEach(projectCoordinate -> {
			String distance = DistanceUtil.getDistance(latitude, longitude, projectCoordinate.getLatitude(),
					projectCoordinate.getLongitude());
			// 当前位置打卡距离小于打卡半径
			if (Double.valueOf(distance) < projectCoordinate.getClockScope()) {
				result.addAndGet(1);
			}
		});
		Person person = iPersonService.getById(personId);
		PersonAscription ascription = iPersonAscriptionService
				.getOne(new LambdaQueryWrapper<PersonAscription>().eq(PersonAscription::getPersonId, personId));
		Date currentDate = new Date();
		long currentDateTime = currentDate.getTime();
		if (result.get() < 1) {
			throw new BaseException("打卡位置大于项目设定的最远距离");
		}
		PersonClock personClock = new PersonClock();
		personClock.setPersonId(Long.valueOf(personId));
		if (Constant.ZERO.equals(type)) {
			personClock.setInOrOut(0);
		} else {
			personClock.setInOrOut(1);
		}
		try {
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
			personClock.setClockDate(dateFormat.parse(dateFormat.format(new Date())));
		} catch (ParseException e) {
			throw new BaseException("日期转换错误");
		}
		personClock.setClockCompanyId(ascription.getCompanyId());
		personClock.setClockTime(new Date());
		personClock.setClockProjectId(String.valueOf(pId));
		personClock.setClockProject(project.getName());
		personClock.setClockAddress(addressName);
		personClock.setOrgCode(person.getOrgCode());
		iPersonClockService.save(personClock);
		String day = DateTools.getPastDate(0);
		String start = day + " 00:00:00";
		String end = day + " 23:59:59";
		double resultTime;

		if (Constant.ZERO.equals(type)) {
			// 入场进行激活状态调整
			if (person != null) {
				person.setActiveStatus(1L);
				iPersonService.updateById(person);
			}
		} else if (Constant.ONE.equals(type)) {
			if (person != null) {
				person.setActiveStatus(0L);
				iPersonService.updateById(person);
			}
			// 离场 计算出工时数据
			PersonWorkingHours personWorkingHours = iPersonWorkingHoursService
					.getOne(new LambdaQueryWrapper<PersonWorkingHours>().eq(PersonWorkingHours::getPersonId, personId)
							.eq(PersonWorkingHours::getProjectId, pId).eq(PersonWorkingHours::getDate, day));
			// 获取最小打卡时间
			List<PersonClock> personClockList = iPersonClockService
					.list(new LambdaQueryWrapper<PersonClock>().eq(PersonClock::getClockProjectId, pId)
							.eq(PersonClock::getPersonId, personId).between(PersonClock::getClockTime, start, end)
							.eq(PersonClock::getInOrOut, 0).orderByAsc(PersonClock::getClockTime));
			if (StringUtil.isNotEmpty(personClockList)) {
				PersonClock personClock1 = personClockList.get(0);
				long minTime = personClock1.getClockTime().getTime();
				resultTime = (currentDateTime - minTime) / 1000 / 60 / 60.0;

				if (personWorkingHours == null) {
					personWorkingHours = new PersonWorkingHours();
					if (StringUtil.isNotEmpty(personClockList)) {
						personWorkingHours.setPersonId(personId);
						personWorkingHours.setDate(currentDate);
						personWorkingHours.setProjectId(Long.valueOf(pId));
						personWorkingHours.setWorkingHours(resultTime);
						iPersonWorkingHoursService.save(personWorkingHours);
					}
				} else {
					// 更新
					personWorkingHours.setWorkingHours(resultTime);
					iPersonWorkingHoursService.updateById(personWorkingHours);
				}
			} else {
				log.error("未打入场卡,直接打了离场卡:{}", personId);
			}
		}

		// 更新推送
		statisticsService.initWs(person.getOrgCode(), Constant.WS_COMPOSITESUM);
	}

	/**
	 * 根据类型、工程id、频率计算返回对象 部分参数根据需求调整 暂时不考虑去除
	 *
	 * @param type
	 * @param projectId
	 * @param frequency
	 * @param cal
	 * @return
	 */
	private ProjectQrBaseVo getProjectQrCodeVo(String type, Long projectId, String frequency, Calendar cal,
			String accessToken) {
		switch (type) {
		case Constant.ZERO:
			AdmissionVo adminssionVo = new AdmissionVo();
			adminssionVo.setType(type);
			adminssionVo.setPId(projectId);
			return adminssionVo;
		case Constant.ONE:
			DepartureVo departureVo = new DepartureVo();
			departureVo.setType(type);
			departureVo.setPId(projectId);
			return departureVo;
		case Constant.TWO:
			EntryVo entryVo = new EntryVo();
			entryVo.setType(type);
			entryVo.setPId(projectId);
			return entryVo;
		case Constant.THREE:
			LeaveJobVo leaveJobVo = new LeaveJobVo();
			leaveJobVo.setType(type);
			leaveJobVo.setPId(projectId);
			return leaveJobVo;
		default:
			throw new BaseException(BaseExceptionEnum.PARAMETER_ERROR);
		}
	}

	private String jxdjLeave(Person person, boolean jxdj) {
		try {
			String currentOrgCode = null;
			Long companyId;
			String departmentOrgCode = null;
			Long departmentId = null;
			Long userId = person.getUserId();
			log.info("江西电建离岗人员userId:" + userId);
			AgencyUserModel userModel = platformUtils.getSyncPlatformUser(String.valueOf(userId));
			companyId = (userModel.getCompanys() != null && userModel.getCompanys().get(0) != null)
					? userModel.getCompanys().get(0).getSequenceNbr()
					: null;
			log.info("江西电建离岗人员companyId:" + companyId);
			List<DepartmentModel> departmentList = null;
			Map<Long, List<DepartmentModel>> companyDepartments = userModel.getCompanyDepartments();
			if (null != companyDepartments) {
				departmentList = userModel.getCompanyDepartments().get(companyId);
			}
			if (departmentList != null && departmentList.get(0) != null) {
				departmentId = departmentList.get(0).getSequenceNbr();
				departmentOrgCode = departmentList.get(0).getOrgCode();
			}
			log.info("江西电建离岗人员departmentId:" + departmentId);
			log.info("江西电建离岗人员departmentOrgCode:" + departmentOrgCode);
			if (!platformUtils.isBelongDept(departmentId, companyId, "public")) {
				boolean hasChild = platformUtils.hasChild(departmentId);
				log.info("江西电建离岗人员是否有上级部门:" + hasChild);
				currentOrgCode = hasChild ? departmentOrgCode
						: departmentOrgCode.substring(0, departmentOrgCode.lastIndexOf("*"));
				log.info("江西电建离岗人员orgCode:" + currentOrgCode);
			}
			return currentOrgCode;
		} catch (Exception e) {
			return null;
		}
	}

	
	/**
	 * 获取项目二维码 type = "0 入场 1离场 2入岗 3离岗",
	 *
	 * @return
	 */
	@RequestMapping(value = "/getJoinQrCode", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = "获取加入部门二维码", notes = "获取加入部门二维码")
	public void getJoinQrCode(
			@RequestParam(value = "fileType", required = false, defaultValue = "png") String fileType,
			@RequestParam(value = "width", required = false, defaultValue = "20") String width,HttpServletResponse response) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(new Date());
		String token = smallProService.getSmallProToken();
//		String uuid = String.valueOf(projectId) + "_" + type;
//		redisUtil.set(Constant.SMALL_PRO_PRCODE + uuid, projectQrBaseVo);
		long uuid= System.currentTimeMillis();
		String page = "view/mine/JoinDepart";
		//String page = "view/mine/ClockIn";
		smallProService.getSmallProQrCodeResponse(token, String.valueOf(uuid), page, Long.valueOf(width), null, null, null, response,
				String.valueOf(uuid), fileType);
	}
}
