package com.hzya.frame.sysnew.warningConfig.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hzya.frame.sysnew.application.dao.ISysApplicationDao;
import com.hzya.frame.sysnew.application.entity.SysApplicationEntity;
import com.hzya.frame.sysnew.messageTemplate.dao.ISysMessageTemplateDao;
import com.hzya.frame.sysnew.messageTemplate.entity.SysMessageTemplateEntity;
import com.hzya.frame.sysnew.person.dao.ISysPersonDao;
import com.hzya.frame.sysnew.person.entity.SysPersonEntity;
import com.hzya.frame.sysnew.user.dao.ISysUserDao;
import com.hzya.frame.sysnew.user.entity.SysUserEntity;
import com.hzya.frame.sysnew.warningConfig.entity.SysWarningConfigEntity;
import com.hzya.frame.sysnew.warningConfig.dao.ISysWarningConfigDao;
import com.hzya.frame.sysnew.warningConfig.service.ISysWarningConfigService;
import com.hzya.frame.sysnew.warningInterface.dao.ISysWarningInterfaceDao;
import com.hzya.frame.sysnew.warningInterface.entity.SysWarningInterfaceEntity;
import com.hzya.frame.web.entity.BaseResult;
import com.hzya.frame.web.entity.JsonResultEntity;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import javax.annotation.Resource;
import com.hzya.frame.basedao.service.impl.BaseService;

import java.util.ArrayList;
import java.util.List;

/**
 * 预警配置表(SysWarningConfig)表服务实现类
 *
 * @author makejava
 * @since 2024-09-03 09:28:23
 */
@Service(value = "sysWarningConfigService")
public class SysWarningConfigServiceImpl extends BaseService<SysWarningConfigEntity, String> implements ISysWarningConfigService {

	@Resource
	private ISysWarningInterfaceDao sysWarningInterfaceDao;
	@Resource
	private ISysUserDao sysUserDao;
	@Resource
	private ISysPersonDao sysPersonDao;

	@Resource
	private ISysApplicationDao sysApplicationDao;

	@Resource
	private ISysMessageTemplateDao sysMessageTemplateDao;

    private ISysWarningConfigDao sysWarningConfigDao;
    
    @Autowired
	public void setSysWarningConfigDao(ISysWarningConfigDao dao) {
		this.sysWarningConfigDao = dao;
		this.dao = dao;
	}

	@Override
	public JsonResultEntity queryEntityPage(JSONObject jsonObject){
		SysWarningConfigEntity entity = getData("jsonStr", jsonObject, SysWarningConfigEntity.class);
		if(entity == null || entity.getPageSize() == null || entity.getPageNum() == null){
			return BaseResult.getFailureMessageEntity("分页查询参数不存在");
		}
		PageHelper.startPage(entity.getPageNum(), entity.getPageSize());
		List<SysWarningConfigEntity> list = sysWarningConfigDao.queryByLike(entity);
		//查询并记录应用名称、预警应用名称、接收者名称列表
		List<SysWarningConfigEntity> resultList = queryNameList(list);
		PageInfo pageInfo = new PageInfo(resultList);
		return BaseResult.getSuccessMessageEntity("查询数据成功",pageInfo);
	}

	@Override
	public JsonResultEntity queryEntity(JSONObject jsonObject){
		SysWarningConfigEntity entity = getData("jsonStr", jsonObject, SysWarningConfigEntity.class);
		if(entity == null){
			entity = new SysWarningConfigEntity();
		}
		List<SysWarningConfigEntity> list = sysWarningConfigDao.queryByLike(entity);
		//查询并记录应用名称、预警应用名称、接收者名称列表
		List<SysWarningConfigEntity> resultList = queryNameList(list);
		return BaseResult.getSuccessMessageEntity("查询数据成功",resultList);
	}
	/**查询应用名称、预警应用名称、接收者名称列表*/

	@Override
	public JsonResultEntity getEntity(JSONObject jsonObject){
		SysWarningConfigEntity entity = getData("jsonStr", jsonObject, SysWarningConfigEntity.class);
		if(entity == null){
			return BaseResult.getFailureMessageEntity("参数不允许为空");
		}
		if(entity.getId() == null || "".equals(entity.getId())){
			return BaseResult.getFailureMessageEntity("系统错误");
		}
		//查询主表信息
		 entity = sysWarningConfigDao.get(entity.getId());
		if(entity == null){
			return BaseResult.getFailureMessageEntity("获取预警配置失败");
		}
		List<SysWarningConfigEntity> list = new ArrayList<>();
		list.add(entity);
		//查询并记录应用名称、预警应用名称、接收者名称列表
		List<SysWarningConfigEntity> resultList = queryNameList(list);
		String warningConfigId = resultList.get(0).getId();
		//查询子表信息
		SysWarningInterfaceEntity interfaceEntity = new SysWarningInterfaceEntity();
		interfaceEntity.setWarningConfigId(warningConfigId);
		List<SysWarningInterfaceEntity> interfaceList = sysWarningInterfaceDao.queryByLike(interfaceEntity);
		//拼接主子表信息并返回
		JSONObject father = (JSONObject) JSONObject.toJSON(resultList.get(0));
		JSONArray sonArray = new JSONArray();
        for(SysWarningInterfaceEntity interfaceOne : interfaceList){
			JSONObject interfaceJson = (JSONObject) JSONObject.toJSON(interfaceOne);
			sonArray.add(interfaceJson);
		}
		JSONObject resultJson = new JSONObject();
		resultJson.put("father", father);
		resultJson.put("son", sonArray);
		return BaseResult.getSuccessMessageEntity("获取预警配置成功",resultJson);
	}

	@Override
	public JsonResultEntity saveEntity(JSONObject jsonObject){
		JSONObject jsonStr = jsonObject.getJSONObject("jsonStr");
		JSONArray sonArray = jsonStr.getJSONArray("son");
		List<SysWarningInterfaceEntity> interfaceEntities = new ArrayList<>();
		for(int i=0;i<sonArray.size();i++){
			String  sonString = sonArray.getJSONObject(i).toString();
			SysWarningInterfaceEntity interfaceEntity = getData(sonString,SysWarningInterfaceEntity.class);
			interfaceEntities.add(interfaceEntity);
		}
		SysWarningConfigEntity entity = getData("father", jsonStr, SysWarningConfigEntity.class);
		if(entity == null){
			return BaseResult.getFailureMessageEntity("参数不允许为空");
		}
		if(entity.getMessageTemplateId() == null || "".equals(entity.getMessageTemplateId())){
			return BaseResult.getFailureMessageEntity("消息模版id不允许为空");
		}
		if(entity.getAppIdList() == null || "".equals(entity.getAppIdList())){
			return BaseResult.getFailureMessageEntity("应用ID不允许为空");
		}
		if(entity.getWarningAppId() == null || "".equals(entity.getWarningAppId())){
			return BaseResult.getFailureMessageEntity("预警应用类型不允许为空");
		}
		if(entity.getStatus() == null || "".equals(entity.getStatus())){
			return BaseResult.getFailureMessageEntity("状态不允许为空");
		}
		if(entity.getRecipientIdList() == null || "".equals(entity.getRecipientIdList())){
			return BaseResult.getFailureMessageEntity("接收者ID不允许为空");
		}
		//检查接收者是否合规
		String checkResult = checkRecipients(entity);
		if(!"success".equals(checkResult)){
			return BaseResult.getFailureMessageEntity(checkResult);
		}

		entity.setCreate();
		String warningConfigId = entity.getId();
		sysWarningConfigDao.save(entity);
		for(SysWarningInterfaceEntity interfaceEntity : interfaceEntities){
			interfaceEntity.setWarningConfigId(warningConfigId);
			if(interfaceEntity.getApiCode() == null || "".equals(interfaceEntity.getApiCode())){
				return BaseResult.getFailureMessageEntity("接口编码不能为空");
			}
			if(interfaceEntity.getPushMethod() == null || "".equals(interfaceEntity.getPushMethod())){
				return BaseResult.getFailureMessageEntity("推送方式不能为空");
			}
			if(interfaceEntity.getStatus() == null || "".equals(interfaceEntity.getStatus())){
				return BaseResult.getFailureMessageEntity("状态不能为空");
			}
			if(interfaceEntity.getWarningConfigId() == null || "".equals(interfaceEntity.getWarningConfigId())){
				return BaseResult.getFailureMessageEntity("预警配置id不能为空");
			}
			interfaceEntity.setCreate();
			sysWarningInterfaceDao.save(interfaceEntity);
		}
		return BaseResult.getSuccessMessageEntity("保存预警配置成功",entity);
	}

	@Override
	public JsonResultEntity updateEntity(JSONObject jsonObject){
		JSONObject jsonStr = jsonObject.getJSONObject("jsonStr");
		JSONArray sonArray = jsonStr.getJSONArray("son");
		List<SysWarningInterfaceEntity> interfaceEntities = new ArrayList<>();
		for(int i=0;i<sonArray.size();i++){
			String  sonString = sonArray.getJSONObject(i).toString();
			SysWarningInterfaceEntity interfaceEntity = getData(sonString,SysWarningInterfaceEntity.class);
			interfaceEntities.add(interfaceEntity);
		}
		SysWarningConfigEntity entity = getData("father", jsonStr, SysWarningConfigEntity.class);
		if(entity == null){
			return BaseResult.getFailureMessageEntity("参数不允许为空");
		}
		if(entity.getId() == null || "".equals(entity.getId())){
			return BaseResult.getFailureMessageEntity("系统错误");
		}
		if(entity.getMessageTemplateId() == null || "".equals(entity.getMessageTemplateId())){
			return BaseResult.getFailureMessageEntity("消息模版id不允许为空");
		}
		if(entity.getAppIdList() == null || "".equals(entity.getAppIdList())){
			return BaseResult.getFailureMessageEntity("应用ID不允许为空");
		}
		if(entity.getWarningAppId() == null || "".equals(entity.getWarningAppId())){
			return BaseResult.getFailureMessageEntity("预警应用类型不允许为空");
		}
		if(entity.getStatus() == null || "".equals(entity.getStatus())){
			return BaseResult.getFailureMessageEntity("状态不允许为空");
		}
		if(entity.getRecipientIdList() == null || "".equals(entity.getRecipientIdList())){
			return BaseResult.getFailureMessageEntity("接收者ID不允许为空");
		}
		//检查接收者是否合规
		String checkResult = checkRecipients(entity);
		if(!"success".equals(checkResult)){
			return BaseResult.getFailureMessageEntity(checkResult);
		}
		entity.setUpdate();
		String warningConfigId = entity.getId();
		sysWarningConfigDao.update(entity);
		//先查询现有的子表数据并记录
		SysWarningInterfaceEntity oldInterfaceEntity = new SysWarningInterfaceEntity();
		oldInterfaceEntity.setWarningConfigId(warningConfigId);
		List<SysWarningInterfaceEntity> oldInterfaceList = sysWarningInterfaceDao.queryBase(oldInterfaceEntity);
		//更新子表数据
		for(SysWarningInterfaceEntity interfaceEntity : interfaceEntities){
			interfaceEntity.setWarningConfigId(warningConfigId);
			if(interfaceEntity.getApiCode() == null || "".equals(interfaceEntity.getApiCode())){
				return BaseResult.getFailureMessageEntity("接口编码不能为空");
			}
			if(interfaceEntity.getPushMethod() == null || "".equals(interfaceEntity.getPushMethod())){
				return BaseResult.getFailureMessageEntity("推送方式不能为空");
			}
			if(interfaceEntity.getStatus() == null || "".equals(interfaceEntity.getStatus())){
				return BaseResult.getFailureMessageEntity("状态不能为空");
			}
			if(interfaceEntity.getWarningConfigId() == null || "".equals(interfaceEntity.getWarningConfigId())){
				return BaseResult.getFailureMessageEntity("预警配置id不能为空");
			}
			if(interfaceEntity.getId() == null || "".equals(interfaceEntity.getId())){
				//新增
				interfaceEntity.setCreate();
				sysWarningInterfaceDao.save(interfaceEntity);
			}else{
				//修改
				interfaceEntity.setUpdate();
				interfaceEntity.setSts("Y");
				sysWarningInterfaceDao.update(interfaceEntity);
			}
		}
		//删除多余的子表数据
		boolean isDelete = true;
		for(SysWarningInterfaceEntity oldInterface : oldInterfaceList){
			isDelete = true;
			for(SysWarningInterfaceEntity interfaceEntity : interfaceEntities){
				if(oldInterface.getId().equals(interfaceEntity.getId())){
					isDelete = false;
					break;
				}
			}
			if(isDelete){
				sysWarningInterfaceDao.logicRemove(oldInterface);
			}

		}

		return BaseResult.getSuccessMessageEntity("修改预警配置成功",entity);
	}

	/**
	 * 删除主表时，同时删除子表数据*/
	@Override
	public JsonResultEntity deleteEntity(JSONObject jsonObject) {
		SysWarningConfigEntity entity = getData("jsonStr", jsonObject, SysWarningConfigEntity.class);
		if (entity == null) {
			return BaseResult.getFailureMessageEntity("参数不允许为空");
		}
		if (entity.getId() == null || "".equals(entity.getId())) {
			return BaseResult.getFailureMessageEntity("系统错误");
		}
		//先删除子表中对应数据，在删除主表数据
		SysWarningInterfaceEntity interfaceEntity = new SysWarningInterfaceEntity();
		interfaceEntity.setWarningConfigId(entity.getId());
		sysWarningInterfaceDao.logicRemoveMultiCondition(interfaceEntity);

		entity.setUpdate();
		sysWarningConfigDao.logicRemove(entity);

		return BaseResult.getSuccessMessageEntity("删除预警配置成功");
	}

	@Override
	public JsonResultEntity enableDisableEntity(JSONObject jsonObject){
		SysWarningConfigEntity entity = getData("jsonStr", jsonObject, SysWarningConfigEntity.class);
		if (entity == null) {
			return BaseResult.getFailureMessageEntity("参数不允许为空");
		}
		if (entity.getId() == null || "".equals(entity.getId())) {
			return BaseResult.getFailureMessageEntity("id不能为空");
		}
		if (entity.getStatus() == null || "".equals(entity.getStatus())) {
			return BaseResult.getFailureMessageEntity("状态不能为空");
		}
		if(entity.getMessageTemplateId() == null || "".equals(entity.getMessageTemplateId())){
			return BaseResult.getFailureMessageEntity("消息模版id不允许为空");
		}
		//0停用，1启用
		if("0".equals(entity.getStatus())){
			entity.setUpdate();
			sysWarningConfigDao.update(entity);
			return BaseResult.getSuccessMessageEntity("停用模版成功");
		}else{
			//校验该预警设置的消息模版是否为启用状态
			SysMessageTemplateEntity templateEntity = sysMessageTemplateDao.get(entity.getMessageTemplateId());
			if(templateEntity == null){
				return BaseResult.getFailureMessageEntity("消息模版不存在");
			}
			if(!"1".equals(templateEntity.getState())){
				return BaseResult.getFailureMessageEntity("该预警设置的消息模版未启用，请先启用");
			}
			entity.setUpdate();
			sysWarningConfigDao.update(entity);
			return BaseResult.getSuccessMessageEntity("启用模版成功");
		}
	}

	public String checkRecipients(SysWarningConfigEntity entity){
		String recipientIds = entity.getRecipientIdList();
		String[] recipientIdList = recipientIds.split(",");
		SysUserEntity userEntity = new SysUserEntity();

		for(String recipientId : recipientIdList){
			String personName = sysPersonDao.get(recipientId).getPersonName();

			userEntity.setPersonId(recipientId);
			SysUserEntity usefulEntity = sysUserDao.queryOne(userEntity);
			if(usefulEntity == null){
				return "接收人"+personName+"不存在账号";
			}
			//预警应用只有一个的情况下
			switch (entity.getWarningAppId()){
				case "7ebc1702511f463d9cf50162973bf935":
					String ddUserId = usefulEntity.getDdUserId();
					if(ddUserId == null || "".equals(ddUserId)){
						return "接收人"+personName+"未配置钉钉用户id";
					}
					break;
				default:
					return "预警应用类型错误";
			}
		}
		return "success";
	}

	public List<SysWarningConfigEntity> queryNameList(List<SysWarningConfigEntity> list){
		for(SysWarningConfigEntity configEntity : list){
			//拼接应用名称列表
			String appIds = configEntity.getAppIdList();
			String[] appIdList = appIds.split(",");
			String appNameList = "";
			for(String appId : appIdList){
				SysApplicationEntity appEntity = sysApplicationDao.get(appId);
				String appName = appEntity.getName();
				if(!"".equals(appNameList)){
					appNameList += ",";
				}
				appNameList += appName;
			}
			configEntity.setAppNameList(appNameList);
			//拼接预警应用名称列表
			String warningAppIds = configEntity.getWarningAppId();
			String[] warningAppIdList = warningAppIds.split(",");
			String warningAppNameList = "";
			for(String warningAppId : warningAppIdList){
				SysApplicationEntity warningAppEntity = sysApplicationDao.get(warningAppId);
				String warningAppName = warningAppEntity.getName();
				if(!"".equals(warningAppNameList)){
					warningAppNameList += ",";
				}
				warningAppNameList += warningAppName;
			}
			configEntity.setWarningAppNameList(warningAppNameList);
			//拼接接收者名称列表
			String recipientIds = configEntity.getRecipientIdList();
			String[] recipientIdList = recipientIds.split(",");
			String recipientNameList = "";
			for(String recipientId : recipientIdList){
//				SysUserEntity userEntity = sysUserDao.get(recipientId);
//				String personId = userEntity.getPersonId();
				SysPersonEntity personEntity = sysPersonDao.get(recipientId);
				String recipientName = personEntity.getPersonName();
				if(!"".equals(recipientNameList)){
					recipientNameList += ",";
				}
				recipientNameList += recipientName;
			}
			configEntity.setRecipientNameList(recipientNameList);

		}
		return list;
	}

}
