package com.dbnt.faisp.main.fpiMgt.sri.service;

import com.dbnt.faisp.config.BaseService;
import com.dbnt.faisp.config.FileInfo;
import com.dbnt.faisp.main.fpiMgt.sri.mapper.SriMapper;
import com.dbnt.faisp.main.fpiMgt.sri.model.Sri;
import com.dbnt.faisp.main.fpiMgt.sri.model.SriFile;
import com.dbnt.faisp.main.fpiMgt.sri.model.SriReadUser;
import com.dbnt.faisp.main.fpiMgt.sri.repository.SriFileRepository;
import com.dbnt.faisp.main.fpiMgt.sri.repository.SriReadUserRepository;
import com.dbnt.faisp.main.fpiMgt.sri.repository.SriRepository;
import com.dbnt.faisp.main.userInfo.model.UserAlarm;
import com.dbnt.faisp.main.userInfo.service.UserAlarmService;
import lombok.RequiredArgsConstructor;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;


@Service
@RequiredArgsConstructor
public class SriService extends BaseService {

  private final UserAlarmService userAlarmService;
  private final SriRepository sriRepository;
  private final SriReadUserRepository sriReadUserRepository;
  private final SriFileRepository sriFileRepository;
  private final SriMapper sriMapper;
  
  @Value("${file.dir}")
  protected String fileDir;
  @Value("${file.dir.sri}")
  protected String sriDir;
  
  
  public List<Sri> selectSriList(Sri sri) {
	  return sriMapper.selectSriList(sri);
  }
  
  public Integer selectSriCnt(Sri sri) {
	return sriMapper.selectSriCnt(sri);
  }
  
  @Transactional
  public Integer saveSriBoard(Sri sri, List<Integer> deleteFileSeq) {
	  Integer faSriKey = sriRepository.save(sri).getFaSriKey();
	    if(deleteFileSeq!=null && deleteFileSeq.size()>0){
	      deleteFaRptFile(faSriKey, deleteFileSeq);
	    }
	    if(sri.getMultipartFileList() != null){
	      saveUploadFiles(faSriKey, sri.getMultipartFileList());
	    }
	    if(sri.getReadUserList() != null){
	      saveSriReadUser(faSriKey, sri.getReadUserList());
	    }

	    return faSriKey;
  }

  @Transactional
  public Sri selectFaSriBoard(Integer faSriKey, Integer userSeq) {
	  Sri sri = sriRepository.findById(faSriKey).orElse(null);
	    if(sri != null){
	    	sri.setFileList(sriFileRepository.findByFaSriKey(faSriKey));
	    	sri.setReadUserList(sriReadUserRepository.findByFaSriKey(faSriKey));
	      if(sri.getStatus().equals("DST007")){
	        for(SriReadUser readUser: sri.getReadUserList()){
	          if(readUser.getUserSeq().equals(userSeq)){
	            readUser.setReadYn("T");
	            sriReadUserRepository.save(readUser);
	          }
	        }
	      }
	    }
	    return sri;
	}



  private void saveSriReadUser(Integer faSriKey, List<SriReadUser> readUserList) {
	  sriReadUserRepository.deleteByFaSriKey(faSriKey);
    List<UserAlarm> alarmList = new ArrayList<>();
    LocalDateTime dateTime = LocalDateTime.now();
    for(SriReadUser readUser: readUserList){
      readUser.setFaSriKey(faSriKey);
      UserAlarm alarm = userAlarmService.makeUserAlarm
          (dateTime, readUser.getUserSeq(), faSriKey, 40, "SRI에 수신 문서가 있습니다.");
      alarmList.add(alarm);
    }
    userAlarmService.saveAlarmList(alarmList);
    sriReadUserRepository.saveAll(readUserList);
  }

  private void saveUploadFiles(Integer faSriKey, List<MultipartFile> multipartFileList) {
    SriFile lastFile = sriFileRepository.findTopByFaSriKeyOrderByFileSeq(faSriKey).orElse(null);
    int fileSeq = lastFile==null?1:(lastFile.getFileSeq()+1);
    for(MultipartFile file: multipartFileList){
      String saveName = UUID.randomUUID().toString();
      String path = fileDir+sriDir;
      saveFile(file, new File(path+File.separator+saveName));

      String originalFilename = file.getOriginalFilename();
      int extnIdx = originalFilename.lastIndexOf(".");
      SriFile fileInfo = new SriFile();
      fileInfo.setFaSriKey(faSriKey);
      fileInfo.setFileSeq(fileSeq++);
      fileInfo.setOrigNm(originalFilename.substring(0, extnIdx));
      fileInfo.setFileExtn(originalFilename.substring(extnIdx+1));
      fileInfo.setConvNm(saveName);
      fileInfo.setFileSize(calculationSize(file.getSize()));
      fileInfo.setSavePath(path);
      sriFileRepository.save(fileInfo);
    }
  }

  private void deleteFaRptFile(Integer faSriKey, List<Integer> deleteFileSeq) {
    List<SriFile> fileList = sriFileRepository.findByFaSriKey(faSriKey);
    for(SriFile file: fileList){
      if(deleteFileSeq.contains(file.getFileSeq())){
        deleteStoredFile(new File(file.getSavePath(), file.getConvNm()));
        sriFileRepository.delete(file);
      }
    }
  }

  public FileInfo selectFaSriFile(Integer faSriKey, Integer fileSeq) {
	return sriFileRepository.findById(new SriFile.SriFileId(faSriKey, fileSeq)).orElse(null);
  }
  
  @Transactional
  public void sriDelete(List<Sri> sri) {
	  for(Sri sriData : sri) {
		  Sri dbSri = sriRepository.findById(sriData.getFaSriKey()).orElse(null);
		  dbSri.setStatus("DST008");
		  sriRepository.save(dbSri);
	  }
  }



 
}