package com.huatek.busi.service.impl.temperature;

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.springframework.util.ObjectUtils;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.huatek.busi.common.SiteConstants;
import com.huatek.busi.common.SiteConstants.ExternalTypeEnum;
import com.huatek.busi.dao.BusiTemperPointDao;
import com.huatek.busi.dto.BusiEvaMonitorConfigDto;
import com.huatek.busi.dto.BusiTemperPointDto;
import com.huatek.busi.entity.BusiSiteTree;
import com.huatek.busi.entity.BusiTemperPoint;
import com.huatek.busi.mapper.BusiTemperPointMapper;
import com.huatek.busi.service.BusiEvaMonitorConfigService;
import com.huatek.busi.service.BusiSiteTreeService;
import com.huatek.busi.service.temperature.BusiTemperPointService;
import com.huatek.busi.vo.BusiEvaMonitorRefVo;
import com.huatek.busi.vo.BusiEvaMonitorUnitVo;
import com.huatek.busi.vo.BusiSensorVo;
import com.huatek.busi.vo.BusiTemperPointVo;
import com.huatek.frame.base.util.BeanUtils;
import com.huatek.torch.frame.exception.OwlException;
import com.huatek.torch.sql.beans.WherePrams;
import com.huatek.torch.util.uuid.Uuid;

/**
 * 测温柜/点信息表 ServiceImpl
 *
 * @author anker_cheng
 * @date Jul 1, 2019 4:05:05 PM
 */
@Component
@Service(interfaceClass = BusiTemperPointService.class)
@Transactional(rollbackFor = Exception.class)
public class BusiTemperPointServiceImpl implements BusiTemperPointService {

    @Autowired
    private BusiTemperPointMapper busiTemperPointMapper;
    @Autowired
    private BusiTemperPointDao busiTemperPointDao;

    @Autowired
    private BusiSiteTreeService busiSiteTreeService;
    
	
	@Autowired
	private BusiEvaMonitorConfigService busiEvaMonitorConfigService;

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

    @Override
    public List<BusiSensorVo> findSensorList(String equipmentId) {
        return busiTemperPointMapper.findSensorList(equipmentId);
    }

    @Override
    public BusiTemperPoint findByPK(String pk) {
        return busiTemperPointDao.get(pk);
    }

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

    @Override
    public boolean update(BusiSensorVo busiSensorVo) {
        BusiTemperPoint find = this.findByPK(busiSensorVo.getId());
        if (null != find) {
        	if (StringUtils.isNotEmpty(busiSensorVo.getSensorCode())) {
				Integer sensorCodeCount = busiTemperPointMapper.checkSensorCode(busiSensorVo.getSensorCode(), busiSensorVo.getId());
				if (sensorCodeCount > 0) {
					throw new OwlException("当前sensor编码已经存在");
				}
			}
            find = this.buildData(busiSensorVo, find);
            this.busiTemperPointDao.updateLocal(find);
            return true;
        }
        return false;
    }

    @Override
    public boolean delete(List<String> list) {
        list.forEach(pk -> {
            BusiTemperPoint find = this.findByPK(pk);
            if (null != find) {
                find.setStatus(SiteConstants.Status.DELETE.getValue());
                this.busiTemperPointDao.updateLocal(find);
            }
        });
        return true;
    }

    public BusiTemperPoint buildData(BusiSensorVo busiSensorVo, BusiTemperPoint entity) {
        if (null == entity) {
            entity = new BusiTemperPoint();
            String equipmentId = busiSensorVo.getEquipmentId();
            entity.setId(Uuid.getUUID());
            entity.setStatus(SiteConstants.Status.NORMAL.getValue());
            entity.setCreateTime(LocalDateTime.now());
            BusiSiteTree siteTree = busiSiteTreeService.findByPK(equipmentId);
            if (null != siteTree) {
                entity.setSiteId(siteTree.getSiteId());
                entity.setEquipmentId(equipmentId);
            }
        }
        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.setGrowRate(busiSensorVo.getGrowRate());
        entity.setWarningValue(busiSensorVo.getWarningValue());

        return entity;
    }

    @Override
    public List<BusiTemperPoint> findAll() {
        return busiTemperPointMapper.findAll();
    }

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

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

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

    @Override
    public PageInfo<BusiTemperPointVo> findBusiTemperPointPage(BusiTemperPointDto busiTemperPointDto) {
        return PageHelper.startPage(busiTemperPointDto.getPage(), busiTemperPointDto.getLimit())
            .doSelectPageInfo(() -> busiTemperPointMapper.selectBusiTemperPointPage(busiTemperPointDto));
    }

    @Override
    public int saveBusiTemperPoint(BusiTemperPointDto busiTemperPointDto) {
        Integer sensorCodeCount = busiTemperPointMapper.checkSensorCode(busiTemperPointDto.getSensorCode(), busiTemperPointDto.getId());
        if (sensorCodeCount > 0) {
            throw new OwlException("当前sensor编码已经存在");
        }
        BusiTemperPoint busiTemperPoint = new BusiTemperPoint();
        busiTemperPoint.setMiddleId(busiTemperPointDto.getEquipmentId());
        BeanUtils.copyPropertiesWithIgnoreNull(busiTemperPointDto, busiTemperPoint);
        if(StringUtils.isEmpty(busiTemperPoint.getId())) {
            busiTemperPoint.setCreateTime(LocalDateTime.now());
            busiTemperPoint.setStatus(SiteConstants.Status.NORMAL.getValue());
        }
        if(StringUtils.isEmpty(busiTemperPoint.getThresholdValue())) {
            busiTemperPoint.setThresholdValue(busiTemperPoint.getWarningValue());
        }
    	//维护考评指标
        if (StringUtils.isNotEmpty(busiTemperPointDto.getSensorCode())) {	
			BusiEvaMonitorUnitVo busiEvaMonitorUnitVo = busiEvaMonitorConfigService.findBusiEvaMonitorUnit("061", ExternalTypeEnum.CW.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(busiTemperPointDto.getSensorCode());
						busiEvaMonitorConfigService.saveOrUpdate("", monitorConfig);
					});
				}
			}
         
        }
        return busiTemperPointDao.saveOrUpdate(busiTemperPoint);
    }

    @Override
    public int deleteBusiTemperPoint(String[] ids) {
        if(ids == null || ids .length == 0) {
            return 0;
        }
        int count = 0;
        for(String id : ids) {
            BusiTemperPoint busiTemperPoint = new BusiTemperPoint();
            busiTemperPoint.setId(id);
            busiTemperPoint.setStatus(SiteConstants.Status.DELETE.getValue());
            busiTemperPointDao.updateLocal(busiTemperPoint);
        }
        return count;
    }

    @Override
    public BusiTemperPointVo getBusiTemperPointVoBySensor(String sensorCode) {
        return busiTemperPointMapper.getBySensor(sensorCode);
    }
}