package com.house365.ws.interfaces.rest;

import com.google.common.base.Strings;
import com.house365.beans.entity.CmCreditRecordEntity;
import com.house365.beans.entity.CmRankingEntity;
import com.house365.beans.system.QueryParams;
import com.house365.rest.context.Parameter;
import com.house365.rest.exception.ServiceRunException;
import com.house365.web.util.MemoryPropertyPlaceholderConfigurer;
import com.house365.ws.dao.mapper.CmCreditRecordMapper;
import com.house365.ws.service.interfaces.ICmCreditRecordService;
import com.house365.ws.system.ReturnAppResult;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.Transaction;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component("getInviteRanking")
public class GetInviteRankingImpl implements IGetInviteRanking {

    private static final Logger LOGGER = LoggerFactory.getLogger("InterfaceLog");
    private static final String RESULT = "result";
    private static final String MSG = "msg";
    @Autowired
    private CmCreditRecordMapper cmcreditrecordmapper;

    @Override
    public Object rollback() {
        return null;
    }

    @Override
    public void commit() {
        LOGGER.debug("commit");
    }

    private String getMapValueByKey(String key, Map<String, Object> map, String defaultValue) {
        String value = "";
        if (map.containsKey(key) && map.get(key) != null && !Strings.isNullOrEmpty(((String[]) map.get(key))[0])) {
            value = ((String[]) map.get(key))[0];
        }

        if (Strings.isNullOrEmpty(value)) {
            value = defaultValue;
        }
        return value;
    }


    @Override
    public Object exectue(Parameter parameter) throws ServiceRunException {
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        Map<String, Object> resultMap = new HashMap<>(10);
        String startTime = getMapValueByKey("startTime", map, "");
        String endTime = getMapValueByKey("endTime", map, "");
        // 业务层统一处理
        try {
            if (startTime == null || "".equals(startTime)) {
                resultMap.put(RESULT, ReturnAppResult.APP_FAIL.getResultCode());
                resultMap.put(MSG, "开始时间不能为空!");
                return JSONObject.fromObject(resultMap).toString();
            }
            if (endTime == null || "".equals(endTime)) {
                resultMap.put(RESULT, ReturnAppResult.APP_FAIL.getResultCode());
                resultMap.put(MSG, "结束时间不能为空!");
                return JSONObject.fromObject(resultMap).toString();
            }
            if(!isRqSjFormat(startTime) || !isRqSjFormat(endTime) ){
                resultMap.put(RESULT, ReturnAppResult.APP_FAIL.getResultCode());
                resultMap.put(MSG, "时间格式非法:yyyy-MM-dd HH:mm:ss");
                return JSONObject.fromObject(resultMap).toString();
            }
            String host = MemoryPropertyPlaceholderConfigurer.getContextProperty("redis.host");

            if (!Strings.isNullOrEmpty(host)) {
                final String key = ":getInviteCodeRanking";
                JedisPoolConfig config = new JedisPoolConfig();
                config.setMaxTotal(50);
                config.setMaxIdle(5);
                config.setMinIdle(1);
                JedisPool pool = new JedisPool(config, host);
                try (Jedis jedis = pool.getResource()) {
                    String current = jedis.get(key);
                    if (!Strings.isNullOrEmpty(current) && com.house365.web.util.StringUtils.isNumeric(
                            current) && (Integer.parseInt(current)) >= 2) {
                        LOGGER.warn("请求过于频繁，请稍后再试! [{}]", key);
                        resultMap.put("result", ReturnAppResult.APP_FAIL.getResultCode());
                        resultMap.put("msg", "请求过于频繁，请稍后再试!!");
                        return JSONObject.fromObject(resultMap).toString();
                    } else {
                        Transaction t = jedis.multi();
                        t.incr(key);
                        t.expire(key, 1);
                        t.exec();
                    }
                } finally {
                    pool.close();
                }
            } else {
                LOGGER.warn("can not get redis host !");
            }

            Map<String, Object> searchMap = new HashMap<>(10);
            searchMap.put("startTime", startTime);
            searchMap.put("endTime", endTime);
            List<CmRankingEntity> rakingList = cmcreditrecordmapper.queryInviteRanking(searchMap);

            resultMap.put("result", ReturnAppResult.APP_SUCCESS.getResultCode());
            resultMap.put("msg", "操作成功!");
            resultMap.put("ranking", rakingList);

        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            resultMap.put("result", ReturnAppResult.APP_FAIL.getResultCode());
            resultMap.put("msg", "获取用户信息失败!");
        }

        return JSONObject.fromObject(resultMap).toString();

    }

    /**
     * v判断字符串是否是yyyy-MM-dd HH:mm:ss格式
     * @param mes
     * @return
     */
    public static boolean isRqSjFormat(String mes){
        String format = "([0-9]{4})-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])"
                + " ([01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9]";
        Pattern pattern = Pattern.compile(format);
        Matcher matcher = pattern.matcher(mes);
        if (matcher.matches()) {
            pattern = Pattern.compile("(\\d{4})-(\\d{2})-(\\d{2}).*");
            matcher = pattern.matcher(mes);
            if (matcher.matches()) {
                int y = Integer.valueOf(matcher.group(1));
                int m = Integer.valueOf(matcher.group(2));
                int d = Integer.valueOf(matcher.group(3));
                if (d > 28) {
                    Calendar c = Calendar.getInstance();
                    c.set(y, m-1, 1);
                    int lastDay = c.getActualMaximum(Calendar.DAY_OF_MONTH);
                    return (lastDay >= d);
                }
            }
            return true;
        }
        return false;

    }


    @Override
    public boolean isControlService() {
        return false;
    }

    @Override
    public boolean isLogService() {
        return false;
    }

    @Override
    public boolean isMonitorService() {
        return false;
    }

}
