package com.house365.ws.interfaces.rest;

import com.google.common.base.Strings;
import com.house365.beans.entity.CmCreditRecordEntity;
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.web.util.StringUtils;
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.HashMap;
import java.util.Map;

/**
 * <p>Title: </p>
 * <p>Description: </p>
 * <p>Date: 2017/6/12</p>
 *
 * @author XN
 * @version 1.0
 */
@Component("getInviteCount")
public class GetUserInviterCountByDateRangeImpl implements IGetUserInviterCountByDateRange {

    private static final Logger GuetUserInviterLOGGER = LoggerFactory.getLogger("InterfaceLog");
    private static final String RESULT = "result";
    private static final String MSG = "msg";


    @Autowired
    private ICmCreditRecordService<CmCreditRecordEntity> iCmCreditRecord;

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

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

    @Override
    public Object exectue(Parameter parameter) throws ServiceRunException {
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        Map<String, Object> resultMap = new HashMap<>(10);
        // 业务层统一处理
        try {
            if (!map.containsKey("phone") || map.get("phone") == null) {
                resultMap.put(RESULT, ReturnAppResult.APP_FAIL.getResultCode());
                resultMap.put(MSG, "用户不存在!");
                return JSONObject.fromObject(resultMap).toString();
            }

            String phone = ((String[]) map.get("phone"))[0];
            if (Strings.isNullOrEmpty(phone) || !StringUtils.isNumeric(phone)) {
                resultMap.put(RESULT, ReturnAppResult.APP_FAIL.getResultCode());
                resultMap.put(MSG, "手机格式不正确!");
                return JSONObject.fromObject(resultMap).toString();
            }

            if (!map.containsKey("startTime") || map.get("startTime") == null) {
                resultMap.put(RESULT, ReturnAppResult.APP_FAIL.getResultCode());
                resultMap.put(MSG, "开始时间不能为空!");
                return JSONObject.fromObject(resultMap).toString();
            }

            String startTime = ((String[]) map.get("startTime"))[0];
            if (Strings.isNullOrEmpty(startTime) || !StringUtils.isNumeric(startTime)) {
                resultMap.put(RESULT, ReturnAppResult.APP_FAIL.getResultCode());
                resultMap.put(MSG, "开始时间必须是数字!");
                return JSONObject.fromObject(resultMap).toString();
            }

            if (!map.containsKey("endTime") || map.get("endTime") == null) {
                resultMap.put(RESULT, ReturnAppResult.APP_FAIL.getResultCode());
                resultMap.put(MSG, "截止时间不能为空!");
                return JSONObject.fromObject(resultMap).toString();
            }

            String endTime = ((String[]) map.get("endTime"))[0];
            if (Strings.isNullOrEmpty(endTime) || !StringUtils.isNumeric(endTime)) {
                resultMap.put(RESULT, ReturnAppResult.APP_FAIL.getResultCode());
                resultMap.put(MSG, "截止时间必须是数字!");
                return JSONObject.fromObject(resultMap).toString();
            }

            String host = MemoryPropertyPlaceholderConfigurer.getContextProperty("redis.host");

            if (!Strings.isNullOrEmpty(host)) {
                final String key = phone + ":getUserCreditsInfo";
                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) {
                        GuetUserInviterLOGGER.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 {
                GuetUserInviterLOGGER.warn("can not get redis host !");
            }

            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String star = format.format(Long.parseLong(startTime));
            String end = format.format(Long.parseLong(endTime));


            Map<String, Object> searchMap = new HashMap<>(10);
            searchMap.put("EQ_userPhone", phone);
            searchMap.put("EQ_ruleId", "8");
            searchMap.put("GTE_happenTime", star);
            searchMap.put("LTE_andHappenTime", end);
            QueryParams queryParams = new QueryParams();
            queryParams.setSearchParams(searchMap);
            Integer count = iCmCreditRecord.getUserInviteCount(queryParams);

            resultMap.put("result", ReturnAppResult.APP_SUCCESS.getResultCode());
            resultMap.put("count", count);
            resultMap.put("phone", phone);
            resultMap.put("startTime", startTime);
            resultMap.put("endTime", endTime);
            resultMap.put("msg", "操作成功!");

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

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

    }

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

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

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