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

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

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.GisTreeEnum;
import com.huatek.busi.common.SiteConstants.SiteTreeEnum;
import com.huatek.busi.dao.BusiGisSensorDao;
import com.huatek.busi.dto.BusiEvaMonitorConfigDto;
import com.huatek.busi.dto.BusiSensorQueryParamDto;
import com.huatek.busi.entity.BusiGisSensor;
import com.huatek.busi.entity.BusiGisSubTree;
import com.huatek.busi.mapper.BusiGisSensorMapper;
import com.huatek.busi.service.BusiEvaMonitorConfigService;
import com.huatek.busi.service.BusiGisSubTreeService;
import com.huatek.busi.service.gis.BusiGisSensorService;
import com.huatek.busi.service.gis.GisSF6ThresholdService;
import com.huatek.busi.service.threshold.InfraredThresholdService;
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: BusiGisSensorServiceImpl
 * @FullClassPath: com.huatek.busi.service.impl.gis.BusiGisSensorServiceImpl
 * @Description: GIS外挂设备传感器服务
 * @author: Arno
 * @date: Jun 27, 2019 6:52:25 PM
 * @version: 1.0
 */
@Component
@Service(interfaceClass = BusiGisSensorService.class)
@Transactional(rollbackFor = Exception.class)
public class BusiGisSensorServiceImpl implements BusiGisSensorService {

	@Autowired
	private BusiGisSensorDao busiGisSensorDao;

	@Autowired
	private BusiGisSubTreeService busiGisSubTreeService;

	@Autowired
	private BusiGisSensorMapper busiGisSensorMapper;

	@Autowired
    private InfraredThresholdService infraredThresholdService;

	@Autowired
	private GisSF6ThresholdService gisSF6ThresholdService;
	
	@Autowired
	private BusiEvaMonitorConfigService busiEvaMonitorConfigService;
    
	@Override
	public Page<BusiSensorVo> page(String equipmentId) {
		return busiGisSensorMapper.page(equipmentId);
	}

	@Override
	public BusiGisSensor findByPK(String pk) {
		return busiGisSensorDao.get(pk);
	}

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

	@Override
	public boolean update(String token,BusiSensorVo busiSensorVo) {
		BusiGisSensor find = this.findByPK(busiSensorVo.getId());
		if (null != find) {
			if (StringUtils.isNotEmpty(busiSensorVo.getSensorCode())) {
				Integer sensorCodeCount = busiGisSensorMapper.checkSensorCode(busiSensorVo.getSensorCode(), busiSensorVo.getId());
				if (sensorCodeCount > 0) {
					throw new OwlException("当前sensor编码已经存在");
				}
			}
			String oldSensorCode = find.getSensorCode();
			find = this.buildData(busiSensorVo, find);
			this.busiGisSensorDao.updateLocal(find);
			if (StringUtils.isNotEmpty(oldSensorCode)) {
				if(find.getEquipmentType().equals(GisTreeEnum.SF6_EQM.getValue())) {
					if (!oldSensorCode.equals(busiSensorVo.getSensorCode())) {
					    gisSF6ThresholdService.updateGisSensorThresholdBySensorCode(oldSensorCode, busiSensorVo.getSensorCode());
					}
				}
				if(find.getEquipmentType().equals(GisTreeEnum.HW_EQM.getValue())) {
					if (!oldSensorCode.equals(busiSensorVo.getSensorCode())) {
						infraredThresholdService.updateSensorInsertInfrared(oldSensorCode, busiSensorVo.getSensorCode());
					}
				}
			} else {
				if(StringUtils.isNotEmpty(busiSensorVo.getSensorCode()) && find.getEquipmentType().equals(GisTreeEnum.HW_EQM.getValue())) {
					infraredThresholdService.addSensorInsertInfrared(token, busiSensorVo.getSensorCode(), SiteTreeEnum.GIS.getValue());
				}
			}
			if (StringUtils.isNotEmpty(busiSensorVo.getSensorCode())) {
				BusiEvaMonitorUnitVo busiEvaMonitorUnitVo = busiEvaMonitorConfigService.findBusiEvaMonitorUnit(find.getEquipmentType(), ExternalTypeEnum.GIS.getValue());
				if(!ObjectUtils.isEmpty(busiEvaMonitorUnitVo)) {
					List<BusiEvaMonitorRefVo> busiEvaMonitorRefVoList = busiEvaMonitorConfigService.findBusiEvaMonitorRefList(busiEvaMonitorUnitVo.getId(),"");
					if(!busiEvaMonitorRefVoList.isEmpty()) {
						busiEvaMonitorRefVoList.stream().forEach(RedefinitionListenable -> {
							BusiEvaMonitorConfigDto monitorConfig = new BusiEvaMonitorConfigDto();
							monitorConfig.setMonitorTypeId(busiEvaMonitorUnitVo.getEqTypeId());
							monitorConfig.setMonitorUnitId(busiEvaMonitorUnitVo.getId());
							monitorConfig.setIndicatorsId(RedefinitionListenable.getIndicatorsId());
							monitorConfig.setType(ExternalTypeEnum.GIS.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 -> {
			BusiGisSensor find = this.findByPK(pk);
			if (null != find) {
				find.setStatus(SiteConstants.Status.DELETE.getValue());
				this.busiGisSensorDao.updateLocal(find);
				if (StringUtils.isNotEmpty(find.getSensorCode())) {
					if (find.getEquipmentType().equals(GisTreeEnum.SF6_EQM.getValue())) {
					    gisSF6ThresholdService.deleteGisThresholdBySensorCode(find.getSensorCode());
					}
					if(find.getEquipmentType().equals(GisTreeEnum.HW_EQM.getValue())) {
						infraredThresholdService.deleteSensorInsertInfrared(find.getSensorCode());
					}
				}
			}
		});
		return true;
	}

	public BusiGisSensor buildData(BusiSensorVo busiSensorVo, BusiGisSensor entity) {
		if (null == entity) {
			entity = new BusiGisSensor();
			String equipmentId = busiSensorVo.getEquipmentId();
			entity.setId(Uuid.getUUID());
			entity.setStatus(SiteConstants.Status.NORMAL.getValue());
			entity.setCreateTime(LocalDateTime.now());
			BusiGisSubTree subTree = busiGisSubTreeService.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());
		if (SiteConstants.GisTreeEnum.SF6_EQM.getValue().equals(entity.getEquipmentType())) {
			entity.setMonitorSite(busiSensorVo.getMonitorSite());
			entity.setStandardPressure(busiSensorVo.getStandardPressure());
		}
		return entity;
	}

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

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

    @Override
    public BusiSensorVo getBusiSensorVo(String sensorCode) {
        return busiGisSensorMapper.getBusiSensorVo(sensorCode);
    }
    @Override
    public BusiSensorVo getBusiSensorVoById(String id) {
        return busiGisSensorMapper.getBusiSensorVoById(id);
    }

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