package com.handong.smartservice.service;

import com.handong.smartservice._AG;
import com.handong.smartservice.component.CtResponse;
import com.handong.smartservice.component.ErrorCode;
import com.handong.smartservice.mapper.NoticeMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
public class NoticeService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private final NoticeMapper noticeMapper;


    public NoticeService(NoticeMapper noticeMapper) {
        this.noticeMapper = noticeMapper;
    }

    public CtResponse getNoticeDetail(String notice_id) {
        CtResponse result = new CtResponse();

        Map<String, Object> detail = noticeMapper.selectDetailNotice(notice_id);

        if (notice_id == null || notice_id.isEmpty()) {
            result.setErrCode(ErrorCode.INVALID_PARAMETER);
            return result;
        }

        result.put("result", detail);
        return result;
    }

    public Map<String, Object> getNoticeList(Long offset, Long limit, String date_start, String date_end,
                String title, String content) {
        Map<String, Object> mapResult = new HashMap<>();

        List<Map<String, Object>> listMap = (List<Map<String, Object>>)noticeMapper.selectNotice(false, offset, limit,
            date_start, date_end, title, content);
        mapResult.put("list", listMap);
        
        //Long totalCount = _AG.getTotalCount(noticeMapper.selectNotice(true, offset, limit,
        //    date_start, date_end, title, content));
        Long totalCount = _AG.getNumberFromQuery("COUNT(*)", noticeMapper.selectNotice(true, offset, limit,
            date_start, date_end, title, content));
        mapResult.put("totalCount", totalCount);
        mapResult.put("offset", offset);
        return mapResult;
    }

    public CtResponse addOrModifyNotice(boolean isModify, String notice_id, String title, String content) {
        CtResponse result = new CtResponse();

        if (isModify) {
            if (notice_id == null || notice_id.isEmpty()) {
                result.setErrCode(ErrorCode.INVALID_PARAMETER);
                return result;
            }

            noticeMapper.updateNotice(_AG.toLong(notice_id), title, content);
        }
        else {
            noticeMapper.insertNotice(title, content, 2L);
        }

        return result;
    }

    public CtResponse removeNotice(String ids) {
        CtResponse result = new CtResponse();

        List<Long> arrId = Arrays.stream(ids.split(","))
            .map(Long::parseLong)
            .collect(Collectors.toList());

        int changed = noticeMapper.changeStateNotice(arrId, 2);
        //if (changed == 0) {
            //result.setErrCode(ErrorCode.QUERY_ERROR);
        //}

        return result;
    }
}
