package com.jiayue.ipfcst.console.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import com.jiayue.ipfcst.common.core.exception.BusinessException;
import com.jiayue.ipfcst.common.core.util.DateTimeUtil;
import com.jiayue.ipfcst.common.core.util.JsonBeanUtil;
import com.jiayue.ipfcst.common.data.entity.ElectricField;
import com.jiayue.ipfcst.common.data.entity.OverhaulPlan;
import com.jiayue.ipfcst.common.data.entity.PowerStationStatusData;
import com.jiayue.ipfcst.common.data.entity.SysParameter;
import com.jiayue.ipfcst.common.data.repository.ElectricFieldRepository;
import com.jiayue.ipfcst.common.data.repository.OverhaulPlanRepository;
import com.jiayue.ipfcst.console.util.GzipUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 检修计划业务层
 *
 * @author Tangle
 * @version 1.0
 * @since 2020/03/27 10:02
 */
@Service
@Slf4j
public class OverHaulPlanService {
  private final OverhaulPlanRepository overhaulPlanRepository;

  private final ElectricFieldRepository electricFieldRepository;

  @Autowired
  public OverHaulPlanService(OverhaulPlanRepository overhaulPlanRepository,ElectricFieldRepository electricFieldRepository) {
    this.overhaulPlanRepository = overhaulPlanRepository;
    this.electricFieldRepository = electricFieldRepository;
  }

  /**
   * 新增检修计划
   *
   * @param overhaulPlan 检修计划实体
   */
  public void add(OverhaulPlan overhaulPlan) {
    overhaulPlan.setFinalEntryTime(overhaulPlan.getStartTime());
    this.overhaulPlanRepository.save(overhaulPlan);
  }

  /**
   * 修改检修计划信息
   *
   * @param overhaulPlan
   * @throws BusinessException
   */
  public void save(OverhaulPlan overhaulPlan) throws BusinessException {
    if (overhaulPlan.getId() == null) {
      throw new BusinessException("修改时主键不能为空");
    } else {
      Calendar calendar = Calendar.getInstance();
      if (overhaulPlan.getStatus() == 2) {
        calendar.setTime(new Date());
        overhaulPlan.setMcTime(calendar.getTimeInMillis());
      }
      overhaulPlan.setFinalEntryTime(overhaulPlan.getStartTime());
      this.overhaulPlanRepository.save(overhaulPlan);
    }
  }

  /**
   * 删除检修计划信息
   *
   * @param id 主键
   */
  public void delete(final Integer id) {
    this.overhaulPlanRepository.deleteById(id);
  }

  /**
   * 查询检修计划信息（分页）
   */
  public Page<OverhaulPlan> get(final OverhaulPlan overhaulPlan, final Integer page, final Integer size) {
    getAll();
    ExampleMatcher matcher =
      ExampleMatcher.matching().withMatcher("id", ExampleMatcher.GenericPropertyMatchers.contains());
    Example<OverhaulPlan> example = Example.of(overhaulPlan, matcher);
    Pageable pageable = PageRequest.of(page - 1, size);
    return overhaulPlanRepository.findAll(example, pageable);

  }

  /**
   * 查询检修计划信息
   */
  @Transactional
  public List<OverhaulPlan> getAll() {
    List<OverhaulPlan> overhaulPlans = overhaulPlanRepository.findAll();
    List<OverhaulPlan> overhaulPlansResult = new ArrayList<>();
    overhaulPlans.forEach(s->{
      long a = s.getEndTime();
      long b = System.currentTimeMillis();
      if(a< b){
        s.setStatus(2);
        overhaulPlanRepository.save(s);
      }
      overhaulPlansResult.add(s);
    });


    return overhaulPlansResult;

  }

  /**
   * 计算出距离当前最近且在当前时间之后的时间
   *
   * @return
   */
  public OverhaulPlan findByNextTime() {

    List<OverhaulPlan> overhaulPlanList = overhaulPlanRepository.findAll();
    OverhaulPlan overhaulPlan1 = new OverhaulPlan();
    overhaulPlan1.setStartTime(0l);
    if (overhaulPlanList.size() > 0) {

      Long time = System.currentTimeMillis();
      for (OverhaulPlan overhaulPlan : overhaulPlanList) {
        if (overhaulPlan.getStartTime() > time) {
          Long difference = overhaulPlan.getStartTime() - time;
          if (overhaulPlan1.getStartTime() == 0) {
            overhaulPlan1 = overhaulPlan;
          }
          if (difference > 0l && difference < overhaulPlan1.getStartTime()) {
            overhaulPlan1 = overhaulPlan;
          }
        }
      }
    }

    return overhaulPlan1;
  }

  /**
   * 单条数据更新操作
   * @param bean
   */
  @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
  public void saveCloud(OverhaulPlan bean) {
    Optional<OverhaulPlan> optional = overhaulPlanRepository.findById(bean.getId());
    if (optional.isPresent()) {
      bean.setId(optional.get().getId());
    }
    overhaulPlanRepository.save(bean);
  }

  /**
   * 先清空本地数据，再保存新数据
   * @param overhaulPlans
   */
  @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
  public void saveCloud(List<OverhaulPlan> overhaulPlans) {
    if (null != overhaulPlans && overhaulPlans.size() > 0) {
      overhaulPlanRepository.deleteAll();
      overhaulPlanRepository.saveAll(overhaulPlans);
    }
  }

  /**
   * 获取当前时间检修容量
   */
  public BigDecimal getOverhaulCapacity(){
    BigDecimal overhaulCapacity = new BigDecimal(0);
    long time = System.currentTimeMillis();
    List<OverhaulPlan> overhaulPlans = overhaulPlanRepository.findByStartTimeLessThanAndEndTimeGreaterThanAndStatus(time, time, 1);
    if(overhaulPlans.size()>0){
      overhaulCapacity = overhaulPlans.get(0).getOverhaulCapactity();
    }
    return overhaulCapacity;
  }

  /**
   * 检修计划二维码内容生成
   *
   * @return 二维码生成内容集
   * @throws IOException       io异常
   * @throws BusinessException 业务异常
   */
  public List<String> generateOverHaulPlanCodeContent() throws IOException, BusinessException {

    ElectricField electricField = electricFieldRepository.findAll().get(0);

    String content = electricField.getStationCode() + "|";

    List<OverhaulPlan> overhaulPlanList = overhaulPlanRepository.findAll();

    content = JsonBeanUtil.beanToJson(overhaulPlanList);

    List<String> qrCodeContents = GzipUtil.zipList(content);
    List<String> result = new ArrayList<>();
    String taskNo = getTaskNo(electricField);
    for (int i = 0; i < qrCodeContents.size(); i++) {
      JSONObject jsonObject = new JSONObject();
      jsonObject.putOnce("taskNo", taskNo);
      jsonObject.putOnce("taskType", "stationData-jx");
      jsonObject.putOnce("partNo", i + 1);
      jsonObject.putOnce("partTotal", qrCodeContents.size());
      jsonObject.putOnce("data", qrCodeContents.get(i));
      result.add(i, jsonObject.toString());
    }

    return result;
  }

  /**
   * 获取taskNo编号
   *
   * @param electricField 场站对象
   * @return 编号
   */

  private String getTaskNo(ElectricField electricField) {
    Date date = DateUtil.date();
    return electricField.getStationCode() + DateUtil.format(date, "yyMMddHHmmss");
  }



}
