package com.oqpo.api.service.oper;


import com.oqpo.api.entity.oper.FileEntity;
import com.oqpo.api.entity.oper.NticeEntity;
import com.oqpo.api.entity.oper.NticeTargetEntity;
import com.oqpo.api.exception.GlobalException;
import com.oqpo.api.mapper.FileMapper;
import com.oqpo.api.mapper.oper.NticeMapper;
import com.oqpo.api.service.CommonService;
import com.oqpo.api.web.dto.request.GridRequest;
import com.oqpo.api.web.dto.request.oper.ntice.SaveNticeRequest;
import com.oqpo.api.web.dto.response.GridResponse;
import com.oqpo.api.web.dto.response.oper.ntice.NticeResponse;
import com.oqpo.api.web.dto.response.oper.ntice.NticeSearchResponse;
import com.oqpo.api.web.dto.response.oper.ntice.NticeTargetResponse;
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.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class NticeService extends CommonService {
    @Autowired
    private NticeMapper nticeMapper;

    @Autowired
    private FileMapper fileMapper;


    /*
      공지 검색 리스트 조회
     */

    public GridResponse selectNticeGridList( String afflShopId, String brandId, String authTpCd, String sAfflShopId, String sBrandId, String fromDt, String toDt, String sNticeTitl, GridRequest gridRequest) throws Exception {
        int gridPage = gridRequest.getGridPage();
        int gridSize = gridRequest.getGridSize();

        fromDt = fromDt == null ? null : fromDt.replace(".", "");
        toDt = toDt == null ? null : toDt.replace(".", "");

        int gridRecords = nticeMapper.selectNticeGridCnt(afflShopId, brandId, authTpCd, sAfflShopId, sBrandId, fromDt, toDt, sNticeTitl);
        int gridTotal = fnCalculateGridTotal(gridSize, gridRecords);
        List<NticeEntity> entities = nticeMapper.selectNticeGridList(afflShopId, brandId, authTpCd, sAfflShopId, sBrandId, fromDt, toDt, sNticeTitl, gridRequest);

        List<Object> gridRows = entities.stream()
                .map(m -> NticeSearchResponse.builder()
                        .viewCd("R")
                        .afflShopId(m.getAfflShopId()  == null ? "" : m.getAfflShopId() )
                        .afflShopNm(m.getAfflShopNm()  == null ? "" : m.getAfflShopNm() )
                        .brandId(m.getBrandId()  == null ? "" : m.getBrandId())
                        .brandNm(m.getBrandNm()  == null ? "" : m.getBrandNm())
                        .nticeNo(m.getNticeNo())
                        .nticeTitl(m.getNticeTitl() == null ? "" : m.getNticeTitl())
                        .targetCd(m.getTargetCd() == null ? "" : m.getTargetCd())
                        .targetNm(m.getTargetNm() == null ? "" : m.getTargetNm())
                        .nticeStatNm(m.getNticeStatNm())
                        .notiStDay(m.getNotiStDay())
                        .addDt(m.getAddDt())
                        .build())
                .collect(Collectors.toList());

        return GridResponse.toDTO(gridPage, gridTotal, gridRecords, gridRows);
    }

    /*
    공지 저장
     */
    @Transactional
    public void saveNtice(String userId, SaveNticeRequest saveNticeRequest) throws Exception {
        try {
            // 기본정보 저장
            NticeEntity entity = new NticeEntity();
            entity.setNticeTitl(saveNticeRequest.getNticeTitl());
            entity.setTargetCd(saveNticeRequest.getTargetCd());
            entity.setNticeDesc(saveNticeRequest.getNticeDesc());
            entity.setDelYn(saveNticeRequest.getDelYn());
            entity.setNotiStDay(saveNticeRequest.getNotiStDay().replace(".", ""));
            entity.setNotiEdDay(saveNticeRequest.getNotiEdDay().replace(".", ""));
            entity.setFileNo(saveNticeRequest.getFileNo());
            entity.setBrandId(saveNticeRequest.getBrandId());
            entity.setAfflShopId(saveNticeRequest.getAfflShopId());
            entity.setBrandChk(saveNticeRequest.getBrandChk());
            entity.setShopChk(saveNticeRequest.getShopChk());
            entity.setSupplyChk(saveNticeRequest.getSupplyChk());
            if ("C".equals(saveNticeRequest.getViewCd())) {
                // 신규 공지번호 생성
                entity.setNticeNo(fnGetKeyNo(6));
                nticeMapper.insertNticeInfo(userId, entity);
            } else if ("U".equals(saveNticeRequest.getViewCd())) {
                entity.setNticeNo(saveNticeRequest.getNticeNo());
                nticeMapper.updateNticeInfo(userId, entity);
            }

            //  공지타겟 저장
            // 신규건
            List<NticeTargetEntity> gridInsertData = saveNticeRequest.toNticeTargetEntities(saveNticeRequest.getGridInsertData());
            if (gridInsertData.size() > 0) {
                nticeMapper.insertNticeTarget(userId, entity.getNticeNo(), gridInsertData);
            }

            // 삭제건
            List<NticeTargetEntity> gridDeleteData = saveNticeRequest.toNticeTargetEntities(saveNticeRequest.getGridDeleteData());

            if (gridDeleteData.size() > 0) {
                nticeMapper.deleteNticeTarget(entity.getNticeNo(), gridDeleteData);
            }
        } catch (GlobalException e) {
            e.getStackTrace();
            throw new GlobalException(e.getSystemMessageCode());
        } catch (Exception e) {
            e.getStackTrace();
            throw new RuntimeException();
        }
    }

    /*
   공지 정보 가져오기  selectFileList
    */
    public NticeResponse selectNticeInfo(String nticeNo) throws Exception {
        NticeEntity nticeEntity = nticeMapper.selectNticeInfo(nticeNo) ;
        List<FileEntity> nFileList = null;

        if (!"".equals(nticeEntity.getFileNo())) {
            nFileList = fileMapper.selectFileList(nticeEntity.getFileNo()) ;
        } else {
            nFileList = new ArrayList<FileEntity>();
        }

        return NticeResponse.toDTO(nticeEntity, nFileList);
    }

    /*
    공지 타겟 대상리스트
     */

    public GridResponse selectNticeTargetGridList(String nticeNo, GridRequest gridRequest) throws Exception {
        int gridPage = gridRequest.getGridPage();
        int gridSize = gridRequest.getGridSize();
        int gridRecords = nticeMapper.selectNticeTargetGridCnt(nticeNo);
        int gridTotal = fnCalculateGridTotal(gridSize, gridRecords);
        List<NticeTargetEntity> entities = nticeMapper.selectNticeTargetGridList(nticeNo, gridRequest);
        List<Object> gridRows = entities.stream()
                .map(m -> NticeTargetResponse.builder()
                        .viewCd("R")
                        .nticeNo(m.getNticeNo())
                        .brandId(m.getBrandId())
                        .brandNm(m.getBrandNm())
                        .build())
                .collect(Collectors.toList());
        return GridResponse.toDTO(gridPage, gridTotal, gridRecords, gridRows);
    }


    /*
   공지 viewCnt
    */
    @Transactional
    public void saveViewCnt(String nticeNo) throws Exception {
        try {
            nticeMapper.updateNticeViewCnt(nticeNo);
        } catch (GlobalException e) {
            e.getStackTrace();
            throw new GlobalException(e.getSystemMessageCode());
        } catch (Exception e) {
            e.getStackTrace();
            throw new RuntimeException();
        }
    }


    /*
      코너 검색 리스트 조회
     */
    public List<NticeEntity> selectMNticeList(String userId) throws Exception {
        return nticeMapper.selectMNticeList(userId);
    }

}
