package com.oqpo.api.service.system;


import com.oqpo.api.entity.system.NumbEntity;
import com.oqpo.api.exception.GlobalException;
import com.oqpo.api.mapper.system.NumbMapper;
import com.oqpo.api.service.CommonService;
import com.oqpo.api.web.dto.request.numb.SaveNumbRequest;
import com.oqpo.api.web.dto.response.numb.NumbResponse;
import com.oqpo.api.web.dto.response.numb.NumbSearchListResponse;
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;

@Service
@Slf4j
public class NumbService extends CommonService {
    @Autowired
    private NumbMapper mumbMapper;

    /*
    채번 조회
     */
    public NumbSearchListResponse selectSearchNumbList(String sUseYn, String sNumNm) throws Exception {
        List<NumbEntity> entities = mumbMapper.selectSearchNumbList(sUseYn, sNumNm);
        return NumbSearchListResponse.toDTO(entities);
    }


    /*
      채번  정보 조회
    */
    public NumbResponse selectNumbInfo(String numNo) throws Exception {

        return NumbResponse.toDTO(mumbMapper.selectNumbInfo(Integer.parseInt(numNo)));
    }

    /*
      채번관리 - 저장
     */
    @Transactional
    public void saveNumb(String userId, SaveNumbRequest saveNumbRequest) throws Exception {
        try {
            // 기본정보 저장
            NumbEntity entity = new NumbEntity();
            entity.setNumNo(saveNumbRequest.getNumNo());
            entity.setDefiInfo(saveNumbRequest.getDefiInfo());
            entity.setNumNm(saveNumbRequest.getNumNm());
            entity.setYearChk(saveNumbRequest.getYearChk());
            entity.setMonthChk(saveNumbRequest.getMonthChk());
            entity.setDayChk(saveNumbRequest.getDayChk());
            entity.setNumStNo(saveNumbRequest.getNumStNo());
            entity.setNumEdNo(saveNumbRequest.getNumEdNo());
            entity.setUseYn(saveNumbRequest.getUseYn());

            if ("C".equals(saveNumbRequest.getViewCd())) {
                mumbMapper.insertNumbInfo(userId, entity);
            } else if ("U".equals(saveNumbRequest.getViewCd())) {
                mumbMapper.updateNumbInfo(userId, entity);
            }

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


}
