package com.house365.ws.interfaces.rest;

import com.google.common.base.Strings;
import com.house365.beans.entity.CmCreditRuleEntity;
import com.house365.beans.entity.CmOrderEntity;
import com.house365.beans.entity.CmUserEntity;
import com.house365.rest.context.CmConstant;
import com.house365.rest.context.Parameter;
import com.house365.rest.exception.ServiceRunException;
import com.house365.web.util.DateTimeUtils;
import com.house365.web.util.MemoryPropertyPlaceholderConfigurer;
import com.house365.ws.service.interfaces.ICmCreditRuleService;
import com.house365.ws.service.interfaces.ICmOrderService;
import com.house365.ws.service.interfaces.ICmUserService;
import com.house365.ws.system.ReturnAppResult;
import com.house365.ws.util.CmCommonUtils;
import com.house365.ws.util.DateUtils;
import com.house365.ws.util.InviteCodeUtil;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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.Date;
import java.util.HashMap;
import java.util.Map;

@Component("getUserCredits")
public class GetUserCreditsImpl implements IGetUserCredits {

    private static final Logger UserCreditLogger = LoggerFactory.getLogger("InterfaceLog");

    @Autowired
    ICmUserService<CmUserEntity> iCmUserService;

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

            String host = MemoryPropertyPlaceholderConfigurer.getContextProperty("redis.host");
            String userIdStr = ((String[]) map.get(CmConstant.USERID))[0];

            if (!Strings.isNullOrEmpty(host)) {
                final String key = userIdStr + ":getUserCredits";
                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)) >= 5) {
                        UserCreditLogger.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, 2);
                        t.exec();
                    }
                } finally {
                    pool.close();
                }
            } else {
                UserCreditLogger.warn("can not get redis host !");
            }

            CmUserEntity cmUser = iCmUserService.registUserByUserId(map);
            if (cmUser == null) {
                resultMap.put("result", ReturnAppResult.APP_FAIL.getResultCode());
                resultMap.put("msg", "用户中心用户不存在!");
                return JSONObject.fromObject(resultMap).toString();
            }

            Map<String, String> info = new HashMap<>();
            info.put("userId", null == cmUser.getUserId() ? userIdStr : cmUser.getUserId());
            info.put("credits", String.valueOf(null == cmUser.getCredits() ? "0" : cmUser.getCredits()));
            info.put("phone", Strings.isNullOrEmpty(cmUser.getPhoneNumber()) ? "" : cmUser.getPhoneNumber());

            resultMap.put("data", info);
            resultMap.put("result", ReturnAppResult.APP_SUCCESS.getResultCode());
            resultMap.put("msg", "");

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

    @Override
    public boolean isControlService() {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public boolean isLogService() {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public boolean isMonitorService() {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public Object rollback() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void commit() {
        // TODO Auto-generated method stub

    }

}
