/**
 *
 */
package com.huatek.busi.service.impl.transformer;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

import com.huatek.busi.service.threshold.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.apache.commons.lang3.ObjectUtils;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.huatek.busi.common.SiteConstants;
import com.huatek.busi.common.SiteConstants.ExternalTypeEnum;
import com.huatek.busi.common.SiteConstants.SiteTreeEnum;
import com.huatek.busi.common.SiteConstants.TransfromerTreeEnum;
import com.huatek.busi.dao.BusiTransformerSensorDao;
import com.huatek.busi.dto.BusiEvaMonitorConfigDto;
import com.huatek.busi.dto.BusiSensorQueryParamDto;
import com.huatek.busi.entity.BusiTransformerSensor;
import com.huatek.busi.entity.BusiTransfromerSubTree;
import com.huatek.busi.mapper.BusiTransformerSensorMapper;
import com.huatek.busi.service.BusiEvaMonitorConfigService;
import com.huatek.busi.service.BusiTransfromerSubTreeService;
import com.huatek.busi.service.transformer.BusiTransformerSensorService;
import com.huatek.busi.vo.BusiEvaMonitorRefVo;
import com.huatek.busi.vo.BusiEvaMonitorUnitVo;
import com.huatek.busi.vo.BusiSensorVo;
import com.huatek.torch.frame.exception.OwlException;
import com.huatek.torch.sql.beans.LocalUser;
import com.huatek.torch.sql.beans.WherePrams;
import com.huatek.torch.util.tools.UserUtil;
import com.huatek.torch.util.uuid.Uuid;

/**
 * @ClassName: BusiTransformerSensorServiceImpl
 * @FullClassPath: com.huatek.busi.service.impl.busi.transformer.
 *                 BusiTransformerSensorServiceImpl
 * @Description: 变压器外挂设备传感器服务
 * @author: Arno
 * @date: Jun 27, 2019 10:09:37 AM
 * @version: 1.0
 */
@Component
@Service(interfaceClass = BusiTransformerSensorService.class)
@Transactional(rollbackFor = Exception.class)
public class BusiTransformerSensorServiceImpl implements BusiTransformerSensorService {

	@Autowired
	private BusiTransformerSensorDao busiTransformerSensorDao;

	@Autowired
	private BusiTransformerSensorMapper busiTransformerSensorMapper;

	@Autowired
	private BusiTransfromerSubTreeService busiTransfromerSubTreeService;

	@Autowired
	private InfraredThresholdService infraredThresholdService;

	@Autowired
	private WindingThresholdService windingThresholdService;

	@Autowired
	private CwzzThresholdService cwzzThresholdService;

	@Autowired
	private TransformerTgThresholdService transformerTgThresholdService;

	@Autowired
	private TransformerIcgeThresholdService transformerIcgeThresholdService;

	@Autowired
	private TransformerOilThresholdService transformerOilThresholdService;

	@Autowired
	private BusiEvaMonitorConfigService busiEvaMonitorConfigService;

	@Override
	public BusiTransformerSensor findByPK(String pk) {
		return busiTransformerSensorDao.get(pk);
	}

	@Override
	public Page<BusiSensorVo> page(String equipmentId) {
		return busiTransformerSensorMapper.page(equipmentId);
	}

	@Override
	public boolean add(BusiSensorVo busiSensorVo) {
		BusiTransformerSensor entity = null;
		entity = this.buildData(busiSensorVo, entity);
		this.busiTransformerSensorDao.add(entity);
		return true;
	}

	@Override
	public boolean update(String token,BusiSensorVo busiSensorVo) {
		BusiTransformerSensor find = this.findByPK(busiSensorVo.getId());
		if (null != find) {
			if (StringUtils.isNotEmpty(busiSensorVo.getSensorCode())) {
				Integer sensorCodeCount = busiTransformerSensorMapper.checkSensorCode(busiSensorVo.getSensorCode(), busiSensorVo.getId());
				if (sensorCodeCount > 0) {
					throw new OwlException("当前sensor编码已经存在");
				}
			}
			String oldSensorCode = find.getSensorCode();
			find = this.buildData(busiSensorVo, find);

			//查询多组分油色谱
//			BusiTransformerSensor type1 = new BusiTransformerSensor();
//			if(find.getEquipmentType().equals(TransfromerTreeEnum.YSP_EQM.getValue())) {
//				String oilType = SiteConstants.oilType.OILTYPE1.getValue();
//				String deleted = SiteConstants.Status.NORMAL.getValue();
//				String type = TransfromerTreeEnum.YSP_EQM.getValue();
//				String equipmentId = busiSensorVo.getMainTreeId();
//				type1 = busiTransformerSensorMapper.findSensorType1(oilType, deleted, type, equipmentId);
//				if(ObjectUtils.isEmpty(type1)) {
//					this.busiTransformerSensorDao.updateLocal(find);
//				}
//				//else if(find.getType().equals(type1.getType()) && !Objects.equals(find.getId(), type1.getId())){
//				//	throw new OwlException("该变压器下已存在多组分油色谱");
//				//}
//				else{
//					this.busiTransformerSensorDao.updateLocal(find);
//				}
//			} else {
				this.busiTransformerSensorDao.updateLocal(find);
			//}
			if(StringUtils.isNotEmpty(busiSensorVo.getSensorCode())) {
				if (StringUtils.isNotEmpty(oldSensorCode) && !oldSensorCode.equals(busiSensorVo.getSensorCode())) {
					//油色谱
					if(find.getEquipmentType().equals(TransfromerTreeEnum.YSP_EQM.getValue())) {
						//if(ObjectUtils.isEmpty(type1)){
							transformerOilThresholdService.updateTransformerOilThresholdBySensorCode(oldSensorCode, busiSensorVo.getSensorCode());
						//} else{
							//throw new OwlException("每个变压器下只可建立一个多组分油色谱");
						//}
					}
					//铁芯、夹件
					if(find.getEquipmentType().equals(TransfromerTreeEnum.TX_EQM.getValue()) || find.getEquipmentType().equals(TransfromerTreeEnum.JJ_EQM.getValue())) {
						transformerIcgeThresholdService.updateTransformerIcgeThresholdBySensorCode(oldSensorCode, busiSensorVo.getSensorCode());
					}
					//套管
					if(find.getEquipmentType().equals(TransfromerTreeEnum.TG_EQM.getValue())) {
						transformerTgThresholdService.updateTransformerTgThresholdBySensorCode(oldSensorCode, busiSensorVo.getSensorCode());
					}
					//红外
					if(find.getEquipmentType().equals(TransfromerTreeEnum.HW_EQM.getValue())) {
						infraredThresholdService.updateSensorInsertInfrared(oldSensorCode, busiSensorVo.getSensorCode());
					}
					//绕组测温
					if(find.getEquipmentType().equals(TransfromerTreeEnum.RZCW_EQM.getValue())) {
						windingThresholdService.updateSensorInsertWinding(oldSensorCode, busiSensorVo.getSensorCode());
					}
					// 测温装置
					if(find.getEquipmentType().equals(TransfromerTreeEnum.CW_EQM.getValue())) {
						cwzzThresholdService.updateSensorInsertCwzz(oldSensorCode, busiSensorVo.getSensorCode());
					}
				} else {
					if(find.getEquipmentType().equals(TransfromerTreeEnum.HW_EQM.getValue())) {
						infraredThresholdService.addSensorInsertInfrared(token, busiSensorVo.getSensorCode(), SiteTreeEnum.BYQ.getValue());
					}
					if(find.getEquipmentType().equals(TransfromerTreeEnum.RZCW_EQM.getValue())) {
						windingThresholdService.addSensorInsertWinding(token, busiSensorVo.getSensorCode(), SiteTreeEnum.BYQ.getValue());
					}
					if(find.getEquipmentType().equals(TransfromerTreeEnum.CW_EQM.getValue())) {
						cwzzThresholdService.addSensorInsertCwzz(token, busiSensorVo.getSensorCode(), SiteTreeEnum.BYQ.getValue());
					}
				}
			}
			if (StringUtils.isNotEmpty(busiSensorVo.getSensorCode())) {
					//维护考评指标
					BusiEvaMonitorUnitVo busiEvaMonitorUnitVo = busiEvaMonitorConfigService.findBusiEvaMonitorUnit(find.getEquipmentType(), ExternalTypeEnum.BYQ.getValue());
					if(!ObjectUtils.isEmpty(busiEvaMonitorUnitVo)) {
						String phase = StringUtils.EMPTY;
						if (find.getEquipmentType().equals(TransfromerTreeEnum.SJZD_EQM.getValue())) {
							if (StringUtils.isNotEmpty(busiSensorVo.getPosition())) {
								phase = busiSensorVo.getPosition();
							} else {
								phase = "4";
							}
						}
						List<BusiEvaMonitorRefVo> busiEvaMonitorRefVoList = busiEvaMonitorConfigService.findBusiEvaMonitorRefList(busiEvaMonitorUnitVo.getId(),phase);
						if(!busiEvaMonitorRefVoList.isEmpty()) {
							if (find.getEquipmentType().equals(TransfromerTreeEnum.SJZD_EQM.getValue())) {
								//删除考评指标
								busiEvaMonitorConfigService.deleteBusiEvaMonitorConfig(busiSensorVo.getSensorCode());
							}
							busiEvaMonitorRefVoList.stream().forEach(RedefinitionListenable -> {
								BusiEvaMonitorConfigDto monitorConfig = new BusiEvaMonitorConfigDto();
								monitorConfig.setMonitorTypeId(busiEvaMonitorUnitVo.getEqTypeId());
								monitorConfig.setMonitorUnitId(busiEvaMonitorUnitVo.getId());
								monitorConfig.setIndicatorsId(RedefinitionListenable.getIndicatorsId());
								monitorConfig.setType(ExternalTypeEnum.BYQ.getValue());
								monitorConfig.setSensorId(busiSensorVo.getSensorCode());
								LocalUser user = UserUtil.getLocalUser(token);
								if (ObjectUtils.isNotEmpty(user)) {
									monitorConfig.setCreator(user.getUid());
								}
								busiEvaMonitorConfigService.saveOrUpdate("", monitorConfig);
							});
						}
					}
			}
			return true;
		}

		return false;
	}

	@Override
	public boolean delete(List<String> list) {
		list.forEach(pk -> {
			BusiTransformerSensor find = this.findByPK(pk);
			if (null != find) {
				find.setStatus(SiteConstants.Status.DELETE.getValue());
				this.busiTransformerSensorDao.updateLocal(find);
				if (StringUtils.isNotEmpty(find.getSensorCode())) {
					//油色谱
					if(find.getEquipmentType().equals(TransfromerTreeEnum.YSP_EQM.getValue())) {
						transformerOilThresholdService.delTransformerOilThresholdBySensorCode(find.getSensorCode());
					}
					//铁芯、夹件
					if(find.getEquipmentType().equals(TransfromerTreeEnum.TX_EQM.getValue()) || find.getEquipmentType().equals(TransfromerTreeEnum.JJ_EQM.getValue())) {
						transformerIcgeThresholdService.deleteTransformerTgThresholdBySensorCode(find.getSensorCode());
					}
					//套管
					if(find.getEquipmentType().equals(TransfromerTreeEnum.TG_EQM.getValue())) {
						transformerTgThresholdService.deleteTransformerTgThresholdBySensorCode(find.getSensorCode());
					}
					//红外
					if(find.getEquipmentType().equals(TransfromerTreeEnum.HW_EQM.getValue())) {
						infraredThresholdService.deleteSensorInsertInfrared(find.getSensorCode());
					}
					//绕组测温
					if(find.getEquipmentType().equals(TransfromerTreeEnum.RZCW_EQM.getValue())) {
						windingThresholdService.deleteSensorInsertWinding(find.getSensorCode());
					}
					//测温
					if(find.getEquipmentType().equals(TransfromerTreeEnum.CW_EQM.getValue())) {
						cwzzThresholdService.deleteSensorInsertCwzz(find.getSensorCode());
					}
				}
			}
		});
		return true;
	}

	public BusiTransformerSensor buildData(BusiSensorVo busiSensorVo, BusiTransformerSensor entity) {
		if (null == entity) {
			entity = new BusiTransformerSensor();
			String equipmentId = busiSensorVo.getEquipmentId();
			entity.setId(Uuid.getUUID());
			entity.setStatus(SiteConstants.Status.NORMAL.getValue());
			entity.setCreateTime(LocalDateTime.now());
			BusiTransfromerSubTree subTree = busiTransfromerSubTreeService.findByPK(equipmentId);
			if (null != subTree) {
				entity.setSiteId(subTree.getSiteId());
				entity.setEquipmentId(equipmentId);
				entity.setEquipmentType(subTree.getEquipmentType());
			}
		}
		entity.setSensorBrand(busiSensorVo.getSensorBrand());
		entity.setSensorCode(busiSensorVo.getSensorCode());
		entity.setSensorName(busiSensorVo.getSensorName());
		entity.setPosition(busiSensorVo.getPosition());
		entity.setPositionDes(busiSensorVo.getPositionDes());
		entity.setManufactor(busiSensorVo.getManufactor());
		entity.setUseDate(busiSensorVo.getUseDate());
		entity.setProductionDate(busiSensorVo.getProductionDate());
		entity.setPdValue(busiSensorVo.getPdValue());
		entity.setType(busiSensorVo.getOilType());
		entity.setOilType(busiSensorVo.getOilDetailType());
		return entity;
	}

	@Override
	public BusiTransformerSensor findSensorBySensorCode(String sensorCode) {
		return busiTransformerSensorDao.get(new WherePrams().where("sensor_code", sensorCode).and("status", SiteConstants.Status.NORMAL.getValue()));
	}

    @Override
    public List<BusiSensorVo> findSensorList(BusiSensorQueryParamDto param) {
        return busiTransformerSensorMapper.findSensorList(param);
    }

    @Override
    public BusiSensorVo getBusiSensorVo(String sensorCode) {
        return busiTransformerSensorMapper.getBusiSensorVo(sensorCode);
    }

    @Override
    public BusiSensorVo getBusiSensorVoById(String id) {
        return busiTransformerSensorMapper.getBusiSensorVoById(id);
    }

    @Override
    public int findSensorCount(String equipmentType) {
         return busiTransformerSensorMapper.findSensorCount(equipmentType);
    }
}
