package com.icomsys.main_vm.biz.rcp.oprManage.service;

import com.icomsys.main_vm.biz.rcp.oprManage.dto.BgmDto;
import com.icomsys.main_vm.db.jpa.entity.oprManage.TbBgmMng;
import com.icomsys.main_vm.db.jpa.repo.oprManage.TbBgmMngRepo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Slf4j
@RequiredArgsConstructor
public class OprManageBgmService2 {

    @Autowired
    private final TbBgmMngRepo tbBgmMngRepo;

    @Transactional
    public String saveFile(MultipartFile file, BgmDto bgmDto) {
        //file save logic implement
        //if not exist folder, make new directory
        File fileFolder = new File(bgmDto.getFilePath());

        try {
            if (!fileFolder.exists()) {
                if (fileFolder.mkdir()) {
                    log.info("[file mkdirs] : Success");
                } else {
                    log.error("[file mkdirs] : Fail");
                }
            }

            String saveFileName = bgmDto.getFileName();
            String saveFilePath = bgmDto.getFilePath() + File.separator + bgmDto.getFileName();

            File saveFile = new File(saveFilePath);
            if (saveFile.isFile()) {

                boolean _exist = true;

                int index = 0;

                // 중복 파일 검사
                while (_exist) {
                    index++;

                    String fileName = file.getOriginalFilename();
                    String fileCutName = fileName.substring(0, fileName.lastIndexOf("."));
                    String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1);

                    saveFileName = fileCutName + "_" + index + "." + fileExt;
                    String dictFile = bgmDto.getFilePath() + File.separator + saveFileName;
                    _exist = new File(dictFile).isFile();

                    if (!_exist) {
                        saveFilePath = dictFile;
                    }
                }
                file.transferTo(new File(saveFilePath));
            } else {
                file.transferTo(saveFile);
            }
        } catch (Exception e) {
            log.error("save file error", e);
        }

        return tbBgmMngRepo.save(bgmDto.toEntity()).getFileName();
    }

    // 전체 조회
    @Transactional
    public ModelAndView searchFiles(Map<String, String> dataMap) {
        ModelAndView mv = new ModelAndView(ajaxMainView);
        HashMap emap = new HashMap();
        emap.putAll(dataMap);

        var fileList = tbBgmMngRepo.findAll();

        mv.addObject("fileList", fileList);
        return mv;
    }

    // 파일명 조회
    @Transactional
    public BgmDto searchFile(String filename) {
        TbBgmMng file = tbBgmMngRepo.findById(filename).get();

        BgmDto bgmDto = BgmDto.builder()
                .fileName(file.getFileName())
                .filePath(file.getFilePath())
                .custCode(file.getCustCode())
                .registId(file.getRegistId())
//                .registDate(file.getRegistDate())
                .build();
        return bgmDto;
    }


    public Optional<TbBgmMng> findByFilename(String s) {
        return tbBgmMngRepo.findById(s);
    }



    @Resource
    MappingJackson2JsonView ajaxMainView;

    public void insertInferenceExcel(MultipartHttpServletRequest request, HashMap<String, String> eMap) throws Exception {
        // excel 관련
        MultipartFile file = request.getFile("upFile");
        List<String> testList = this.readExcelFile(file);

        // file 관련
        Calendar c = Calendar.getInstance();
        c.clear();
        c.setTime(new Date());
        SimpleDateFormat sdfForPath = new SimpleDateFormat("yyyy\\MM\\");

        // DB저장 데이터 및 파일 데이터
        String uploadfileName = file.getOriginalFilename();
        String uploadFilePath = StringUtils.join(sdfForPath.format(c.getTime()));
        String testCnt = Integer.toString(testList.size());

        // 업로드 파일 저장
        this.createDirs(uploadFilePath);
        File uploadFIle = new File(StringUtils.join(uploadFilePath, uploadfileName));
        file.transferTo(uploadFIle);

        eMap.put("uploadFileName", uploadfileName);
        eMap.put("uploadFilePath", uploadFilePath);
        eMap.put("testCnt", testCnt);

        log.info("# UPLOAD PATH : {}", uploadFilePath);
        log.info("# MAP : {}", eMap.toString());

//        // 성공
//        if(StringUtils.equals(returnCode, "000")) {
//            eMap.put("testResult", testResult);
//
//        }
//        // 실패
//        else {
//            eMap.put("testResult", testResult);
//        }
    }



    /**
     * 파일 저장 디렉토리 생성
     */
    private void createDirs(String path) throws IOException {
        try {
            Files.createDirectories(Paths.get(path));
        } catch(FileAlreadyExistsException faee) {
            log.info("이미 존재하는 디렉토리 입니다.");
        }
    }

    /**
     * 유저가 업로드한 엑셀 파일 Read
     */
    private List<String> readExcelFile(MultipartFile file) throws IOException {

        List<String> testList = new ArrayList<String>();

        return testList;
    }


}
