package com.yeejoin.precontrol.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yeejoin.precontrol.common.entity.Person;
import com.yeejoin.precontrol.common.entity.PersonAscription;
import com.yeejoin.precontrol.common.entity.PersonClock;
import com.yeejoin.precontrol.common.entity.Project;
import com.yeejoin.precontrol.common.entity.ProjectDevice;
import com.yeejoin.precontrol.common.entity.access.AccessInfo;
import com.yeejoin.precontrol.common.entity.access.CommInfo;
import com.yeejoin.precontrol.common.entity.access.DoorOpenAndShowTips;
import com.yeejoin.precontrol.common.entity.access.Event;
import com.yeejoin.precontrol.common.entity.access.HttpAccessVerifyParam;
import com.yeejoin.precontrol.common.entity.access.HttpAccessVerifyResult;
import com.yeejoin.precontrol.common.entity.access.PersonInfo;
import com.yeejoin.precontrol.common.entity.access.PictureAck;
import com.yeejoin.precontrol.common.entity.access.RecognizeResult;
import com.yeejoin.precontrol.common.exception.BaseException;
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.IPersonService;
import com.yeejoin.precontrol.common.service.IProjectDeviceService;
import com.yeejoin.precontrol.common.service.IProjectService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.annotations.ApiIgnore;

/**
 * 门禁
 *
 * @author duanwei
 * @date 2020-07-06
 */
@RestController
@ApiIgnore
@Api(tags = " 门禁")
@RequestMapping(value = "/access", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class AccessController {

	@Autowired
	IPersonAccessService iPersonAccessService;

	@Autowired
	IPersonService iPersonService;

	@Autowired
	IProjectDeviceService iProjectDeviceService;

	@Autowired
	IPersonAscriptionService iPersonAscriptionService;

	@Autowired
	IProjectService iProjectService;

	@Autowired
	IPersonClockService iPersonClockService;

	/**
	 * 门禁信令连接
	 *
	 * @return
	 */
	@RequestMapping(value = "/connect", method = RequestMethod.GET)
	@ApiOperation(httpMethod = "GET", value = " 门禁信令连接", notes = "门禁信令连接")
	public Object connect() {
		System.out.println("门禁心跳运行中...");
		return null;
	}

	/**
	 * 人脸认证推送
	 *
	 * @return
	 */
	@RequestMapping(value = "/faceVerify", method = RequestMethod.POST)
	@ApiOperation(httpMethod = "POST", value = "人脸认证推送", notes = "人脸认证推送")
	public Object faceVerify(String json) {
		System.out.println(json);
		HttpAccessVerifyParam param = JSONObject.parseObject(json, HttpAccessVerifyParam.class);
		int PicID = param.getPicID();
		List<Event> Events = param.getEvents();
		List<RecognizeResult> RecognizeResults = Events.get(0).getRecognizeResults();
		AccessInfo AccessInfo = Events.get(0).getAccessInfo();
		CommInfo CommInfo = Events.get(0).getCommInfo();
		HttpAccessVerifyResult result = new HttpAccessVerifyResult();
		if (AccessInfo.getPassResult() == 1) {
			ProjectDevice projectDevice = iProjectDeviceService.getOne(
					new LambdaQueryWrapper<ProjectDevice>().eq(ProjectDevice::getNumber, CommInfo.getSerialNo()));
			PersonInfo personInfo = RecognizeResults.get(0).getPersonInfo();
			PictureAck pictureAck = new PictureAck();
			pictureAck.setPicID(PicID);
			pictureAck.setResult(true);
			DoorOpenAndShowTips doorOpenAndShowTips = new DoorOpenAndShowTips();
			doorOpenAndShowTips.setType("both");
			if (projectDevice == null) {
				doorOpenAndShowTips.setCustomtip("设备未绑定项目");
			} else {
				Person person = iPersonService
						.getOne(new LambdaQueryWrapper<Person>().eq(Person::getUserId, personInfo.getID()));
				try {
					if ("入向".equals(projectDevice.getDirect())) {
						iPersonAccessService.enterJudge(person,projectDevice.getProjectId());
						doorOpenAndShowTips.setCustomtip("入场成功");
						saveClock(person, 0);
					} else if ("出向".equals(projectDevice.getDirect())) {
						doorOpenAndShowTips.setCustomtip("出场成功");
						saveClock(person, 1);
					} else {
						doorOpenAndShowTips.setCustomtip("设备未选择方向");
					}
				} catch (BaseException e) {
					doorOpenAndShowTips.setCustomtip(e.getMessage());
				}
			}
			result.setPictureAck(pictureAck);
			result.setDoorOpenAndShowTips(doorOpenAndShowTips);
		} else if (AccessInfo.getPassResult() == 16) {
			PictureAck pictureAck = new PictureAck();
			pictureAck.setPicID(PicID);
			pictureAck.setResult(true);
			DoorOpenAndShowTips doorOpenAndShowTips = new DoorOpenAndShowTips();
			doorOpenAndShowTips.setType("both");
			doorOpenAndShowTips.setCustomtip("未识别的人员");
			result.setPictureAck(pictureAck);
			result.setDoorOpenAndShowTips(doorOpenAndShowTips);
		}
		return JSONObject.toJSON(result);
	}

	private void saveClock(Person person,int direct) {
		PersonAscription personAscription = iPersonAscriptionService
				.getOne(new LambdaQueryWrapper<PersonAscription>().eq(PersonAscription::getPersonId, person.getId()));
		Project project = iProjectService
				.getOne(new LambdaQueryWrapper<Project>().eq(Project::getId, personAscription.getProjectId()));
		PersonClock personClock = new PersonClock();
		personClock.setPersonId(Long.valueOf(person.getId()));
		personClock.setInOrOut(direct);
		try {
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
			personClock.setClockDate(dateFormat.parse(dateFormat.format(new Date())));
		} catch (ParseException e) {
			throw new BaseException("日期转换错误");
		}
		personClock.setClockCompanyId(personAscription != null ? personAscription.getCompanyId() : null);
		personClock.setClockTime(new Date());
		personClock
				.setClockProjectId(personAscription != null ? String.valueOf(personAscription.getProjectId()) : null);
		personClock.setClockProject(project.getName());
		personClock.setClockAddress(project.getAddress());
		personClock.setOrgCode(person.getOrgCode());
		iPersonClockService.save(personClock);
	}
}
