package com.yeejoin.amos.boot.module.jcs.biz.service.impl;

import java.net.ProtocolException;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yeejoin.amos.boot.biz.common.enums.RuleTypeEnum;
import com.yeejoin.amos.component.rule.config.ClazzUtils;
import com.yeejoin.amos.feign.rule.Rule;
import com.yeejoin.amos.feign.rule.client.RuleClient;
import com.yeejoin.amos.feign.rule.model.FactBaseModel;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.typroject.tyboot.core.foundation.utils.Bean;
import org.typroject.tyboot.core.foundation.utils.ValidationUtil;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;

import com.alibaba.fastjson.JSONArray;
import com.yeejoin.amos.boot.biz.common.utils.DateUtils;
import com.yeejoin.amos.boot.module.common.api.dto.FormValue;
import com.yeejoin.amos.boot.module.jcs.api.dto.AlertCallePowerTransferRo;
import com.yeejoin.amos.boot.module.jcs.api.dto.AlertCalledFormDto;
import com.yeejoin.amos.boot.module.jcs.api.dto.AlertCalledObjsDto;
import com.yeejoin.amos.boot.module.jcs.api.dto.AlertCalledRo;
import com.yeejoin.amos.boot.module.jcs.api.dto.PowerTransferCompanyDto;
import com.yeejoin.amos.boot.module.jcs.api.entity.AlertCalled;
import com.yeejoin.amos.boot.module.jcs.api.entity.AlertFormValue;
import com.yeejoin.amos.boot.module.jcs.api.enums.AlertStageEnums;
import com.yeejoin.amos.boot.module.jcs.api.enums.FireBrigadeTypeEnum;
import com.yeejoin.amos.component.rule.RuleTrigger;

/**
 * 
 * <pre>
 * 规则触发服务
 * </pre>
 *
 * @author gwb
 * @version $Id: RuleAlertCalledService.java, v 0.1 2021年6月24日 下午6:30:44 gwb Exp
 *          $
 */
@Service
public class RuleAlertCalledService {

	@Autowired
	private RuleTrigger ruleTrigger;

	@Autowired
	AlertCalledServiceImpl alertCalledServiceImpl;


	private static final String DANGEROUSEXPLOSIVES="dangerousExplosives";

	/**
	 *
	 * <pre>
	 * 触发警情报送规则
	 * </pre>
	 *
	 * @return
	 * @throws Exception
	 */
	public Boolean fireAlertCalledRule(AlertCalledObjsDto alertCalledVo,String alertWay, String mobiles,String usIds,String feedBack)  {
		AlertCalled alertCalled = alertCalledVo.getAlertCalled();
		if (ValidationUtil.isEmpty(alertCalled)) {
			throw new BadRequest("参数校验失败.");
		}
    	/**
    	 * 构建警情报送规则对象
    	 */
    	AlertCalledRo alertCalledRo = new AlertCalledRo();
		alertCalledRo.setFeedback(feedBack);

    	String replaceContent = init(alertCalledRo,alertCalledVo);

		// 警情 报送类型
		alertCalledRo.setAlertWay(alertWay);
		alertCalledRo.setReplaceContent(replaceContent);
		alertCalledRo.setUsIds(usIds);

		if(!ValidationUtil.isEmpty(mobiles)) {
			alertCalledRo.setIds(mobiles);
		}

		FactBaseModel factBaseModel = new FactBaseModel();
		factBaseModel.setPackageId("西咸机场119接处警规则/alertCalledRule");
		HashMap<String, byte[]> map = new HashMap<>();

		map.put("com.yeejoin.amos.boot.module.jcs.api.dto.AlertCalledRo", JSON.toJSON(alertCalledRo).toString().getBytes());

		factBaseModel.setFactMap(map);
		Rule.ruleClient.fireRule(factBaseModel);
		return true;
	}


	public static String init(AlertCalledRo alertCalledRo , AlertCalledObjsDto alertCalledVo ) {
		AlertCalled alertCalled = alertCalledVo.getAlertCalled();
		//通用属性
		alertCalledRo.setSequenceNbr(String.valueOf(alertCalled.getSequenceNbr()));
		alertCalledRo.setAddress(alertCalled.getAddress());
		alertCalledRo.setUnitInvolved(alertCalled.getUnitInvolved());
		alertCalledRo.setContactUser(alertCalled.getContactUser());
		alertCalledRo.setContactPhone(alertCalled.getContactPhone());
		alertCalledRo.setAlertType(alertCalled.getAlertType());
		alertCalledRo.setAlertTypeCode(alertCalled.getAlertTypeCode());
		alertCalledRo.setCasualtiesNum(alertCalled.getCasualtiesNum() != null ? String.valueOf(alertCalled.getCasualtiesNum()) : "无");
		alertCalledRo.setTrappedNum(alertCalled.getTrappedNum() != null ? String.valueOf(alertCalled.getTrappedNum()) : "无");
		alertCalledRo.setCompanyName(alertCalled.getCompanyName());

		List<AlertFormValue> alertFormValues = alertCalledVo.getAlertFormValue();

		if (!ValidationUtil.isEmpty(alertFormValues))
		{
			for (AlertFormValue alertFormValue : alertFormValues)
			{
				if (alertFormValue.getFieldCode().equals("alertSubmittedId"))
				{
					alertCalledRo.setAlertSubmittedId(alertFormValue.getFieldValue());
				}
				//一般火灾
				if (alertFormValue.getFieldCode().equals("fireLocation"))
				{
					alertCalledRo.setFireLocation(alertFormValue.getFieldValue());
				}
				if (alertFormValue.getFieldCode().equals("burningMaterial"))
				{
					alertCalledRo.setBurningMaterial(alertFormValue.getFieldValue());
				}
				if (alertFormValue.getFieldCode().equals("fireSituation"))
				{
					alertCalledRo.setFireSituation(alertFormValue.getFieldValue());
				}
				if (alertFormValue.getFieldCode().equals(DANGEROUSEXPLOSIVES))
				{
					alertCalledRo.setDangerousExplosives(alertFormValue.getFieldValue());
				}
				if (alertFormValue.getFieldCode().equals("fireTime"))
				{
					alertCalledRo.setCallTimeStr(alertFormValue.getFieldValue());
				}
				//航空器救援
				if (alertFormValue.getFieldCode().equals("flightNumber")) {
					alertCalledRo.setFlightNumber(ValidationUtil.isEmpty(alertFormValue.getFieldValueCode()) ?  alertFormValue.getFieldValue() : alertFormValue.getFieldValueCode());
				}
				if (alertFormValue.getFieldCode().equals("aircraftModel")) {
					alertCalledRo.setAircraftModel(ValidationUtil.isEmpty(alertFormValue.getFieldValueCode()) ?  alertFormValue.getFieldValue() : alertFormValue.getFieldValueCode());
				}
				if (alertFormValue.getFieldCode().equals("landingTime")) {
					alertCalledRo.setLandingTime(alertFormValue.getFieldValue());
				}
				if (alertFormValue.getFieldCode().equals("developmentTrend")) {
					alertCalledRo.setDevelopmentTrend(alertFormValue.getFieldValue());
				}
				if (alertFormValue.getFieldCode().equals("fuelQuantity")) {
					alertCalledRo.setFuelQuantity(alertFormValue.getFieldValue());
				}
				if (alertFormValue.getFieldCode().equals("passengerCapacity")) {
					alertCalledRo.setPassengerCapacity(alertFormValue.getFieldValue());
				}
				if (alertFormValue.getFieldCode().equals("damageLocation")) {
					alertCalledRo.setDamageLocation(alertFormValue.getFieldValue());
				}
				if (alertFormValue.getFieldCode().equals("forcedLandingTrack")) {
					alertCalledRo.setForcedLandingTrack(alertFormValue.getFieldValue());
				}
				if (alertFormValue.getFieldCode().equals("accidentSituation")) {
					alertCalledRo.setAccidentSituationHkq(alertFormValue.getFieldValue());
				}

				//突发事件救援
				if (alertFormValue.getFieldCode().equals("accidentSituation")) {
					alertCalledRo.setAccidentSituation(alertFormValue.getFieldValue());
				}

				//漏油现场安全保障
				if (alertFormValue.getFieldCode().equals("flightNumber")) {
					alertCalledRo.setFlightNumberLy(ValidationUtil.isEmpty(alertFormValue.getFieldValueCode()) ?  alertFormValue.getFieldValue() : alertFormValue.getFieldValueCode());
				}
				if (alertFormValue.getFieldCode().equals("seat")) {
					alertCalledRo.setSeat(alertFormValue.getFieldValue());
				}
				if (alertFormValue.getFieldCode().equals("oilLeakageArea")) {
					alertCalledRo.setOilLeakageArea(alertFormValue.getFieldValue());
				}

				//专机保障
				if (alertFormValue.getFieldCode().equals("securityLevel")) {
					alertCalledRo.setSecurityLevel(alertFormValue.getFieldValue());
				}
				if (alertFormValue.getFieldCode().equals("seat")) {
					alertCalledRo.setSeatBz(alertFormValue.getFieldValue());
				}

				//120 急救
				if (alertFormValue.getFieldCode().equals("patientStatus")) {
					alertCalledRo.setPatientStatus(alertFormValue.getFieldValue());
				}
				if (alertFormValue.getFieldCode().equals("gender")) {
					alertCalledRo.setGender(alertFormValue.getFieldValue());
				}
				if (alertFormValue.getFieldCode().equals("ageGroup")) {
					alertCalledRo.setAgeGroup(alertFormValue.getFieldValue());
				}
			}
		}

		// 警情初报模板替换规则
		String replaceContent = "";
		if(alertCalled.getAlertTypeCode().equals(AlertStageEnums.YBHZ.getCode())) {
			replaceContent  =  "失火位置：".concat(ValidationUtil.isEmpty(alertCalledRo.getFireLocation()) ? "无": alertCalledRo.getFireLocation()).concat(
					"；燃烧物质：").concat(ValidationUtil.isEmpty(alertCalledRo.getBurningMaterial() )?  "无": alertCalledRo.getBurningMaterial()).concat(
					"；火势情况：").concat(ValidationUtil.isEmpty(alertCalledRo.getFireSituation() ) ? "无" : alertCalledRo.getFireSituation());
		}

		if(alertCalled.getAlertTypeCode().equals(AlertStageEnums.HKJY.getCode())) {
			replaceContent  =  "航班号：".concat(ValidationUtil.isEmpty(alertCalledRo.getFlightNumber()) ? "无": alertCalledRo.getFlightNumber()).concat(
					"；飞机型号：").concat(ValidationUtil.isEmpty(alertCalledRo.getAircraftModel() )?  "无": alertCalledRo.getAircraftModel()).concat(
					"；落地时间：").concat(ValidationUtil.isEmpty(alertCalledRo.getLandingTime() ) ? "无" : alertCalledRo.getLandingTime()).concat(
					"发生".concat(ValidationUtil.isEmpty(alertCalledRo.getAccidentSituationHkq()) ? "无": alertCalledRo.getAccidentSituationHkq()).concat(
							"；飞机受损位置：").concat(ValidationUtil.isEmpty(alertCalledRo.getDamageLocation() )?  "无": alertCalledRo.getDamageLocation()).concat(
							"；燃油量：").concat(ValidationUtil.isEmpty(alertCalledRo.getFuelQuantity() ) ? "无" : alertCalledRo.getFuelQuantity()).concat(
							"载客量：".concat(ValidationUtil.isEmpty(alertCalledRo.getPassengerCapacity()) ? "无": alertCalledRo.getPassengerCapacity()).concat(
									"；迫降跑道：").concat(ValidationUtil.isEmpty(alertCalledRo.getForcedLandingTrack() )?  "无": alertCalledRo.getForcedLandingTrack()).concat(
									"；发展态势：").concat(ValidationUtil.isEmpty(alertCalledRo.getDevelopmentTrend() ) ? "无" : alertCalledRo.getDevelopmentTrend())
					));
		}

		if(alertCalled.getAlertTypeCode().equals(AlertStageEnums.TFSJ.getCode())) {
			replaceContent  =  "发生：".concat(ValidationUtil.isEmpty(alertCalledRo.getAccidentSituation()) ? "无": alertCalledRo.getAccidentSituation().concat("事件"));
		}

		if(alertCalled.getAlertTypeCode().equals(AlertStageEnums.LYXC.getCode())) {
			replaceContent  =  "航班号：".concat(ValidationUtil.isEmpty(alertCalledRo.getFlightNumberLy()) ? "无": alertCalledRo.getFlightNumberLy()).concat(
					"；机位：").concat(ValidationUtil.isEmpty(alertCalledRo.getSeat() )?  "无": alertCalledRo.getSeat()).concat(
					"；漏油面积：").concat(ValidationUtil.isEmpty(alertCalledRo.getOilLeakageArea() ) ? "无" : alertCalledRo.getOilLeakageArea());
		}

		if(alertCalled.getAlertTypeCode().equals(AlertStageEnums.ZJBZ.getCode())) {
			replaceContent  =  "保障等级：".concat(ValidationUtil.isEmpty(alertCalledRo.getSecurityLevel()) ? "无": alertCalledRo.getSecurityLevel()).concat(
					"；机位：").concat(ValidationUtil.isEmpty(alertCalledRo.getSeatBz() )?  "无": alertCalledRo.getSeatBz());
		}

		if(alertCalled.getAlertTypeCode().equals(AlertStageEnums.JJJQ.getCode())) {
			replaceContent  =  "患者现状：".concat(ValidationUtil.isEmpty(alertCalledRo.getPatientStatus()) ? "无": alertCalledRo.getPatientStatus()).concat(
					"；性别：").concat(ValidationUtil.isEmpty(alertCalledRo.getGender() )?  "无": alertCalledRo.getGender()).concat(
					"；年龄段：").concat(ValidationUtil.isEmpty(alertCalledRo.getAgeGroup() ) ? "无" : alertCalledRo.getAgeGroup());
		}

		return replaceContent;
	}

	public boolean powerTransferCalledRule(Set<PowerTransferCompanyDto> i, Long alertCalledId, String type,String companyName) throws Exception {
		if (ValidationUtil.isEmpty(alertCalledId)) {
			throw new BadRequest("参数校验失败.");
		}
		AlertCallePowerTransferRo alertCallePowerTransferRo = new AlertCallePowerTransferRo();

		AlertCalledFormDto alertCalledFormDto = (AlertCalledFormDto) alertCalledServiceImpl
				.selectAlertCalledByIdNoRedis(alertCalledId);
		
		alertCallePowerTransferRo.setAlertSubmittedId(Long.toString(alertCalledId));
		if (alertCalledFormDto == null) {
			return false;
		}


		AlertCalled alertCalled = alertCalledFormDto.getAlertCalled();
		alertCallePowerTransferRo
				.setCallTimeStr(DateUtils.convertDateToString(alertCalled.getCallTime(), DateUtils.DATE_TIME_PATTERN));
		alertCallePowerTransferRo.setSequenceNbr(String.valueOf(alertCalled.getSequenceNbr()));
		alertCallePowerTransferRo.setAddress(alertCalled.getAddress());
		alertCallePowerTransferRo.setAlertType(alertCalled.getAlertType());
		alertCallePowerTransferRo.setAlertTypeCode(alertCalled.getAlertTypeCode());
		alertCallePowerTransferRo.setCompanyName(companyName);
		alertCallePowerTransferRo.setTrappedNum(Integer.toString(alertCalled.getTrappedNum()));
		alertCallePowerTransferRo.setCasualtiesNum(Integer.toString(alertCalled.getCasualtiesNum()));
		alertCallePowerTransferRo.setContactPhone(alertCalled.getContactPhone());
		alertCallePowerTransferRo.setContactUser(alertCalled.getContactUser());
		String presentSituation =null;//性别
		String gender =null;//年龄段(岁)
		String ageGroup =null;//患者现状说明
		String dangerousExplosives=null;//危险爆炸品
		List<FormValue> alertFormValues = alertCalledFormDto.getDynamicFormAlert();
		if (!ValidationUtil.isEmpty(alertFormValues)) {
			for (FormValue alertFormValue : alertFormValues) {
				// 一般火灾
				if (alertFormValue.getKey().equals("fireLocation")) {
					alertCallePowerTransferRo.setFireLocation(alertFormValue.getValue());
				}
				if (alertFormValue.getKey().equals("burningSubstancesDescription")) {
					alertCallePowerTransferRo.setBurningMaterial(alertFormValue.getValue());
				}
				if (alertFormValue.getKey().equals("fireSituation")) {
					alertCallePowerTransferRo.setFireSituation(alertFormValue.getValue());
				}
				if (alertFormValue.getKey().equals(DANGEROUSEXPLOSIVES)) {
					alertCallePowerTransferRo.setDangerousExplosives(alertFormValue.getValue());
				}
				if (alertFormValue.getKey().equals("fireTime")) {
					alertCallePowerTransferRo.setCallTimeStr(alertFormValue.getValue());
				}
				if (alertFormValue.getKey().equals("presentSituation")) {
					presentSituation = alertFormValue.getValue();
				}
				if (alertFormValue.getKey().equals("gender")) {
					gender = alertFormValue.getValue();
				}
				if (alertFormValue.getKey().equals("ageGroup")) {
					ageGroup = alertFormValue.getValue();
				}
				if (alertFormValue.getKey().equals(DANGEROUSEXPLOSIVES)) {
					dangerousExplosives = alertFormValue.getValue();
				}
			}
		}
		if (FireBrigadeTypeEnum.专职消防队.getKey().equals(type)||FireBrigadeTypeEnum.监控大队.getKey().equals(type)) {
			alertCallePowerTransferRo.setCompany(JSON.toJSONString(i));
			alertCallePowerTransferRo.setPowerTransType(type);
			StringBuilder stringBuffer = new StringBuilder();
			stringBuffer.append(" 失火位置："+alertCallePowerTransferRo.getFireLocation());
			stringBuffer.append(" 燃烧物质："+alertCallePowerTransferRo.getBurningMaterial());
			stringBuffer.append(" 火势情况："+alertCallePowerTransferRo.getFireSituation());
			stringBuffer.append(" 有无危险爆炸品："+dangerousExplosives);
			alertCallePowerTransferRo.setContent(stringBuffer.toString());

		} else if (FireBrigadeTypeEnum.医疗救援队.getKey().equals(type)) {
			alertCallePowerTransferRo.setCompany(JSON.toJSONString(i));
			alertCallePowerTransferRo.setPowerTransType(type);
			StringBuilder stringBuffer = new StringBuilder();
			stringBuffer.append(" 患者现状："+ageGroup==null?"无":ageGroup);
			stringBuffer.append(" 性别："+presentSituation==null?"无":presentSituation);
			stringBuffer.append(" 年龄段："+gender==null?"无":gender);
			alertCallePowerTransferRo.setContent(stringBuffer.toString());
		}
		// 触发规则
		 ruleTrigger.publish(alertCallePowerTransferRo, "西咸机场119接处警规则/powerTransferCalledRule", new String[0]);  // 废弃


		return true;

	}

}
