package com.oqpo.api.service.system;

import com.oqpo.api.entity.oper.AuthDtlEntity;
import com.oqpo.api.entity.oper.AuthEntity;
import com.oqpo.api.exception.GlobalException;
import com.oqpo.api.mapper.system.AuthMapper;
import com.oqpo.api.service.CommonService;
import com.oqpo.api.web.dto.request.GridRequest;
import com.oqpo.api.web.dto.request.auth.SaveAuthRequest;
import com.oqpo.api.web.dto.response.GridResponse;
import com.oqpo.api.web.dto.response.auth.AuthDtlResponse;
import com.oqpo.api.web.dto.response.auth.AuthInfoResponse;
import com.oqpo.api.web.dto.response.auth.AuthSearchListResponse;
import com.oqpo.api.web.dto.response.auth.AuthSearchResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

@Service
@Slf4j
public class AuthService extends CommonService {
    @Autowired
    private AuthMapper authMapper;

    /*
        권한관리 - 권한 검색
     */
    public AuthSearchListResponse searchAuthList(String sTopMenuNo, String sAuthTpCd,  String sUseYn, String sAuthNm) throws Exception {

        List<AuthEntity> entities = authMapper.selectSearchAuthList(sAuthTpCd, sTopMenuNo, sUseYn, sAuthNm);
        return AuthSearchListResponse.toDTO(entities);
    }

    /*
       권한 헤더 정보 조회
     */
    public AuthInfoResponse selectAuthInfo(String authNo) throws Exception {
        return AuthInfoResponse.toDTO(authMapper.selectAuthInfo(authNo));
    }

    /*
      권한 상세 리스트 조회
     */
    public GridResponse authDtlGridList(String authNo, GridRequest gridRequest) throws Exception {
        int gridPage = gridRequest.getGridPage();
        int gridSize = gridRequest.getGridSize();
        int gridRecords = authMapper.selectAuthDtlGridListCnt(authNo);
        int gridTotal = fnCalculateGridTotal(gridSize, gridRecords);
        List<AuthEntity> entities = authMapper.selectAuthDtlGridList(authNo, gridRequest);
        List<Object> gridRows = entities.stream()
                .map(m -> AuthDtlResponse.builder()
                        .viewCd("R")
                        .authNo(m.getAuthNo())
                        .topMenuNm(m.getTopMenuNm())
                        .menuNo(m.getAuthDtl().getMenuNo())
                        .menuNm(m.getAuthDtl().getMenuNm())
                        .writeYn(m.getAuthDtl().getWriteYn())
                        .useYn(m.getAuthDtl().getUseYn())
                        .build())
                .collect(Collectors.toList());
        return GridResponse.toDTO(gridPage, gridTotal, gridRecords, gridRows);
    }

    /*
      권한 중목체크
    */
    public  String selectAuthDupYn(String authNo) throws Exception {
        return authMapper.selectAuthDupYn(authNo);
    }

    /*
      권한관리 - 저장
     */
    @Transactional
    public void saveAuth(String userId, SaveAuthRequest saveAuthRequest) throws Exception {
        try {
            // 기본정보 저장
            AuthEntity entity = new AuthEntity();
            entity.setAuthNo(saveAuthRequest.getAuthNo());
            entity.setAuthNm(saveAuthRequest.getAuthNm());
            entity.setAuthTpCd(saveAuthRequest.getAuthTpCd());
            entity.setTopMenuNo(saveAuthRequest.getTopMenuNo());
            entity.setUseYn(saveAuthRequest.getUseYn());

            if ("C".equals(saveAuthRequest.getViewCd())) {
                authMapper.insertAuthInfo(userId, entity);
            } else if ("U".equals(saveAuthRequest.getViewCd())) {
                authMapper.updateAuthInfo(userId, entity);
            }

            //  권한 상세 정보 저장
            // 신규건
            List<AuthDtlEntity> gridInsertData = saveAuthRequest.toAuthEntities(saveAuthRequest.getGridInsertData());
            if (gridInsertData.size() > 0) {
                authMapper.insertAuthDtl(userId, gridInsertData) ;
            }
            // 수정건
            List<AuthDtlEntity> gridUpdateData = saveAuthRequest.toAuthEntities(saveAuthRequest.getGridUpdateData());
            if (gridUpdateData.size() > 0) {
                authMapper.updateAuthDtl(userId, gridUpdateData) ;
            }
            // 삭제건
            List<AuthDtlEntity> gridDeleteData = saveAuthRequest.toAuthEntities(saveAuthRequest.getGridDeleteData());
            if (gridDeleteData.size() > 0) {
                authMapper.deleteAuthDtl(entity.getAuthNo(), gridDeleteData) ;
            }
        } catch (GlobalException e) {
            e.getStackTrace();
            throw new GlobalException(e.getSystemMessageCode());
        } catch (Exception e) {
            e.getStackTrace();
            throw new RuntimeException();
        }
    }



    /*
      권한 상세 리스트 조회
     */
    public GridResponse authSearchGridList( String authTpCd, String sAuthTpCd,  String sAuthNm, GridRequest gridRequest) throws Exception {
        int gridPage = gridRequest.getGridPage();
        int gridSize = gridRequest.getGridSize();
        int gridRecords = authMapper.selectAuthSearchGridListCnt(authTpCd, sAuthTpCd, sAuthNm);
        int gridTotal = fnCalculateGridTotal(gridSize, gridRecords);
        List<AuthEntity> entities = authMapper.selectAuthSearchGridList(authTpCd, sAuthTpCd, sAuthNm, gridRequest);
        List<Object> gridRows = entities.stream()
                .map(m -> AuthSearchResponse.builder()
                        .viewCd("R")
                        .authNo(m.getAuthNo())
                        .authNm(m.getAuthNm())
                        .topMenuNo(m.getTopMenuNo())
                        .topMenuNm(m.getTopMenuNm())
                        .build())
                .collect(Collectors.toList());
        return GridResponse.toDTO(gridPage, gridTotal, gridRecords, gridRows);
    }
}
