package com.jiayue.ipfcst.fileupload.service;

import com.jiayue.ipfcst.common.core.exception.BusinessException;
import com.jiayue.ipfcst.common.data.entity.*;
import com.jiayue.ipfcst.common.data.repository.InverterInfoRepository;
import com.jiayue.ipfcst.common.data.repository.UploadObjectRepository;
import com.jiayue.ipfcst.common.data.repository.WindTurbineInfoRepository;
import com.jiayue.ipfcst.common.data.service.BaseService;
import com.jiayue.ipfcst.common.data.service.uploadfilerule.IUploadFileRuleService;
import lombok.extern.slf4j.Slf4j;
import net.sf.ehcache.Cache;
import net.sf.ehcache.Element;
import net.sf.ehcache.search.Attribute;
import net.sf.ehcache.search.Query;
import net.sf.ehcache.search.Result;
import net.sf.ehcache.search.Results;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 上报对象业务层
 *
 * @author xsl
 * @version 3.0
 */
@Service
@Slf4j
public class UploadObjectService extends BaseService {
  @Autowired
  UploadObjectRepository uploadObjectRepository;
  @Autowired
  EhCacheCacheManager ehCacheCacheManager;
  @Autowired
  private Map<String, IUploadFileService> uploadFileServiceMap;
  @Autowired
  private WindTurbineInfoRepository windTurbineInfoRepository;
  @Autowired
  private InverterInfoRepository inverterInfoRepository;

  /**
   * 保存上报对象
   *
   * @param uploadObject 上报对象信息
   */
  @Transactional(propagation = Propagation.SUPPORTS)
  public void save(UploadObject uploadObject) {
    clearUploadObjectCache();
    uploadObjectRepository.save(uploadObject);
  }

  @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
  public UploadObject saveCloud(UploadObject uploadObject) {
    return uploadObjectRepository.save(uploadObject);
  }
  @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
  public void saveCloud(List<UploadObject> beans) {
    if(beans != null && beans.size() > 0){
      clearUploadObjectCache();
      uploadObjectRepository.deleteAll();
      uploadObjectRepository.saveAll(beans);
    }
  }

  /**
   * 删除上报对象
   *
   * @param id 上报对象信息
   */
  @Transactional(propagation = Propagation.SUPPORTS)
  public void delete(Integer id) {
    clearUploadObjectCache();
    uploadObjectRepository.deleteById(id);
  }

  /**
   * 移除缓存中的上报对象信息
   */
  public void clearUploadObjectCache() {
    List<UploadObject> uploadObjectList = this.get();
    Cache cache = ehCacheCacheManager.getCacheManager().getCache("searchablecache");
    for (UploadObject uploadObject : uploadObjectList) {
      cache.remove("uo" + uploadObject.getId());
    }
  }

  /**
   * 查询上报对象信息
   *
   * @return 上报对象信息
   */
  public List<UploadObject> get() {
    Cache cache = ehCacheCacheManager.getCacheManager().getCache("searchablecache");
    Query query = cache.createQuery();
    //查询结果中包含Key和value
    query.includeKeys().includeValues();
    Attribute<String> keyName = cache.getSearchAttribute("key");
    query.addCriteria(keyName.ilike("*uo*"));
    Results results = query.execute();
    List<Result> resultList = results.all();

    List<UploadObject> list = new ArrayList();
    if (resultList != null && !resultList.isEmpty()) {
      for (Result result : resultList) {
        UploadObject e = (UploadObject) result.getValue();
        list.add(e);
      }
      results.discard();
    } else {
      //查询数据库
      list = uploadObjectRepository.findAll();
      for (UploadObject uploadObject : list) {
        //将结果存入缓存
        cache.put(new Element("uo" + uploadObject.getId(), uploadObject));
      }
    }
    return list;
  }

  /**
   * 获取省份对应上报文件类型
   *
   * @return 上报对象信息
   */
  public Map<String,String> getUploadFileType() {
    Map<String,String> uploadFileTypeMap = new HashMap<>();
    try {
      ElectricField electricField = super.getElectricField();
      // 获取未生成的文件信息
      if (uploadFileServiceMap != null) {
        String pro = "";
        if (electricField != null) {
          pro = electricField.getProvinceEnum().name();
        }
        IUploadFileService uploadFileService = uploadFileServiceMap.get(pro.toLowerCase() + "UploadFileService");
        if (uploadFileService instanceof IUploadFileService){
          uploadFileTypeMap = uploadFileService.getUploadFileType();
        }
      }
    } catch (BusinessException e) {
      log.error("获取省份对应上报文件类型失败",e);
    }
    return uploadFileTypeMap;
  }



  /**
   * 检查E402 单机转发上送文件是否符合配置要求
   *
   * @return Boolean
   */
  public Boolean checkE402() throws BusinessException {
    ElectricField electricField = super.getElectricField();
    if (electricField.getElectricFieldTypeEnum().name().equals("E1")) {
      List<InverterInfo> inverterInfos = inverterInfoRepository.findAll();
      List<InverterInfo> collect = inverterInfos.stream().filter(i -> i.getReport()).collect(Collectors.toList());
      if(collect.size()>0){
        return true;
      }
    } else {
      List<WindTurbineInfo> windTurbineInfos = windTurbineInfoRepository.findAll();
      List<WindTurbineInfo> collect = windTurbineInfos.stream().filter(w -> w.getReport()).collect(Collectors.toList());
      if(collect.size()>0){
        return true;
      }
    }

    return false;
  }





}
