package com.oqpo.api.service.system;


import com.oqpo.api.entity.oper.MemberEntity;
import com.oqpo.api.entity.oper.MenuEntity;
import com.oqpo.api.exception.GlobalException;
import com.oqpo.api.mapper.system.MenuMapper;
import com.oqpo.api.service.CommonService;
import com.oqpo.api.web.dto.request.GridRequest;
import com.oqpo.api.web.dto.request.menu.SaveMenuRequest;
import com.oqpo.api.web.dto.response.GridResponse;
import com.oqpo.api.web.dto.response.menu.MenuInfoResponse;
import com.oqpo.api.web.dto.response.menu.MenuPopSearchListResponse;
import com.oqpo.api.web.dto.response.menu.MenuSearchListResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class MenuService extends CommonService {
    @Autowired
    private MenuMapper menuMapper;

    //@Cacheable(value = "authMenuList", key = "'OQKeyIs' + #userId")
    public List<MenuEntity> authMenuList(String userId, MemberEntity memberEntity) throws Exception {
        List<MenuEntity> entities = menuMapper.selectUserAuthMenuList(memberEntity);

        return entities;
    }

    /*
        메뉴관리 - 메뉴 검색
     */
    public MenuSearchListResponse selectAllMenuList() throws Exception {
        List<MenuEntity> entities = menuMapper.selectAllMenuList();
        return MenuSearchListResponse.toDTO(entities);
    }


    /*
      메뉴  정보 조회
    */
    public MenuInfoResponse selectMenuInfo(String menuNo) throws Exception {
        return MenuInfoResponse.toDTO(menuMapper.selectMenuInfo(menuNo));
    }

    /*
      메뉴관리 - 저장
     */
    @CacheEvict(value = {"menuList"}, allEntries = true)
    @Transactional
    public void saveMenu(String userId, SaveMenuRequest saveMenuRequest) throws Exception {
        try {
            // 기본정보 저장
            MenuEntity entity = new MenuEntity();
            entity.setMenuNo(saveMenuRequest.getMenuNo());
            entity.setMenuId(saveMenuRequest.getMenuId());
            entity.setTopMenuNo(saveMenuRequest.getTopMenuNo());
            entity.setMenuNm(saveMenuRequest.getMenuNm());
            entity.setUseYn(saveMenuRequest.getUseYn());
            entity.setViewNum(saveMenuRequest.getViewNum());
            entity.setConnUrl(saveMenuRequest.getConnUrl());
            entity.setIconYn(saveMenuRequest.getIconYn());
            entity.setRoleDesc(saveMenuRequest.getRoleDesc());
            entity.setOpenCd(saveMenuRequest.getOpenCd());

            if ("C".equals(saveMenuRequest.getViewCd())) {
                menuMapper.insertMenu(userId, entity);
            } else if ("U".equals(saveMenuRequest.getViewCd())) {
                menuMapper.updateMenu(userId, entity);
            }

        } catch (GlobalException e) {
            e.getStackTrace();
            throw new GlobalException(e.getSystemMessageCode());
        } catch (Exception e) {
            e.getStackTrace();
            throw new RuntimeException();
        }
    }

    /*
      메뉴관리 - 삭제
     */
    @CacheEvict(value = {"menuList"}, allEntries = true)
    @Transactional
    public void delMenu(String menuNo) throws Exception {
        try {
            menuMapper.deleteMenu(menuNo);

            // 권한의 메뉴 삭제


        } catch (GlobalException e) {
            e.getStackTrace();
            throw new GlobalException(e.getSystemMessageCode());
        } catch (Exception e) {
            e.getStackTrace();
            throw new RuntimeException();
        }
    }

    /*
       메뉴id 중목체크
     */
    public  String selectMenuIdDupYn(String menuId) throws Exception {
        return menuMapper.selectMenuIdDupYn(menuId);
    }


    /*
      Top Menu 리스트
    */
    public List<MenuEntity> selectTopMenuList() throws Exception {
        return menuMapper.selectTopMenuList();
    }

    /*
      권한 메뉴 리스트
    */
    public List<MenuEntity> selectBottomMenuList(String topMenuNo, String authNo) throws Exception {
        return menuMapper.selectBottomMenuList( Integer.parseInt(topMenuNo), authNo);
    }

    /*
      팝업 메뉴 리스트
    */
    public GridResponse selectPopMenuList(String sTopMenuNo, String sMenuNm, GridRequest gridRequest) throws Exception {
        int gridPage = gridRequest.getGridPage();
        int gridSize = gridRequest.getGridSize();
        int gridRecords = menuMapper.selectPopMenuCnt(sTopMenuNo, sMenuNm);
        int gridTotal = fnCalculateGridTotal(gridSize, gridRecords);
        List<MenuEntity> entities = menuMapper.selectPopMenuList(sTopMenuNo, sMenuNm, gridRequest);
        List<Object> gridRows = entities.stream()
                .map(m -> MenuPopSearchListResponse.builder()
                        .viewCd("R")
                        .menuNo(m.getMenuNo())
                        .menuNm(m.getMenuNm())
                        .idPathNm(m.getIdPathNm())
                        .build())
                .collect(Collectors.toList());
        return GridResponse.toDTO(gridPage, gridTotal, gridRecords, gridRows);
    }

    /*
      권한 메뉴 리스트
    */
    public List<MenuEntity> selectMobleMenuList() throws Exception {
        return menuMapper.selectMobleMenuList( );
    }

}
