package com.nokia.sms.service;

import com.nokia.sms.vo.QueryResp;
import com.nokia.sms.vo.RequestParams;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.Map;

@Service
public class QueryService {
    private final JdbcTemplate jdbcTemplate;

    public QueryService(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public QueryResp query(RequestParams params) {
        Map<String, Object> map = getBlackListInfo(params.getPhone());
        QueryResp r = new QueryResp();
        r.setQuerySuccess(false);
        if (CollectionUtils.isEmpty(map)) {
            r.setQueryMessage("无加黑记录");
            return r;
        }

        if (map.get("operation_type").equals(2)) {
            r.setQueryMessage("曾在黑名单，已解黑");
            return r;
        }

        QueryResp.QueryResultDTO dto = new QueryResp.QueryResultDTO();
        dto.setReason(map.get("reason").toString());
        dto.setStartTime((String) map.get("start_time"));
        dto.setEndTime((String) map.get("end_time"));
        dto.setDescribe((String) map.get("hit_desc"));
        dto.setAllowToDel(map.get("suggestion").equals(1));
        r.setQuerySuccess(true);
        r.setQueryMessage("当前在黑名单");
        r.setQueryResult(dto);
        return r;
    }

    /**
     * 得到黑名单信息
     *
     * @param phone 电话
     * @return {@link Map}<{@link String}, {@link Object}>
     */
    public Map<String, Object> getBlackListInfo(String phone) {
        String sql = "select * from sms_blk.blacklist where phone = ?";
        try {
            return jdbcTemplate.queryForMap(sql, phone);
        } catch (EmptyResultDataAccessException e) {
            return Collections.emptyMap();
        }
    }
}
