package com.dbnt.kcscbackend.admin.config.service;

import com.dbnt.kcscbackend.admin.boards.entity.TnBbs;
import com.dbnt.kcscbackend.admin.config.entity.TbMenuRole;
import com.dbnt.kcscbackend.admin.config.entity.TcMenu;
import com.dbnt.kcscbackend.admin.config.entity.TnPartnerSite;
import com.dbnt.kcscbackend.admin.config.mapper.TcMenuMapper;
import com.dbnt.kcscbackend.admin.config.repository.TbMenuRoleRepository;
import com.dbnt.kcscbackend.admin.config.repository.TcMenuRepository;
import com.dbnt.kcscbackend.admin.config.repository.TnPartnerSiteRepository;
import com.dbnt.kcscbackend.auth.entity.LoginVO;
import com.dbnt.kcscbackend.commonCode.entity.TcCodeGrp;
import com.dbnt.kcscbackend.commonCode.entity.TcCodeItem;
import com.dbnt.kcscbackend.commonCode.repository.TcCodeGrpRepository;
import com.dbnt.kcscbackend.commonCode.repository.TcCodeItemRepository;
import com.dbnt.kcscbackend.file.entity.TnAttachFile;
import com.dbnt.kcscbackend.file.service.FileService;
import lombok.RequiredArgsConstructor;
import org.egovframe.rte.fdl.cmmn.EgovAbstractServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
@RequiredArgsConstructor
public class AdminConfigService extends EgovAbstractServiceImpl {

  private final TcCodeGrpRepository codeGrpRepository;
  private final TcCodeItemRepository codeItemRepository;
  private final TcMenuRepository menuRepository;
  private final TbMenuRoleRepository menuRoleRepository;
  private final TcMenuMapper menuMapper;
  private final TnPartnerSiteRepository tnPartnerSiteRepository;
  private final FileService fileService;

  public List<TcCodeGrp> selectCodeGrpList(){
    return codeGrpRepository.findByUseYn("Y");
  }

  @Transactional
  public String addCodeGrp(TcCodeGrp codeGrp) {
    TcCodeGrp savedGrp = codeGrpRepository.findById(codeGrp.getGrpCd()).orElse(null);
    if(savedGrp!=null){
      if(savedGrp.getUseYn().equals("Y")){
        return "isSaved";
      }else{
        savedGrp.setGrpCdNm(codeGrp.getGrpCdNm());
        savedGrp.setUseYn("Y");
        codeGrpRepository.save(savedGrp);
        return savedGrp.getGrpCd();
      }
    }else{
      codeGrpRepository.save(codeGrp);
      return codeGrp.getGrpCd();
    }
  }

  @Transactional
  public String modifyCodeGrp(TcCodeGrp codeGrp) {
    TcCodeGrp savedGrp = codeGrpRepository.findById(codeGrp.getGrpCd()).orElse(null);
    if (savedGrp != null) {
      savedGrp.setGrpCdNm(codeGrp.getGrpCdNm());
      savedGrp.setLastChgId(codeGrp.getLastChgId());
      savedGrp.setLastChgDt(codeGrp.getLastChgDt());
      savedGrp.setUseYn(codeGrp.getUseYn());
      codeGrpRepository.save(savedGrp);
      return "modified";
    }else{
      return "validGrpCd";
    }
  }

  public List<TcCodeItem> selectCodeItemList(String grpCd){
    return codeItemRepository.findByGrpCdAndUseYnOrderByGrpOrder(grpCd, "Y");
  }
  @Transactional
  public String addCodeItem(TcCodeItem codeItem) {
    TcCodeItem savedItem = codeItemRepository.findById(
        new TcCodeItem.TcCodeItemId(codeItem.getItemCd(), codeItem.getGrpCd())
    ).orElse(null);
    if(savedItem!=null){
      if(savedItem.getUseYn().equals("Y")){
        return "isSaved";
      }else{
        savedItem.setItemNm(savedItem.getItemNm());
        savedItem.setUseYn("Y");
        codeItemRepository.save(savedItem);
        return savedItem.getGrpCd();
      }
    }else{
      codeItemRepository.save(codeItem);
      return codeItem.getItemCd();
    }
  }

  @Transactional
    public String modifyCodeItem(TcCodeItem codeItem) {
      TcCodeItem savedItem = codeItemRepository.findById(
              new TcCodeItem.TcCodeItemId(codeItem.getItemCd(), codeItem.getGrpCd())
      ).orElse(null);
      if (savedItem != null) {
        savedItem.setItemNm(codeItem.getItemNm());
        savedItem.setLastChgId(codeItem.getLastChgId());
        savedItem.setLastChgDt(codeItem.getLastChgDt());
        savedItem.setGrpOrder(codeItem.getGrpOrder());
        savedItem.setUseYn(codeItem.getUseYn());
        codeItemRepository.save(savedItem);
        return "modified";
      }else{
        return "validGrpCd";
      }
    }

    public List<TcMenu> selectMenuList() {
      return menuMapper.selectMenuList();
  }

  @Transactional
  public void saveMenu(TcMenu menu, String userId) {
    TcMenu savedMenu = menuRepository.findById(menu.getMenuId()).orElse(null);
    if(savedMenu==null){
      menu.setFrstCrtDt(LocalDateTime.now());
      menu.setFrstCrtId(userId);
      menu.setUseYn("Y");
      menuRepository.save(menu);
    }else{
      savedMenu.setMenuTitle(menu.getMenuTitle());
      savedMenu.setMenuGroup(menu.getMenuGroup());
      savedMenu.setMenuLevel(menu.getMenuLevel());
      savedMenu.setMenuSort(menu.getMenuSort());
      savedMenu.setMenuUrl(menu.getMenuUrl());
      savedMenu.setMenuTypeCd(menu.getMenuTypeCd());
      savedMenu.setUseYn("Y");
      savedMenu.setLastChgId(userId);
      savedMenu.setLastChgDt(LocalDateTime.now());
      menuRepository.save(savedMenu);
    }
  }

  @Transactional
  public String deleteMenu(String menuId, String userId) {
    TcMenu savedMenu = menuRepository.findById(menuId).orElse(null);
    if(savedMenu==null){
      return "notFind";
    }else{
      savedMenu.setUseYn("N");
      savedMenu.setLastChgDt(LocalDateTime.now());
      savedMenu.setLastChgId(userId);
      return null;
    }
  }

  public List<TcMenu> selectMenuAuthList(){
    return menuMapper.selectMenuAuthList();
  }

  @Transactional
  public void editMenuAuth(TcMenu menu) {
    String[] roleAry = menu.getMenuAuth().split(",");
    menuRoleRepository.deleteByMenuId(menu.getMenuId());
    List<TbMenuRole> roleList = new ArrayList<>();
    for(String role: roleAry){
      if(!role.isEmpty()){
        TbMenuRole menuRole = new TbMenuRole();
        menuRole.setMenuId(menu.getMenuId());
        menuRole.setRoleId(role);
        menuRole.setWriteYn("Y");
        roleList.add(menuRole);
      }
    }
    menuRoleRepository.saveAll(roleList);
  }

  public List<TnPartnerSite> selectPartnerSiteList() {
    return tnPartnerSiteRepository.findAllByOrderBySiteOrder();
  }

  /**
   * 파일이 저장될 중간 경로를 생성한다.
   * D:/kcscUploadFiles/XXXX/abc.jpg XXXX에 해당하는 경로다.
   *
   * @return 중간 경로
   */
  private String getMiddlePath() {
    //파일이 저장될 경로를 생성한다.
    String domainPath = "partnerSite";
    Date nowDate = new Date();
    String strNowYyyy = new SimpleDateFormat("yyyy").format(nowDate);
    String strNowYyyyMmdd = new SimpleDateFormat("yyyyMMdd").format(nowDate);
    String middlePath = domainPath + "/" + strNowYyyy + "/" + strNowYyyyMmdd + "/";

    return middlePath;
  }

  public void savePartnerSite(TnPartnerSite tnPartnerSite, HttpServletRequest request, LoginVO user, MultipartFile[] file) throws Exception {
    if (tnPartnerSite.getSiteSeq() == null) {
      String fileGrpId = fileService.addTnAttachFile(request, user, file, this.getMiddlePath());
      tnPartnerSite.setFileGrpId(fileGrpId);
      tnPartnerSiteRepository.save(tnPartnerSite);
    } else {
      String fileGrpId = tnPartnerSite.getFileGrpId();
      System.out.println("@@@ fileGrpId : " + fileGrpId);
      if (file != null && file.length > 0) {
        List<TnAttachFile> tnAttachFileList = fileService.findByFileGrpId(fileGrpId);
        if (tnAttachFileList != null) {
            for (TnAttachFile item : tnAttachFileList) {
                fileService.deleteTnAttachFile(request, user, item.getFileSeq().longValue());
            }
        }
        fileGrpId = fileService.addTnAttachFile(request, user, file, this.getMiddlePath());
      }
      TnPartnerSite savedPartnerSite = tnPartnerSiteRepository.findById(tnPartnerSite.getSiteSeq()).orElse(null);
      savedPartnerSite.setSiteTitle(tnPartnerSite.getSiteTitle());
      savedPartnerSite.setSiteUrl(tnPartnerSite.getSiteUrl());
      savedPartnerSite.setFileGrpId(tnPartnerSite.getFileGrpId());
      savedPartnerSite.setSiteOrder(tnPartnerSite.getSiteOrder());
      savedPartnerSite.setUseYn(tnPartnerSite.getUseYn());
      savedPartnerSite.setFileGrpId(fileGrpId);
      tnPartnerSiteRepository.save(savedPartnerSite);
    }
  }

  @Transactional
  public String deletePartnerSite(TnPartnerSite tnPartnerSite, String userId) {
    Optional<TnPartnerSite> optionalTnPartnerSite = tnPartnerSiteRepository.findById(tnPartnerSite.getSiteSeq());
    optionalTnPartnerSite.ifPresent(partnerSite -> {
      tnPartnerSiteRepository.delete(partnerSite);
    });
    return optionalTnPartnerSite.isPresent() ? null : "notFind";
  }

}