package com.kamco.cd.kamcoback.mapsheet.service;

import com.kamco.cd.kamcoback.common.utils.FIleChecker;
import com.kamco.cd.kamcoback.config.FileConfig;
import com.kamco.cd.kamcoback.mapsheet.dto.MapSheetMngDto;
import com.kamco.cd.kamcoback.mapsheet.dto.MapSheetMngDto.AddReq;
import com.kamco.cd.kamcoback.mapsheet.dto.MapSheetMngDto.DmlReturn;
import com.kamco.cd.kamcoback.mapsheet.dto.MapSheetMngDto.ErrorDataDto;
import com.kamco.cd.kamcoback.mapsheet.dto.MapSheetMngDto.ErrorSearchReq;
import com.kamco.cd.kamcoback.mapsheet.dto.MapSheetMngDto.MngDto;
import com.kamco.cd.kamcoback.mapsheet.dto.MapSheetMngDto.MngFilesDto;
import com.kamco.cd.kamcoback.postgres.core.MapSheetMngCoreService;
import jakarta.validation.Valid;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.List;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

@Service
@RequiredArgsConstructor
@Transactional(readOnly = true)
public class MapSheetMngService {

  private final MapSheetMngCoreService mapSheetMngCoreService;
  private final FileConfig fileConfig;

  public List<MngDto> findMapSheetMngList() {
    return mapSheetMngCoreService.findMapSheetMngList();
  }

  public List<Integer> findMapSheetMngYyyyList() {
    return mapSheetMngCoreService.findMapSheetMngYyyyList();
  }

  public MngDto findMapSheetMng(int mngYyyy) {
    return mapSheetMngCoreService.findMapSheetMng(mngYyyy);
  }

  @Transactional
  public DmlReturn mngComplete(int mngYyyy) {

    mapSheetMngCoreService.MapSheetMngComplete(mngYyyy);

    return new DmlReturn("success", "작업완료 처리되었습니다.");
  }

  public Page<ErrorDataDto> findMapSheetErrorList(@Valid ErrorSearchReq searchReq) {
    return mapSheetMngCoreService.findMapSheetErrorList(searchReq);
  }

  public ErrorDataDto findMapSheetError(Long hstUid) {
    return mapSheetMngCoreService.findMapSheetError(hstUid);
  }

  @Transactional
  public DmlReturn mngDataSave(AddReq AddReq) {
    return mapSheetMngCoreService.mngDataSave(AddReq);
  }

  /*
  public MapSheetMngDto.DmlReturn uploadFile(MultipartFile file, Long hstUid) {
    return mapSheetMngCoreService.uploadFile(file, hstUid);
  }

  public MapSheetMngDto.DmlReturn deleteFile(MapSheetMngDto.DeleteFileReq req) {
    return mapSheetMngCoreService.deleteFile(req);
  }

   */

  public DmlReturn uploadProcess(@Valid List<Long> hstUidList) {
    return mapSheetMngCoreService.uploadProcess(hstUidList);
  }

  public DmlReturn updateExceptUseInference(@Valid List<Long> hstUidList) {
    return mapSheetMngCoreService.updateExceptUseInference(hstUidList);
  }

  @Transactional
  public DmlReturn uploadPair(
      MultipartFile tfwFile,
      MultipartFile tifFile,
      // String targetPath,
      Long hstUid) {

    String rootPath = fileConfig.getRootSyncDir();
    String tmpPath = fileConfig.getTmpSyncDir();

    // 파일 유효성 검증
    if (tfwFile == null || tfwFile.isEmpty() || tfwFile.getSize() == 0) {
      return new DmlReturn("fail", "TFW SIZE 오류");
    } else if (tifFile == null || tifFile.isEmpty() || tifFile.getSize() == 0) {
      return new DmlReturn("fail", "TIF SIZE 오류");
    }

    if (!tfwFile
        .getOriginalFilename()
        .substring(tfwFile.getOriginalFilename().lastIndexOf('.') + 1)
        .toLowerCase()
        .equals("tfw")) {
      return new DmlReturn("fail", "TFW FILENAME ERROR");
    } else if (!tifFile
        .getOriginalFilename()
        .substring(tifFile.getOriginalFilename().lastIndexOf('.') + 1)
        .toLowerCase()
        .equals("tif")) {
      return new DmlReturn("fail", "TIF FILENAME ERROR");
    }

    ErrorDataDto errDto = mapSheetMngCoreService.findMapSheetError(hstUid);
    if (errDto == null) {
      return new DmlReturn("fail", "NO hstUid Data");
    }
    MngDto mngDto = mapSheetMngCoreService.findMapSheetMng(errDto.getMngYyyy());

    String targetYearDir = mngDto.getMngPath();

    List<FIleChecker.Basic> basicTfwList =
        FIleChecker.getFilesFromAllDepth(
            targetYearDir, tfwFile.getOriginalFilename(), "tfw", 100, "name", 0, 100);

    List<FIleChecker.Basic> basicTifList =
        FIleChecker.getFilesFromAllDepth(
            targetYearDir, tifFile.getOriginalFilename(), "tif", 100, "name", 0, 100);

    int tfwCnt =
        (int)
            basicTfwList.stream()
                .filter(dto -> dto.getExtension().toString().equals("tfw"))
                .count();

    int tifCnt =
        (int)
            basicTifList.stream()
                .filter(dto -> dto.getExtension().toString().equals("tif"))
                .count();

    if (tfwCnt > 0 || tifCnt > 0) {
      String tfwMsg = "";
      String tifMsg = "";
      if (tfwCnt > 0) tfwMsg = tfwFile.getOriginalFilename();
      if (tifCnt > 0) tifMsg = tifFile.getOriginalFilename();
      return new DmlReturn("fail", tfwMsg + "," + tifMsg + " DUPLICATE ERROR");
    }

    File directory = new File(tmpPath);
    String tfwTmpPath = tmpPath + tfwFile.getOriginalFilename();
    Path tfwTmpSavePath = Paths.get(tfwTmpPath);
    String tifTmpPath = tmpPath + tifFile.getOriginalFilename();
    Path tifTmpSavePath = Paths.get(tifTmpPath);
    boolean fileUpload = true;
    try {
      tfwFile.transferTo(tfwTmpSavePath);
      tifFile.transferTo(tifTmpSavePath);
    } catch (IOException e) {
      // throw new RuntimeException(e);
      return new DmlReturn("fail", "UPLOAD ERROR");
    }

    if (!FIleChecker.cmmndGdalInfo(tifTmpPath)) return new DmlReturn("fail", "TIF TYPE ERROR");
    if (!FIleChecker.checkTfw(tfwTmpPath)) return new DmlReturn("fail", "TFW TYPE ERROR");

    // 싱크파일목록 가저오기
    List<MngFilesDto> mngFiles = mapSheetMngCoreService.findIdToMapSheetFileList(hstUid);
    String uploadPath = "";
    for (MngFilesDto dto : mngFiles) {
      uploadPath = dto.getFilePath();
      break;
    }

    Path tfwTargetPath = null;
    Path tifTargetPath = null;
    Path uploadTargetPath = null;

    if (uploadPath.isEmpty()) {
      MngFilesDto filesDto =
          mapSheetMngCoreService.findYyyyToMapSheetFilePathRefer(errDto.getMngYyyy());
      String referPath = filesDto.getFilePath();
      uploadPath = Paths.get(referPath).getParent().toString() + "/" + errDto.getRefMapSheetNum();
      tfwTargetPath = Paths.get(uploadPath).resolve(tfwFile.getOriginalFilename());
      tifTargetPath = Paths.get(uploadPath).resolve(tifFile.getOriginalFilename());
    }

    // String searchDir =

    try {
      uploadTargetPath = Paths.get(uploadPath);
      Files.createDirectories(uploadTargetPath);
      Files.move(tfwTmpSavePath, tfwTargetPath, StandardCopyOption.REPLACE_EXISTING);
      Files.move(tifTmpSavePath, tifTargetPath, StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }

    // hst업데이트
    mapSheetMngCoreService.updateMapSheetMngHstSyncCheckState(
        hstUid, uploadPath, tfwFile.getOriginalFilename(), tifFile.getOriginalFilename());
    // 파일정보 업데이트
    mapSheetMngCoreService.deleteByHstUidMngFile(hstUid);

    MapSheetMngDto.MngFileAddReq addReq = new MapSheetMngDto.MngFileAddReq();
    addReq.setMngYyyy(errDto.getMngYyyy());
    addReq.setMapSheetNum(errDto.getMapSheetNum());
    addReq.setRefMapSheetNum(errDto.getRefMapSheetNum());
    addReq.setFilePath(uploadPath);
    addReq.setFileName(tfwFile.getOriginalFilename());
    addReq.setFileExt("tfw");
    addReq.setFileSize(tfwFile.getSize());
    addReq.setHstUid(errDto.getHstUid());
    addReq.setFileState("DONE");

    mapSheetMngCoreService.mngFileSave(addReq);

    addReq.setFileExt("tif");
    addReq.setFileSize(tifFile.getSize());
    mapSheetMngCoreService.mngFileSave(addReq);

    return new DmlReturn("success", "파일 업로드 완료되었습니다.");
  }

  public List<MngFilesDto> findHstUidToMapSheetFileList(Long hstUid) {
    return mapSheetMngCoreService.findHstUidToMapSheetFileList(hstUid);
  }

  @Transactional
  public DmlReturn deleteByFileUidMngFile(List<Long> fileUids) {

    for (Long uid : fileUids) {
      MapSheetMngDto.MngFilesDto dto = mapSheetMngCoreService.findIdToMapSheetFile(uid);
      String filePath = dto.getFilePath() + "/" + dto.getFileName();
      Path path = Paths.get(filePath);
      try {
        boolean isDeleted = Files.deleteIfExists(path);
        if (isDeleted) {
          System.out.println("파일 삭제 성공: " + filePath);
        } else {
          System.out.println("삭제 실패: 파일이 존재하지 않습니다.");
        }
      } catch (IOException e) {
        System.err.println("파일 삭제 중 오류 발생: " + e.getMessage());
      }
      DmlReturn dmlReturn = mapSheetMngCoreService.deleteByFileUidMngFile(uid);
    }

    return new DmlReturn("success", fileUids.size() + "개 파일이 삭제되었습니다.");
  }
}
