package com.dbnt.faisp.menuMgt;

import com.dbnt.faisp.menuMgt.mapper.MenuMgtMapper;
import com.dbnt.faisp.menuMgt.model.MenuMgt;
import com.dbnt.faisp.menuMgt.repository.MenuMgtRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import javax.persistence.Transient;
import java.util.List;

@Service
@RequiredArgsConstructor
public class MenuMgtService {

  private final MenuMgtRepository menuMgtRepository;
  private final MenuMgtMapper menuMgtMapper;

  public List<MenuMgt> selectMenuMgtList(MenuMgt menuMgt){
    List<MenuMgt> menuList = menuMgtMapper.selectMenuMgtList(menuMgt);
    return menuListRowspanSet(menuList);
  }

  public Integer selectMenuMgtListCnt(MenuMgt menuMgt){
    return menuMgtMapper.selectMenuMgtListCnt(menuMgt);
  }

  @Transient
  public String saveMenuMgt(MenuMgt menuMgt) {
    if(menuMgt.getMenuKey()==null){
      MenuMgt duplMenu = menuMgtRepository.findTopByCat1CdAndCat2CdAndCat3Cd(menuMgt.getCat1Cd(), menuMgt.getCat2Cd(), menuMgt.getCat3Cd());
      if(duplMenu!=null){
        return duplMenu.getMenuUrl();
      }else{
        menuMgtRepository.save(menuMgt);
        return "";
      }
    }else{
      menuMgtRepository.save(menuMgt);
      return "";
    }
  }

  @Transient
  public void deleteMenuMgt(List<MenuMgt> menuList) {
    menuMgtRepository.deleteAll(menuList);
  }

  private List<MenuMgt> menuListRowspanSet(List<MenuMgt> menuList){
    for(int i=0; i<menuList.size()-1; i++){
      int rowspanCnt = 1;
      for(int j=i+1; j<menuList.size(); j++){
        if(menuList.get(i).getCat1Cd().equals(menuList.get(j).getCat1Cd())){
          menuList.get(j).setCat1RowspanCnt(0);
          rowspanCnt++;
        }else{
          menuList.get(i).setCat1RowspanCnt(rowspanCnt);
          i=j-1;
          break;
        }
      }
      if(menuList.get(i).getCat1RowspanCnt()==null){
        menuList.get(i).setCat1RowspanCnt(rowspanCnt);
      }
    }

    for(int i=0; i<menuList.size()-1; i++){
      int rowspanCnt = 1;
      for(int j=i+1; j<menuList.size(); j++){
        if(menuList.get(i).getCat2Cd().equals(menuList.get(j).getCat2Cd())){
          menuList.get(j).setCat2RowspanCnt(0);
          rowspanCnt++;
        }else{
          menuList.get(i).setCat2RowspanCnt(rowspanCnt);
          i=j-1;
          break;
        }
      }
      if(menuList.get(i).getCat2RowspanCnt()==null){
        menuList.get(i).setCat2RowspanCnt(rowspanCnt);
      }
    }
    return menuList;
  }
}
