package com.jiayue.ipfcst.console.service;

import com.jiayue.ipfcst.common.core.exception.BusinessException;
import com.jiayue.ipfcst.common.core.util.SpringContextHolder;
import com.jiayue.ipfcst.common.data.entity.BoosterStationInfo;
import com.jiayue.ipfcst.common.data.entity.SubsidiaryEquipmentInfo;
import com.jiayue.ipfcst.common.data.repository.BoosterStationInfoRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Optional;

/**
 * 升压站信息service类
 *
 * @author zy
 * @version 3.0
 */
@Service
@Slf4j
public class BoosterStationInfoService {
  @Autowired BoosterStationInfoRepository boosterStationInfoRepository;

  /*
  * 查询
  * */
  public List<BoosterStationInfo> getAll(){
    return boosterStationInfoRepository.findAll();
  }

  /*
  * 保存
  * */
  public void save(BoosterStationInfo boosterStationInfo){
    try{
      boosterStationInfo.setStationCode(SpringContextHolder.getBean(ElectricFieldService.class).get().getStationCode());
      boosterStationInfoRepository.save(boosterStationInfo);
    }catch (Exception e){
      log.error("系统错误", e);
    }
  }

  /*
  *
  * 删除
  */
  public void delete(Integer id) throws BusinessException {
    if (StringUtils.isEmpty(id)) {
      throw new BusinessException("升压站编号不能为空!");
    } else {
      boosterStationInfoRepository.deleteById(id);
    }
  }

  /**
   * 查询升压站
   *
   * @param no 升压站编号
   * @return 升压站
   * @throws BusinessException 业务异常
   */
  @Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = true)
  public BoosterStationInfo get(final Integer no) throws BusinessException {
    Optional<BoosterStationInfo> optional = boosterStationInfoRepository.findById(no);
    if (optional.isPresent()) {
      return optional.get();
    } else {
      throw new BusinessException("升压站不存在!");
    }
  }

  /**
   * 场站运维状态下进行数据更新操作
   * @param boosterStationInfo
   */
  @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
  public void saveCloud(BoosterStationInfo boosterStationInfo) {
    boosterStationInfoRepository.save(boosterStationInfo);
  }

  /**
   * 场站未运维状态下进行数据清空及入库
   * @param boosterStationInfoList
   */
  @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
  public void saveCloud(List<BoosterStationInfo> boosterStationInfoList) {
    if(boosterStationInfoList != null && boosterStationInfoList.size() > 0){
      boosterStationInfoRepository.deleteAll();
      boosterStationInfoRepository.saveAll(boosterStationInfoList);
    }
  }


}
