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

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

import com.huatek.busi.service.threshold.ArresterInsulationMonitorThresholdService;
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.BusiArresterSensorDao;
import com.huatek.busi.dto.BusiEvaMonitorConfigDto;
import com.huatek.busi.dto.BusiSensorQueryParamDto;
import com.huatek.busi.entity.BusiArresterSensor;
import com.huatek.busi.entity.BusiArresterSubTree;
import com.huatek.busi.mapper.BusiArresterSensorMapper;
import com.huatek.busi.service.BusiArresterSubTreeService;
import com.huatek.busi.service.BusiEvaMonitorConfigService;
import com.huatek.busi.service.arrester.BusiArresterSensorService;
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: BusiArresterSensorServiceImpl
 * @FullClassPath: com.huatek.busi.service.impl.BusiArresterSensorServiceImpl
 * @Description: 避雷器外挂设备传感器服务
 * @author: Arno
 * @date: Jun 28, 2019 4:47:26 PM
 * @version: 1.0
 */
@Component
@Service(interfaceClass = BusiArresterSensorService.class)
@Transactional(rollbackFor = Exception.class)
public class BusiArresterSensorServiceImpl implements BusiArresterSensorService {

	@Autowired
	private BusiArresterSubTreeService busiArresterSubTreeService;

	@Autowired
	private BusiArresterSensorDao busiArresterSensorDao;

	@Autowired
	private BusiArresterSensorMapper busiArresterSensorMapper;

	@Autowired
    private InfraredThresholdService infraredThresholdService;

	@Autowired
	private ArresterInsulationMonitorThresholdService arresterInsulationMonitorThresholdService;
	
	@Autowired
	private BusiEvaMonitorConfigService busiEvaMonitorConfigService;
    
	@Override
	public Page<BusiSensorVo> page(String equipmentId) {
		return busiArresterSensorMapper.page(equipmentId);
	}

	@Override
	public BusiArresterSensor findByPK(String pk) {
		return this.busiArresterSensorDao.get(pk);
	}

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

	@Override
	public boolean update(String token,BusiSensorVo busiSensorVo) {
		BusiArresterSensor find = this.findByPK(busiSensorVo.getId());
		if (!ObjectUtils.isEmpty(find)) {
			if (StringUtils.isNotEmpty(busiSensorVo.getSensorCode())) {
				Integer sensorCodeCount = busiArresterSensorMapper.checkSensorCode(busiSensorVo.getSensorCode(), busiSensorVo.getId());
				if (sensorCodeCount > 0) {
					throw new OwlException("当前sensor编码已经存在");
				}
			}
			String sensorId = find.getSensorCode();
			find = this.buildData(busiSensorVo, find);
			this.busiArresterSensorDao.updateLocal(find);
			if(StringUtils.isNotEmpty(busiSensorVo.getSensorCode())) {
	            if (StringUtils.isNotEmpty(sensorId) && !sensorId.equals(busiSensorVo.getSensorCode())) {
	            	infraredThresholdService.updateSensorInsertInfrared(sensorId, busiSensorVo.getSensorCode());
	            } 
	            if (find.getEquipmentType().equals(GisTreeEnum.HW_EQM.getValue())) {
	            	infraredThresholdService.addSensorInsertInfrared(token, busiSensorVo.getSensorCode(), SiteTreeEnum.BLQ.getValue());
	            }
				if (find.getEquipmentType().equals(SiteConstants.ArresterTreeEnum.JY_EQM.getValue())) {
					arresterInsulationMonitorThresholdService.addSensorInsertInsulation(token, busiSensorVo.getSensorCode(), SiteTreeEnum.BLQ.getValue());
				}
	        }
			if (StringUtils.isNotEmpty(busiSensorVo.getSensorCode())) {
				//维护考评指标
				BusiEvaMonitorUnitVo busiEvaMonitorUnitVo = busiEvaMonitorConfigService.findBusiEvaMonitorUnit(find.getEquipmentType(), ExternalTypeEnum.BLQ.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.BLQ.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 -> {
			BusiArresterSensor find = this.findByPK(pk);
			if (null != find) {
				find.setStatus(SiteConstants.Status.DELETE.getValue());
				this.busiArresterSensorDao.updateLocal(find);
				infraredThresholdService.deleteSensorInsertInfrared(find.getSensorCode());
			}
		});
		return true;
	}

	public BusiArresterSensor buildData(BusiSensorVo busiSensorVo, BusiArresterSensor entity) {
		if (null == entity) {
			entity = new BusiArresterSensor();
			String equipmentId = busiSensorVo.getEquipmentId();
			entity.setId(Uuid.getUUID());
			entity.setStatus(SiteConstants.Status.NORMAL.getValue());
			entity.setCreateTime(LocalDateTime.now());
			BusiArresterSubTree subTree = busiArresterSubTreeService.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());
		return entity;
	}

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

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

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

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

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