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

import java.lang.reflect.ParameterizedType;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Maps;
import com.huatek.busi.common.BusiConstant;
import com.huatek.busi.common.SiteConstants.ArresterTreeEnum;
import com.huatek.busi.common.SiteConstants.GisTreeEnum;
import com.huatek.busi.common.SiteConstants.OtherTreeEnum;
import com.huatek.busi.common.SiteConstants.SiteTreeEnum;
import com.huatek.busi.common.SiteConstants.TransfromerTreeEnum;
import com.huatek.busi.common.util.Tools;
import com.huatek.busi.dto.curve.BaseCurveQueryDto;
import com.huatek.busi.dto.curve.PointItemDto;
import com.huatek.busi.dto.monitor.BusiOnlineMonitorDataDto;
import com.huatek.busi.entity.BusiOnlineMonitorData;
import com.huatek.busi.service.PageUtility;
import com.huatek.busi.service.curve.BaseCurveSensorService;
import com.huatek.busi.service.monitor.BaseMonitorDataTaskService;
import com.huatek.busi.service.monitor.BusiOnlineMonitorDataService;
import com.huatek.busi.service.pointtable.PointTableEtlService;
import com.huatek.busi.service.threshold.PhotoThresholdService;
import com.huatek.busi.vo.PhotoThresholdVo;
import com.huatek.busi.vo.curve.PointItemVo;
import com.huatek.busi.vo.monitor.BusiOnlineMonitorDataVo;
import com.huatek.torch.sql.beans.Pojo;

/**
 * 104数据接口抽象实现
 *
 * @author anker cheng
 *
 * @Date 2019年7月2日
 */
public abstract class AbstractPointTableEtlService<T extends Pojo>
    implements PointTableEtlService, BaseMonitorDataTaskService, BaseCurveSensorService, PageUtility {
    protected final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    protected BusiOnlineMonitorDataService busiOnlineMonitorDataService;
    @Autowired
    private PhotoThresholdService photoThresholdService;

    private Class<?> persistentClass;

    public AbstractPointTableEtlService() {
        this.persistentClass =
            (Class<?>)((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    }

    @Override
    public Class<?> persistentClass() {
        return persistentClass;
    }

    // *****************************在线监测监测数据部分***********************\\
    @Override
    public void doDailyMonitorDataStatistics(LocalDate day) {
        List<Map<String, Object>> monitorDataList =
            this.queryMonitorDataList(day.atStartOfDay(), day.plusDays(1).atStartOfDay());
        if (CollectionUtils.isEmpty(monitorDataList)) {
            return;
        }
        // 保存
        for (Map<String, Object> item : monitorDataList) {
            String sensorCode = Tools.popString(item, "sensorCode");
            String mainTreeId = Tools.popString(item, "mainTreeId");
            String runState = Tools.popString(item, "runState");
            String siteId = Tools.popString(item, "siteId");
            // 生成对象
            BusiOnlineMonitorData busiOnlineMonitorData =
                busiOnlineMonitorDataService.generateBusiOnlineMonitorData(day, sensorCode,runState);
            busiOnlineMonitorData.setSiteId(siteId);
            busiOnlineMonitorData.setMainTreeId(mainTreeId);
            busiOnlineMonitorData.setRunState(runState);
            this.saveBusiOnlineMonitorData(busiOnlineMonitorData, item);
        }
    }

    protected List<Map<String, Object>> queryMonitorDataList(LocalDateTime startTime, LocalDateTime endTime) {
        return null;
    }

    protected void saveBusiOnlineMonitorData(BusiOnlineMonitorData busiOnlineMonitorData, Map<String, Object> item) {
        busiOnlineMonitorDataService.saveBusiOnlineMonitorData(busiOnlineMonitorData, JSONObject.toJSONString(item));
    }

    @Override
    @SuppressWarnings("unchecked")
    public PageInfo<BusiOnlineMonitorDataVo> findBusiOnlineMonitorDataPage(BusiOnlineMonitorDataDto param) {
        PageInfo<BusiOnlineMonitorDataVo> pageInfo =
            busiOnlineMonitorDataService.selectBusiOnlineMonitorDataPage(param);
        if (pageInfo == null || pageInfo.getList() == null) {
            return pageInfo;
        }
        pageInfo.getList().stream().forEach(e -> {
            e.setStabilityIndexMap(Maps.newHashMapWithExpectedSize(0));
            e.setThresholdDataMap(thresholdDataMap(e));
            // 设置阈值显示
            if (e.getThresholdDataMap() == null) {
                e.setThresholdDataMap(Maps.newHashMapWithExpectedSize(0));
            }
            // 设置监测数据
            if(!StringUtils.isEmpty(e.getData())) {
                e.setMonitorDataMap(JSONObject.parseObject(e.getData(), Map.class));
            }else {
                e.setMonitorDataMap(Maps.newHashMapWithExpectedSize(0));
            }
            //其他值
            e.setOtherDataMap(Maps.newHashMapWithExpectedSize(0));
        });
        return pageInfo;
    }
    
    /**
     * 导出在线监测数据
     */
    @Override
    @SuppressWarnings("unchecked")
    public List<BusiOnlineMonitorDataVo> exportBusiOnlineMonitorDataPage(BusiOnlineMonitorDataDto param) {
       List<BusiOnlineMonitorDataVo> resultList = busiOnlineMonitorDataService.selectBusiOnlineMonitorData(param);
       resultList.stream().forEach(e -> {
            e.setStabilityIndexMap(Maps.newHashMapWithExpectedSize(0));
            e.setThresholdDataMap(thresholdDataMap(e));
            // 设置阈值显示
            if (e.getThresholdDataMap() == null) {
                e.setThresholdDataMap(Maps.newHashMapWithExpectedSize(0));
            }
            // 设置监测数据
            if(!StringUtils.isEmpty(e.getData())) {
                e.setMonitorDataMap(JSONObject.parseObject(e.getData(), Map.class));
            }else {
                e.setMonitorDataMap(Maps.newHashMapWithExpectedSize(0));
            }
            //其他值
            e.setOtherDataMap(Maps.newHashMapWithExpectedSize(0));
            //转换相位
            e.setSensorposition(BusiConstant.Phase.getName(e.getSensorposition()));
            //转换主设备类型
            if (e.getEquipmentType().equals(SiteTreeEnum.BYQ_EQM.getValue())) {
            	e.setEquipmentType(SiteTreeEnum.BYQ_EQM.getName());
            	e.setSubEquipmentType(TransfromerTreeEnum.getName(e.getSubEquipmentType()));
            }
            if (e.getEquipmentType().equals(SiteTreeEnum.GIS_HL_EQM.getValue())) {
            	e.setEquipmentType(SiteTreeEnum.GIS_HL_EQM.getName());
            	e.setSubEquipmentType(GisTreeEnum.getName(e.getSubEquipmentType()));
            }
            if (e.getEquipmentType().equals(SiteTreeEnum.CW_HL_EQM.getValue())) {
            	e.setEquipmentType(SiteTreeEnum.CW_HL_EQM.getName());
            }
            if (e.getEquipmentType().equals(SiteTreeEnum.BLQ_HL_EQM.getValue())) {
            	e.setEquipmentType(SiteTreeEnum.BLQ_HL_EQM.getName());
            	e.setSubEquipmentType(ArresterTreeEnum.getName(e.getSubEquipmentType()));
            }
            if (e.getEquipmentType().equals(SiteTreeEnum.OTHER_EQM.getValue())) {
            	e.setEquipmentType(SiteTreeEnum.OTHER_EQM.getName());
            	e.setSubEquipmentType(OtherTreeEnum.getName(e.getSubEquipmentType()));
            }
            //转换监测设备类型
            
        });
        return resultList;
    }
    /**
     * 阈值查询方法
     * 
     * @param vo
     * @return
     */
    protected Map<String, Object> thresholdDataMap(BusiOnlineMonitorDataVo vo) {
        PhotoThresholdVo photoThresholdVo = photoThresholdService.queryPhotoThreshold(vo.getSensorCode(),
            vo.getRunState(), SiteTreeEnum.BYQ.getValue());
        if (photoThresholdVo == null) {
            return Collections.emptyMap();
        }
        Map<String, Object> tMap = Maps.newLinkedHashMapWithExpectedSize(1);
        tMap.put("threshold", photoThresholdVo.getThreshold());
        return tMap;
    }

    // *****************************数据输导出部分*****************************\\
    @Override
    public Map<String, Object> findPointTablePageData(Map<String, Object> params) {
        throw new UnsupportedOperationException();
    }

    @Override
    public Map<String, Object> exportPointTableData(Map<String, Object> params) {
        throw new UnsupportedOperationException();
    }

    // *****************************趋势图部分********************************\\
    @Override
    public List<BaseCurveQueryDto> findSensorCodeList(LocalDate day) {
        return null;
    }

    @Override
    public List<PointItemVo> findDaylyPointList(BaseCurveQueryDto baseCurve, LocalDate day, String subType) {
        return null;
    }

    @Override
    public PointItemDto getDaylyPointStatistics(BaseCurveQueryDto param) {
        return null;
    }
}