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


import com.icomsys.main_vm.biz.rcp.oprManage.service.OprManageBgmService;
import com.icomsys.main_vm.biz.common.login.service.LoginService;
import com.icomsys.main_vm.db.jpa.entity.oprManage.TbBgmMng;
import com.icomsys.main_vm.biz.rcp.oprManage.vo.OprManageBgmVO;
import com.icomsys.main_vm.db.jpa.repo.oprManage.TbBgmMngRepo;
import com.icomsys.main_vm.db.mybatis.alias.OprManageBgmListVo;
import com.querydsl.core.QueryResults;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
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.servlet.http.HttpServletRequest;
import java.io.*;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

@Controller
@Slf4j
@RequiredArgsConstructor
@RequestMapping("/admin/rcp/oprmanage")
public class OprManageBgmController {

    private final LoginService loginService;

    @Autowired
    private final OprManageBgmService oprManageBgmService;
    private final TbBgmMngRepo tbBgmMngRepo;
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${feign.url.bgmpath}")
    private String bgmPath;

    @GetMapping("/bgm/manage.do")
    public String bgmManageView(){
        return "/adm/rcp/oprmanage/bgm";
    }

    @GetMapping("/bgm/manage2.do")
    public String bgmManageView2(){
        return "/adm/rcp/oprmanage/bgm2";
    }




    @PostMapping("/bgm/upload-local")
    @ResponseBody
    public ResponseEntity<Object> uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            File path = new File("C:\\Users\\hyunj\\Downloads\\target_wav\\" + file.getOriginalFilename());
            path.createNewFile();
            FileOutputStream output = new FileOutputStream(path);
            output.write(file.getBytes());
            output.close();
            return new ResponseEntity<>("file Upload", HttpStatus.OK);
            //return ResponseHandler.generateResponse("File is uploaded successfully!", HttpStatus.OK, path);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<>("Invalid file format.", HttpStatus.BAD_REQUEST);
            //return ResponseHandler.generateResponse(e.getMessage(), HttpStatus.MULTI_STATUS, null);
        }
    }

    public int insertBGM(OprManageBgmVO vo,String fileName) {
        //if (!tbBgmMngRepo.existsByUserId("sysadmin")) {

        TbBgmMng save1 = TbBgmMng.builder()
                .registId(vo.getRegistId())
                .custCode(vo.getCustCode())
                .fileName(fileName)
                .filePath("files/" + bgmPath)
                .registDate(LocalDateTime.now().toString())
                .build();
        tbBgmMngRepo.save(save1);
        //}

        int result = 1;
        return result;
    }


    @GetMapping("/bgm/list.do")
    @ResponseBody
    public QueryResults<OprManageBgmListVo> selectBgmList(HttpServletRequest req, OprManageBgmVO vo) {
        String searchKeyword = req.getParameter("searchKeyword");
        vo.setSearchKeyword(searchKeyword);

        QueryResults<OprManageBgmListVo> result = tbBgmMngRepo.selectBgmList(vo);

        return result;
    }

    /*
    @GetMapping("/bgm/list.do")
    @ResponseBody
    public List<HashMap> bgmList(@RequestBody OprManageBgmListVo vo) {
        List<HashMap> result = oprManageBgmService.selectBgmList(vo);

        return result;
    }
     */

    @RequestMapping(value = "/bgm/play.do", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public String playRecordFile(@RequestBody String fileName) {

        return oprManageBgmService.playRecordFileFromS3(fileName);
    }

    @javax.annotation.Resource
    MappingJackson2JsonView ajaxMainView;
    @PostMapping(value ="/bgm/upload.do")
    @ResponseBody
    public ModelAndView uploadWav(MultipartHttpServletRequest request, OprManageBgmVO vo) {

        vo.setCustCode(loginService.getUserVo().getCustCode());
        vo.setRegistId(loginService.getUserVo().getUserId());
        ModelAndView mv = new ModelAndView(ajaxMainView);

        List<MultipartFile> files = request.getFiles("fileList");
        boolean result = true;
        String message = "저장되었습니다.";

        try {
            Map<String, MultipartFile> mfiles = request.getFileMap();

            Iterator<Map.Entry<String, MultipartFile>> itr = mfiles.entrySet().iterator();

            MultipartFile mFile;

            List<String> fileNameList = oprManageBgmService.uploadBgm(files);
            //로컬테스트시 파일리스트 임의추가
//            List<String> fileNameList = new ArrayList<>();
//            fileNameList.add("filaName4");
//            fileNameList.add("filaName5");
//            fileNameList.add("filaName6");
            log.info(fileNameList.toString());

            boolean finalResult = result;
            String finalMessage = message;
            AtomicInteger idx = new AtomicInteger();
            fileNameList.forEach(filename -> {
                log.info("filename123 : " + filename);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date now = new Date();
                String nowTime = sdf.format(now);

                insertBGM(vo, filename);

            });

        } catch(Exception e) {
            result = false;
            message = "처리도중 오류가 발생했습니다.";
            log.error("error upload excel", e);
        }


        return mv;
    }

}
