package com.dbnt.sims.fpiMgt.affair.service;


import com.dbnt.sims.config.BaseService;
import com.dbnt.sims.config.FileInfo;
import com.dbnt.sims.fpiMgt.affair.mapper.AffairMapper;
import com.dbnt.sims.fpiMgt.affair.model.*;
import com.dbnt.sims.fpiMgt.affair.repository.*;
import com.dbnt.sims.userInfo.model.UserInfo;
import lombok.RequiredArgsConstructor;
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.List;
import java.util.UUID;

@Service
@RequiredArgsConstructor
public class AffairService extends BaseService { // 견문보고
  private final AffairBoardRepository affairBoardRepository;
  private final AffairFileRepository affairFileRepository;
  private final AffairRatingRepository affairRatingRepository;
  private final HashTagRepository hashTagRepository;
  private final HashTagLinkRepository hashTagLinkRepository;
  private final AffairMapper affairMapper;

  public List<AffairBoard> selectAffairBoardList(AffairBoard affair){
    return affairMapper.selectAffairBoardList(affair);
  }
  public Integer selectAffairBoardListCnt(AffairBoard affair){
    return affairMapper.selectAffairBoardCnt(affair);
  }

  public AffairBoard selectAffairBoard(Integer affairKey){
    AffairBoard affair = affairBoardRepository.findById(affairKey).orElse(null);
    if(affair != null){
      affair.setHashTags(affairMapper.selectHashTags(affairKey));
      affair.setFileList(affairFileRepository.findByAffairKey(affairKey));
      affair.setRateList(affairRatingRepository.findByAffairKeyOrderByRatingOrganAsc(affairKey));
    }
    return affair;
  }
  @Transactional
  public Integer saveAffairBoard(AffairBoard affair, List<Integer> deleteFileSeq){
    Integer affairKey = affairBoardRepository.save(affair).getAffairKey();
    String[] hashTagAry = affair.getHashTags().split(" ");
    if(hashTagAry.length>0){
      saveHashTagLink(affairKey, hashTagAry);
    }
    if(deleteFileSeq != null && deleteFileSeq.size()>0){
      deleteAffairFile(affairKey, deleteFileSeq);
    }
    if(affair.getMultipartFileList()!=null){
      saveUploadFiles(affairKey, affair.getMultipartFileList());
    }

    AffairRating rating = affairRatingRepository.findById(new AffairRating.AffairRatingId(affairKey,affair.getWrtOrgan())).orElse(null);
    if(rating == null){
      rating = new AffairRating();
      rating.setAffairKey(affairKey);
      rating.setRatingOrgan(affair.getWrtOrgan());
    }
    rating.setAffairStatus(affair.getAffairStatus());
    affairRatingRepository.save(rating);

    return affairKey;
  }

  private void saveHashTagLink(Integer affairKey, String[] hashTagAry){
    hashTagLinkRepository.deleteByAffairKey(affairKey);
    for(String tagNm : hashTagAry){
      HashTag savedTag = hashTagRepository.findByTagNm(tagNm).orElse(null);
      Integer tagKey;
      if(savedTag==null){
        HashTag tag = new HashTag();
        tag.setTagNm(tagNm);
        tagKey = hashTagRepository.save(tag).getTagKey();
      }else{
        tagKey = savedTag.getTagKey();
      }
      HashTagLink hashTagLink = new HashTagLink();
      hashTagLink.setAffairKey(affairKey);
      hashTagLink.setTagKey(tagKey);
      hashTagLinkRepository.save(hashTagLink);
    }
  }
  private void deleteAffairFile(Integer affairKey, List<Integer> deleteFileSeq) {
    List<AffairFile> affairFileList = affairFileRepository.findByAffairKey(affairKey);
    for(AffairFile file: affairFileList){
      if(deleteFileSeq.contains(file.getFileSeq())){
        deleteStoredFile(new File(file.getSavePath(), file.getConvNm()));
        affairFileRepository.delete(file);
      }
    }
  }
  private void saveUploadFiles(Integer affairKey, List<MultipartFile> multipartFileList){
    AffairFile lastFileInfo = affairFileRepository.findTopByAffairKeyOrderByFileSeqDesc(affairKey).orElse(null);
    int fileSeq = lastFileInfo==null?1:(lastFileInfo.getFileSeq()+1);
    for(MultipartFile file : multipartFileList){
      String saveName = UUID.randomUUID().toString();
      String path = locationPath+File.separator+"affair"+File.separator;
      saveFile(file, new File(path+File.separator+saveName));

      String originalFilename = file.getOriginalFilename();
      int extnIdx = originalFilename.lastIndexOf(".");
      AffairFile fileInfo = new AffairFile();
      fileInfo.setAffairKey(affairKey);
      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);
      affairFileRepository.save(fileInfo);
    }
  }

  @Transactional
  public Integer affairStateChange(UserInfo loginUser, List<AffairRating> ratingList) {
    for(AffairRating rating : ratingList){
      AffairRating savedRating = affairRatingRepository.findById(new AffairRating.AffairRatingId(rating.getAffairKey(), loginUser.getOgCd())).orElse(null);
      if(savedRating != null){
        if(rating.getHeadApprv() == null){
          savedRating.setSectionNm(loginUser.getUserNm());
          savedRating.setSectionApprvDt(LocalDateTime.now());
          savedRating.setSectionApprv(rating.getSectionApprv());
          savedRating.setSectionEtc(rating.getSectionEtc());
          savedRating.setAffairStatus(rating.getSectionApprv());
        }else{
          savedRating.setHeadNm(loginUser.getUserNm());
          savedRating.setHeadApprvDt(LocalDateTime.now());
          savedRating.setHeadApprv(rating.getHeadApprv());
          savedRating.setHeadEtc(rating.getHeadEtc());
          savedRating.setAffairRate(rating.getAffairRate());
          savedRating.setOrganUp(rating.getOrganUp()==null?"F":rating.getOrganUp());
          savedRating.setAffairStatus(rating.getHeadApprv());
          if(savedRating.getOrganUp().equals("T")){
            List<String> organList = loginUser.getUpOrganCdList();
            String upOrgan = organList.get(organList.indexOf(savedRating.getRatingOrgan())-1);
            AffairRating upRating = new AffairRating();
            upRating.setRatingOrgan(upOrgan);
            upRating.setAffairKey(savedRating.getAffairKey());
            upRating.setAffairStatus("DST002");
            affairRatingRepository.save(upRating);
          }
        }
        affairRatingRepository.save(savedRating);
      }
    }
    return ratingList.size()>1?0:ratingList.get(0).getAffairKey();
  }

  public FileInfo selectAffairFile(Integer parentKey, Integer fileSeq) {
    return affairFileRepository.findById(new AffairFile.AffairFileId(parentKey, fileSeq)).orElse(null);
  }
}
