package com.yeejoin.amos.api.openapi.face.service;

import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.typroject.tyboot.component.emq.EmqKeeper;
import org.typroject.tyboot.core.foundation.utils.Bean;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.rdbms.service.BaseService;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yeejoin.amos.api.common.restful.utils.ResponseModel;
import com.yeejoin.amos.api.openapi.enums.LiftCircuitStatusEnum;
import com.yeejoin.amos.api.openapi.enums.LiftContactorStatusEnum;
import com.yeejoin.amos.api.openapi.enums.LiftDirectionEnum;
import com.yeejoin.amos.api.openapi.enums.LiftDoorStatusEnum;
import com.yeejoin.amos.api.openapi.enums.LiftPersonFlagEnum;
import com.yeejoin.amos.api.openapi.enums.LiftServiceModelEnum;
import com.yeejoin.amos.api.openapi.enums.LiftStatusEnum;
import com.yeejoin.amos.api.openapi.face.model.ElevatorStatusModel;
import com.yeejoin.amos.api.openapi.face.model.ElevatorVideoModel;
import com.yeejoin.amos.api.openapi.face.orm.dao.ElevatorStatusMapper;
import com.yeejoin.amos.api.openapi.face.orm.entity.ElevatorStatus;

import net.sf.json.JSONObject;

/**
 * 
 * <pre>
 * 电梯运行状态表 服务类
 * </pre>
 *
 * @author gwb
 * @version $Id: ElevatorStatusService.java, v 0.1 2021年9月28日 下午7:55:18 gwb Exp $
 */
@Component
public class ElevatorStatusService extends
		BaseService<ElevatorStatusModel, ElevatorStatus, ElevatorStatusMapper>
{

	private static final Logger logger = LoggerFactory.getLogger(ElevatorStatusService.class);
	
	@Autowired
	private RestTemplate restTemplate;
	
	@Lazy
    @Autowired
    private EmqKeeper emqKeeper;
	
	@Value("${biz.lxyd.lift.url}")
	private String lxydLiftUrl;
	
	/**
	 * 
	 * <pre>
	 * 批量保存电梯运行状态信息
	 * </pre>
	 *
	 * @param models
	 * @return
	 * @throws Exception
	 */
	public String multCreateElevatorStatus(List<ElevatorStatusModel> models) throws Exception
	{

		if (ValidationUtil.isEmpty(models))
			throw new BadRequest("上报电梯状态数据为空.");

		for (ElevatorStatusModel elevatorStatusModel : models)
		{
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			elevatorStatusModel.setUploadDate(
					elevatorStatusModel.getUploadTime()!= null? sdf.parse(elevatorStatusModel.getUploadTime()): null);
			
			List<ElevatorStatusModel> oldModel = queryModelByCodeAndStatusId(elevatorStatusModel.getRegisterCode(), elevatorStatusModel.getStatusId());
			//如果存在该状态编码则不进行发送
			if (ValidationUtil.isEmpty(oldModel))
			{
				//实时消息发送
				ObjectMapper mapper = new ObjectMapper();
				String resultJson = mapper.writeValueAsString(builEnumName(elevatorStatusModel));
				emqKeeper.getMqttClient().publish("openapi/lift/runStatusData" ,resultJson.getBytes(), 2 ,false);
			}
			elevatorStatusModel = this.createWithModel(elevatorStatusModel);
		}

		return "OK";
	}
	
	/**
	 * 
	 * <pre>
	 * 查询电梯最新一条状态数据
	 * </pre>
	 *
	 * @param registerCode 电梯注册码
	 * @param highUpload 是否开启高频上传
	 * @return
	 * @throws Exception
	 */
	public ElevatorStatusModel getLatelyStatus(String registerCode, Boolean highUpload) throws Exception
	{
		ElevatorStatusModel elevatorStatusModel = null;
		ElevatorStatus elevatorStatus = baseMapper.getLatelyStatus(registerCode);
		if (!ValidationUtil.isEmpty(elevatorStatus))
		{
			elevatorStatusModel = Bean.toModel(elevatorStatus, new ElevatorStatusModel());
			elevatorStatusModel = builEnumName(elevatorStatusModel);
			//开启高频上传
			if (highUpload)
			{
				this.highUpload(registerCode);
			}
		}else 
		{
			elevatorStatusModel = new ElevatorStatusModel();
		}
		return elevatorStatusModel;
	}
	
	
	
	/**
	 * 
	 * <pre>
	 * 高频上传状态数据请求
	 * </pre>
	 *
	 * @throws Exception
	 */
	public void highUpload(String registerCode) throws Exception
	{
		HttpHeaders headers = new HttpHeaders();
		headers.add("Content-Type", "application/json");
		SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
		factory.setConnectTimeout(30000);
		factory.setReadTimeout(30000);
		restTemplate.setRequestFactory(factory);
		
		HttpEntity<String> request = new HttpEntity<String>(headers);
		logger.info("发起电梯运行状态高频请求，电梯注册码：" + registerCode);
		restTemplate.exchange(lxydLiftUrl + "/lift/runstatus?registerCode=" + registerCode, HttpMethod.GET, request, String.class);
		
	}
	
	/**
	 * 
	 * <pre>
	 * 获取电梯视频播放地址
	 * </pre>
	 *
	 * @throws Exception
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public ElevatorVideoModel videoPreview(String registerCode) throws Exception
	{
		HttpHeaders headers = new HttpHeaders();
		MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
		headers.setContentType(type);
		headers.add("Content-Type", "application/json");
		SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
		factory.setConnectTimeout(30000);
		factory.setReadTimeout(30000);
		restTemplate.setRequestFactory(factory);
		
		HttpEntity<String> request = new HttpEntity<String>(headers);
		logger.info("获取电梯视频播放地址，电梯注册码：" + registerCode);
		String responseJson = restTemplate.exchange(lxydLiftUrl + "/lift/video/preview?registerCode=" + registerCode, HttpMethod.GET, request, String.class).getBody();
		JSONObject jsonobject = JSONObject.fromObject(responseJson);
		Map<String, Class> classMap = new HashMap<String, Class>();
		classMap.put("result", ElevatorVideoModel.class);
		ResponseModel<ElevatorVideoModel> responseModel =  (ResponseModel<ElevatorVideoModel>)JSONObject.toBean(jsonobject,ResponseModel.class,classMap);
		ElevatorVideoModel elevatorVideoModel = new ElevatorVideoModel();
		elevatorVideoModel.setRegisterCode(registerCode);
		if (responseModel.getStatus() == HttpStatus.OK.value())
		{
			elevatorVideoModel = responseModel.getResult();
		}
		return elevatorVideoModel;
	}

	/**
	 * 
	 * <pre>
	 * 根据电梯注册编码和故障编码查询电梯故障信息
	 * </pre>
	 *
	 * @param registerCode
	 * @param faultId
	 */
	private List<ElevatorStatusModel> queryModelByCodeAndStatusId(String registerCode, String statusId)
	{
		return this.queryForList("upload_date", false,registerCode, statusId);
	}
	
	private ElevatorStatusModel builEnumName(ElevatorStatusModel elevatorStatusModel)
	{
		//总接触器吸合或是断开
		elevatorStatusModel.setMainContactorName(String.valueOf(elevatorStatusModel.getMainContactor()));
		if (!ValidationUtil.isEmpty(elevatorStatusModel.getMainContactor()) && 
				!ValidationUtil.isEmpty(LiftContactorStatusEnum.getEnum(elevatorStatusModel.getMainContactor())))
		{
			elevatorStatusModel.setMainContactorName(LiftContactorStatusEnum.getEnum(elevatorStatusModel.getMainContactor()).getName());
		}
		//运行接触器吸合或是断开
		elevatorStatusModel.setRunContactorName(String.valueOf(elevatorStatusModel.getRunContactor()));
		if (!ValidationUtil.isEmpty(elevatorStatusModel.getRunContactor()) && 
				!ValidationUtil.isEmpty(LiftContactorStatusEnum.getEnum(elevatorStatusModel.getRunContactor())))
		{
			elevatorStatusModel.setRunContactorName(LiftContactorStatusEnum.getEnum(elevatorStatusModel.getRunContactor()).getName());
		}
		//安全回路是否断开
		elevatorStatusModel.setCircuitName(String.valueOf(elevatorStatusModel.getCircuit()));
		if (!ValidationUtil.isEmpty(elevatorStatusModel.getCircuit()) && 
				!ValidationUtil.isEmpty(LiftCircuitStatusEnum.getEnum(elevatorStatusModel.getCircuit())))
		{
			elevatorStatusModel.setCircuitName(LiftCircuitStatusEnum.getEnum(elevatorStatusModel.getCircuit()).getName());
		}
		//当前电梯运行模式
		elevatorStatusModel.setServiceModelName(String.valueOf(elevatorStatusModel.getServiceModel()));
		if (!ValidationUtil.isEmpty(elevatorStatusModel.getServiceModel()) && 
				!ValidationUtil.isEmpty(LiftServiceModelEnum.getEnum(elevatorStatusModel.getServiceModel())))
		{
			elevatorStatusModel.setServiceModelName(LiftServiceModelEnum.getEnum(elevatorStatusModel.getServiceModel()).getName());
		}
		//轿厢运行状态
		elevatorStatusModel.setLiftStatusName(String.valueOf(elevatorStatusModel.getLiftStatus()));
		if (!ValidationUtil.isEmpty(elevatorStatusModel.getLiftStatus()) && 
				!ValidationUtil.isEmpty(LiftStatusEnum.getEnum(elevatorStatusModel.getLiftStatus())))
		{
			elevatorStatusModel.setLiftStatusName(LiftStatusEnum.getEnum(elevatorStatusModel.getLiftStatus()).getName());
		}
		//轿厢运行方向
		elevatorStatusModel.setLiftDirectionName(String.valueOf(elevatorStatusModel.getLiftDirection()));
		if (!ValidationUtil.isEmpty(elevatorStatusModel.getLiftDirection()) && 
				!ValidationUtil.isEmpty(LiftDirectionEnum.getEnum(elevatorStatusModel.getLiftDirection())))
		{
			elevatorStatusModel.setLiftDirectionName(LiftDirectionEnum.getEnum(elevatorStatusModel.getLiftDirection()).getName());
		}
		//关门到位
		elevatorStatusModel.setDoorStatusName(String.valueOf(elevatorStatusModel.getDoorStatus()));
		if (!ValidationUtil.isEmpty(elevatorStatusModel.getDoorStatus()) && 
				!ValidationUtil.isEmpty(LiftDoorStatusEnum.getEnum(elevatorStatusModel.getDoorStatus())))
		{
			elevatorStatusModel.setDoorStatusName(LiftDoorStatusEnum.getEnum(elevatorStatusModel.getDoorStatus()).getName());
		}
		//轿厢内是否有人
		elevatorStatusModel.setPersonFlagName(String.valueOf(elevatorStatusModel.getPersonFlag()));
		if (!ValidationUtil.isEmpty(elevatorStatusModel.getPersonFlag()) && 
				!ValidationUtil.isEmpty(LiftPersonFlagEnum.getEnum(elevatorStatusModel.getPersonFlag())))
		{
			elevatorStatusModel.setPersonFlagName(LiftPersonFlagEnum.getEnum(elevatorStatusModel.getPersonFlag()).getName());
		}
		return elevatorStatusModel;
	}
}
