package com.house365.ws.interfaces.rest;

import com.google.common.base.Strings;
import com.house365.beans.entity.CmCreditRecordEntity;
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.StringUtils;
import com.house365.ws.cached.RedisUtilsInterface;
import com.house365.ws.service.interfaces.ICmCreditRecordService;
import com.house365.ws.service.interfaces.ICmUserService;
import com.house365.ws.system.ReturnAppResult;
import com.house365.ws.util.JsonUtil;
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 java.util.Map;

/**
 * <p>Title: 房博士提问扣积分</p>
 * <p>Description: </p>
 * <p>Date: 2017/4/19</p>
 *
 * @author XN
 * @version 1.0
 */
@Component("questionMinusCredit")
public class QuestionMinusImpl implements IQuestionMinusCredit {
    private static final Logger LOGGER = LoggerFactory.getLogger("InterfaceLog");

    @Autowired
    private ICmCreditRecordService cmCreditRecordService;

    @Autowired
    ICmUserService<CmUserEntity> iCmUserService;

    @Autowired
    RedisUtilsInterface redisUtils;

    static final String lockKey = "questionMinus:lock";

    @Override
    public Object exectue(Parameter parameter) throws ServiceRunException {
        JSONObject mergedJSON = new JSONObject();
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        try {

            //一次只能处理一个请求
            while (true) {
                long time = System.currentTimeMillis() + 30;
                boolean isNotLock = redisUtils.setNotExists(lockKey, time + "");
                if (isNotLock || (redisUtils.getValByKeyNew(
                    lockKey) != null && System.currentTimeMillis() > Long.parseLong(
                    redisUtils.getValByKeyNew(lockKey)) && System.currentTimeMillis() > Long.parseLong(
                    redisUtils.getSet(lockKey, time + "")))) {
                    LOGGER.debug("===== Get LOCK ");
                    break;
                } else {
                    Thread.sleep(35);
                }
            }

            if (!map.containsKey(CmConstant.USERID) || map.get(CmConstant.USERID) == null) {
                mergedJSON.put("result", ReturnAppResult.APP_FAIL.getResultCode());
                mergedJSON.put("msg", "用户参数不存在!");
                return mergedJSON.toString();
            }

            if (!map.containsKey("credit") || map.get("credit") == null) {
                mergedJSON.put("result", ReturnAppResult.APP_FAIL.getResultCode());
                mergedJSON.put("msg", "积分参数不存在!");
                return mergedJSON.toString();
            }

            String credit = ((String[]) map.get("credit"))[0];
            if (Strings.isNullOrEmpty(credit) || !StringUtils.isNumeric(credit)) {
                mergedJSON.put("result", ReturnAppResult.APP_FAIL.getResultCode());
                mergedJSON.put("msg", "积分参数不合法!");
                return mergedJSON.toString();
            }

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

            if (cmUser.getCredits().compareTo(Integer.parseInt(credit)) < 0) {
                mergedJSON.put("result", ReturnAppResult.APP_FAIL.getResultCode());
                mergedJSON.put("msg", "用户积分不足!");
                return mergedJSON.toString();
            }

            CmCreditRecordEntity cmCreditRecordEntity = cmCreditRecordService.transQestionMinusCredit(cmUser,
                                                                                                      Integer.parseInt(
                                                                                                          credit));

            if (cmCreditRecordEntity != null) {
                mergedJSON.put("credit", cmCreditRecordEntity.getAmount());
                mergedJSON.put("totalCredit", cmCreditRecordEntity.getRemainingAmount());
            } else {
                mergedJSON.put("result", ReturnAppResult.APP_FAIL.getResultCode());
                mergedJSON.put("msg", ReturnAppResult.APP_FAIL.getResultMessage());
                return mergedJSON.toString();
            }

        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            mergedJSON.put("result", ReturnAppResult.APP_FAIL.getResultCode());
            mergedJSON.put("msg", ReturnAppResult.APP_FAIL.getResultMessage());
            return mergedJSON.toString();
        } finally {
            //移除订单提交标记
            LOGGER.debug("===== 移除LOCK标记!");
            redisUtils.deleteKey(lockKey);
        }
        JSONObject resultJSON = JsonUtil.getExecuteOKJson(mergedJSON);
        return resultJSON.toString();
    }


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

    @Override
    public void commit() {

    }


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

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

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