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.AGC_AVCInfo;
import com.jiayue.ipfcst.common.data.entity.InverterInfo;
import com.jiayue.ipfcst.common.data.repository.AGC_AVCInfoRepository;
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;

/**
 * AGC_AVC信息service类
 *
 * @author zy
 * @version 3.0
 */
@Service
@Slf4j
public class AGC_AVCInfoService {
  @Autowired AGC_AVCInfoRepository agcAvcInfoRepository;

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

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

  }

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

  }

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

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

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