package com.huatek.busi.service.impl;

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

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 com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.huatek.busi.common.SiteConstants.SiteTreeEnum;
import com.huatek.busi.common.SiteConstants.Status;
import com.huatek.busi.dao.BusiEvaMonitorConfigDao;
import com.huatek.busi.dao.BusiEvaMonitorEquipmentDao;
import com.huatek.busi.dao.BusiEvaMonitorUnitDao;
import com.huatek.busi.dao.BusiEvaMonitorUnitIndicatorsDao;
import com.huatek.busi.dto.BusiEvaMonitorConfigDto;
import com.huatek.busi.entity.BusiEvaMonitorConfig;
import com.huatek.busi.entity.BusiEvaMonitorEquipment;
import com.huatek.busi.entity.BusiEvaMonitorUnit;
import com.huatek.busi.entity.BusiEvaMonitorUnitIndicators;
import com.huatek.busi.mapper.BusiEvaMonitorConfigMapper;
import com.huatek.busi.service.BusiEvaMonitorConfigService;
import com.huatek.busi.service.BusiSensorService;
import com.huatek.busi.vo.BusiEvaMonitorConfigVo;
import com.huatek.busi.vo.BusiEvaMonitorEquipmentVo;
import com.huatek.busi.vo.BusiEvaMonitorRefVo;
import com.huatek.busi.vo.BusiEvaMonitorUnitIndicatorsVo;
import com.huatek.busi.vo.BusiEvaMonitorUnitVo;
import com.huatek.busi.vo.BusiSensorVo;
import com.huatek.frame.base.util.BeanUtils;
import com.huatek.torch.frame.exception.OwlException;
import com.huatek.torch.sql.beans.LocalUser;
import com.huatek.torch.util.tools.UserUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * 考评指标配置 ServiceImpl
 *
 * @author anker_cheng
 * @date Jul 23, 2019 9:50:35 AM
 */
@Component
@Service(interfaceClass = BusiEvaMonitorConfigService.class)
@Transactional(rollbackFor = Exception.class)
@Slf4j
public class BusiEvaMonitorConfigServiceImpl implements BusiEvaMonitorConfigService {
    @Autowired
    private BusiEvaMonitorConfigMapper busiEvaMonitorConfigMapper;

    @Autowired
    private BusiEvaMonitorConfigDao busiEvaMonitorConfigDao;
    @Autowired
    private BusiEvaMonitorUnitDao busiEvaMonitorUnitDao;
    @Autowired
    private BusiEvaMonitorUnitIndicatorsDao busiEvaMonitorUnitIndicatorsDao;
    @Autowired
    private BusiEvaMonitorEquipmentDao busiEvaMonitorEquipmentDao;

    @Reference(check = false)
    private BusiSensorService busiSensorService;

    @Override
    public List<BusiEvaMonitorEquipmentVo> findBusiEvaMonitorEquipmentList() {
        return busiEvaMonitorConfigMapper.findBusiEvaMonitorEquipmentList();
    }

    @Override
    public List<BusiEvaMonitorUnitVo> findBusiEvaMonitorUnitList(String equipTypeId) {
        return busiEvaMonitorConfigMapper.findBusiEvaMonitorUnitList(equipTypeId);
    }

    @Override
    public List<BusiEvaMonitorUnitIndicatorsVo> findBusiEvaMonitorUnitIndicators(String unitId) {
        return busiEvaMonitorConfigMapper.findBusiEvaMonitorUnitIndicators(unitId);
    }

    @Override
    public List<BusiSensorVo> findSensorList(String evaMonitorEquipmentTypeId, String evaMonitorUnitId) {
        BusiEvaMonitorEquipment busiEvaMonitorEquipment = busiEvaMonitorEquipmentDao.get(evaMonitorEquipmentTypeId);
        BusiEvaMonitorUnit busiEvaMonitorUnit = busiEvaMonitorUnitDao.get(evaMonitorUnitId);
        if (busiEvaMonitorEquipment == null || busiEvaMonitorUnit == null) {
            throw new OwlException("基础数据配置错误，请联系管理员");
        }
        SiteTreeEnum siteTreeEnum = SiteTreeEnum.fromValue(busiEvaMonitorEquipment.getCode());
        String[] equipmentTypes =
            StringUtils.isEmpty(busiEvaMonitorUnit.getCode()) ? null : busiEvaMonitorUnit.getCode().split(",");
        return busiSensorService.findSensorList(siteTreeEnum, equipmentTypes);
    }

    @Override
    public List<BusiEvaMonitorUnitIndicatorsVo> findIndicatorsBySensorCode(String sensorCode) {
        return busiEvaMonitorConfigMapper.findIndicatorsBySensorCode(sensorCode);
    }

    @Override
    public PageInfo<BusiEvaMonitorConfigVo>
        findBusiEvaMonitorConfigPage(BusiEvaMonitorConfigDto busiEvaMonitorConfigDto) {
        return PageHelper.startPage(busiEvaMonitorConfigDto.getPage(), busiEvaMonitorConfigDto.getLimit())
            .doSelectPageInfo(() -> busiEvaMonitorConfigMapper.selectBusiEvaMonitorConfigPage(busiEvaMonitorConfigDto));
    }

    @Override
    public synchronized int saveOrUpdate(String token, BusiEvaMonitorConfigDto busiEvaMonitorConfigDto) {
        // 监测设备
        BusiEvaMonitorEquipment busiEvaMonitorEquipment =
            busiEvaMonitorEquipmentDao.get(busiEvaMonitorConfigDto.getMonitorTypeId());
        // 监测单元
        BusiEvaMonitorUnit busiEvaMonitorUnit = busiEvaMonitorUnitDao.get(busiEvaMonitorConfigDto.getMonitorUnitId());
        // 考评指标
        BusiEvaMonitorUnitIndicators busiEvaMonitorUnitIndicators =
            busiEvaMonitorUnitIndicatorsDao.get(busiEvaMonitorConfigDto.getIndicatorsId());
        if (busiEvaMonitorEquipment == null || busiEvaMonitorUnit == null || busiEvaMonitorUnitIndicators == null) {
            throw new OwlException("考评指标数据配置错误，请联系管理员");
        }
        // 重复性校验
        String sensorId = busiEvaMonitorConfigMapper.checkExist(busiEvaMonitorConfigDto.getSensorId(),
            busiEvaMonitorConfigDto.getIndicatorsId(), busiEvaMonitorConfigDto.getId());
        if (!StringUtils.isEmpty(sensorId)) {
//            throw new OwlException(sensorId + "的" + busiEvaMonitorUnitIndicators.getName() + "配置已存在，不能重复添加");
        	log.info(sensorId + "的" + busiEvaMonitorUnitIndicators.getName() + "配置已存在，不能重复添加");
        	return 1;
        }
        // 用户
        LocalUser user = UserUtil.getLocalUser(token);
        // 保存实体
        BusiEvaMonitorConfig busiEvaMonitorConfig = new BusiEvaMonitorConfig();
        BeanUtils.copyPropertiesWithIgnoreNull(busiEvaMonitorConfigDto, busiEvaMonitorConfig);
        if (StringUtils.isEmpty(busiEvaMonitorConfig.getId())) {
            busiEvaMonitorConfig.setCreatedTime(LocalDateTime.now());
            if (user != null) {
                busiEvaMonitorConfig.setCreator(user.getUid());
            }
        } else {
            busiEvaMonitorConfig.setModifiedTime(LocalDateTime.now());
            if (user != null) {
                busiEvaMonitorConfig.setModifier(user.getUid());
            }
        }
        busiEvaMonitorConfig.setStatus(Status.NORMAL.getValue());
        busiEvaMonitorConfig.setType(busiEvaMonitorUnit.getType());
//        BusiSensorVo busiSensorVo = busiSensorService.getBusiSensorVo(
//            SiteTreeEnum.fromValue(busiEvaMonitorUnit.getType()), busiEvaMonitorConfigDto.getSensorId());
//        if (busiSensorVo == null) {
////            throw new OwlException("传感器编码不存在或者已被删除：" + busiEvaMonitorConfigDto.getSensorId());
//        	log.info("传感器编码不存在或者已被删除");
//        	return 1;
//        }
//        busiEvaMonitorConfig.setSensorName(busiSensorVo.getSensorName());
//        busiEvaMonitorConfig.setBrandName(busiSensorVo.getSensorBrand());
        busiEvaMonitorConfig.setEquipmentType(busiEvaMonitorConfigDto.getEquipmentType());
        return busiEvaMonitorConfigDao.saveOrUpdate(busiEvaMonitorConfig);
    }

    @Override
    public BusiEvaMonitorConfigVo findBusiEvaMonitorConfigVo(String id) {
        return busiEvaMonitorConfigMapper.findBusiEvaMonitorConfigVo(id);
    }

    @Override
    public int deleteBusiEvaMonitorConfig(String token, String[] ids) {
        if (ids == null || ids.length == 0) {
            return 0;
        }
        int count = 0;
        LocalUser user = UserUtil.getLocalUser(token);
        for (String id : ids) {
            BusiEvaMonitorConfig busiEvaMonitorConfig = busiEvaMonitorConfigDao.get(id);
            if (busiEvaMonitorConfig == null) {
                continue;
            }
            busiEvaMonitorConfig.setStatus(Status.DELETE.getValue());
            if (user != null) {
                busiEvaMonitorConfig.setModifier(user.getUid());
            }
            busiEvaMonitorConfig.setModifiedTime(LocalDateTime.now());
            busiEvaMonitorConfigDao.updateLocal(busiEvaMonitorConfig);
        }
        return count;
    }

    @Override
    public Map<String, Object> exportBusiEvaMonitorConfig(BusiEvaMonitorConfigDto busiEvaMonitorConfigDto) {
        Map<String, Object> returnMap = new HashMap<>();
        List<BusiEvaMonitorConfigVo> arresterReadTableList =
            busiEvaMonitorConfigMapper.exportBusiEvaMonitorConfigData(busiEvaMonitorConfigDto);
        returnMap.put("fileName", String.format("%s", "考评指标数据"));
        returnMap.put("title", String.format("%s", "考评指标数据"));
        returnMap.put("data", arresterReadTableList);
        return returnMap;
    }

	@Override
	public BusiEvaMonitorUnitVo findBusiEvaMonitorUnit(String equipmentType, String type) {
		// TODO Auto-generated method stub
		return busiEvaMonitorConfigMapper.findBusiEvaMonitorUnit(equipmentType, type);
	}

	@Override
	public List<BusiEvaMonitorRefVo> findBusiEvaMonitorRefList(String unitId,String phase) {
		// TODO Auto-generated method stub
		return busiEvaMonitorConfigMapper.findBusiEvaMonitorRefList(unitId,phase);
	}

	@Override
	public List<BusiEvaMonitorUnitIndicatorsVo> findBusiEvaMonitorUnitIndicatorsList(String sensorId) {
		// TODO Auto-generated method stub
		return busiEvaMonitorConfigMapper.findBusiEvaMonitorUnitIndicatorsList(sensorId);
	}

	@Override
	public int deleteBusiEvaMonitorConfig(String sensorId) {
		// TODO Auto-generated method stub
		return busiEvaMonitorConfigMapper.deleteBusiEvaMonitorConfig(sensorId);
	}
}