package com.house365.ws.interfaces.rest;

import com.google.common.base.Strings;
import com.house365.beans.entity.CmUserEntity;
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.cached.RedisUtilsInterface;
import com.house365.ws.service.interfaces.ICmUserService;
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.util.HashMap;
import java.util.Map;

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

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

    @Autowired
    ICmUserService<CmUserEntity> iCmUserService;
    @Autowired
    private RedisUtilsInterface redisUtils;

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

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

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

            String userId = ((String[]) map.get("userId"))[0];
//            if (Strings.isNullOrEmpty(phone) || !StringUtils.isNumeric(phone)) {
//                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 = userId + ":getUserUnreadReply";
                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) && StringUtils.isNumeric(current) && (Integer.parseInt(
                        current)) >= 5) {
                        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 !");
            }

            String key = "getUnreadReply:" + userId;
            if (redisUtils.hasKey(key)) {
                return redisUtils.getValByKey(key);
            }

            CmUserEntity userEntity = iCmUserService.getUserEntity(userId);
            JSONObject data = new JSONObject();
            Integer unread;
            if (userEntity == null || userEntity.getUnreadReply() == null) {
                unread = 0;
            } else {
                unread = userEntity.getUnreadReply();
            }

            data.put("unreadReplyCount", unread);
            resultMap.put("result", ReturnAppResult.APP_SUCCESS.getResultCode());
            resultMap.put("data", data);
            resultMap.put("msg", "操作成功!");

            result = JSONObject.fromObject(resultMap).toString();
            redisUtils.addKeyValExpire(key, result, 60);

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

        return result;

    }

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

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

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