package com.jiayue.ipfcst.console.service;

import com.jiayue.ipfcst.common.data.constant.enums.FileTypeEnum;
import com.jiayue.ipfcst.common.data.entity.ElectricField;
import com.jiayue.ipfcst.common.data.entity.UploadFileCode;
import com.jiayue.ipfcst.common.data.entity.UploadFileType;
import com.jiayue.ipfcst.common.data.repository.UploadFileCodeRepository;
import com.jiayue.ipfcst.common.data.repository.UploadFileTypeRepository;
import com.jiayue.ipfcst.fileupload.service.UploadFileCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class UploadFileTypeService {
  @Autowired
  UploadFileTypeRepository uploadFileTypeRepository;
  @Autowired
  ElectricFieldService electricFieldService;
  @Autowired
  UploadFileCodeRepository uploadFileCodeRepository;
  @Autowired
  UploadFileCodeService uploadFileCodeService;

  @Transactional
  public boolean uploadFileTypeIntoUploadCode(){
    try {
      uploadFileCodeRepository.deleteAll();

      ElectricField electricField = electricFieldService.get();

      List<UploadFileType> uploadFileTypes = uploadFileTypeRepository.findByProvinceEnum(electricField.getProvinceEnum().name());

      List<UploadFileCode> uploadFileCodes = new ArrayList<>();

      uploadFileTypes.forEach(t->{
        UploadFileCode uploadFileCode = new UploadFileCode();
        uploadFileCode.setFileTypeCode(Integer.parseInt(t.getUploadCode()));
        uploadFileCode.setFileTypeEnum(FileTypeEnum.valueOf(t.getFileTypeEnum()));
        uploadFileCodes.add(uploadFileCode);
      });
      uploadFileCodeService.clearFileCodeCache();
      uploadFileCodeRepository.saveAll(uploadFileCodes);

      return true;
    }catch (Exception e){
      e.printStackTrace();
      return false;
    }

  }
}
