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.SubsidiaryEquipmentInfo;
import com.jiayue.ipfcst.common.data.repository.SubsidiaryEquipmentInfoRepository;
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 修唯
 * @version 3.0
 */
@Service
@Slf4j
public class SubsidiaryEquipmentInfoService {
  @Autowired
  SubsidiaryEquipmentInfoRepository subsidiaryEquipmentInfoRepository;

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

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

  }

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

  }

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

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

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