package com.house365.ws.interfaces.rest;

import com.google.common.base.Strings;
import com.house365.beans.entity.CmUserEntity;
import com.house365.beans.system.QueryParams;
import com.house365.rest.context.Parameter;
import com.house365.rest.exception.ServiceRunException;
import com.house365.rest.parameter.House365RestResponse;
import com.house365.web.util.SpringContextUtil;
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.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 同步用户状态，看用户是否注销，注销才会推送
 *
 * @author Created by Administrator on 2019/4/23.
 */
@Component("updateUserStatus")
public class UpdateUserImpl implements IUpdateUser {

    private static final Logger logger = LoggerFactory.getLogger(UpdateUserImpl.class);

    @Autowired
    private ICmUserService<CmUserEntity> iCmUserService;

    @Override
    public Object exectue(Parameter parameter) throws ServiceRunException {
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<CmUserEntity> response = new House365RestResponse<>();
        try {
            String data = getMapValueByKey("data", map, "");
            if (!Strings.isNullOrEmpty(data)) {
                JSONObject message = JSONObject.fromObject(data);
                String id = getJsonValueByKey("userId", message, "");
                String status = getJsonValueByKey("status", message, "");
                int userId;
                int isDeleted;
                if (StringUtils.isNotBlank(status)) {
                    userId = Integer.parseInt(id);
                } else {
                    response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
                    response.setMsg("userId参数不能为空");
                    return JSONObject.fromObject(response).toString();
                }
                if (StringUtils.isBlank(status)) {
                    response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
                    response.setMsg("status参数不能为空");
                    return JSONObject.fromObject(response).toString();
                } else {
                    if(!"2".equals(status)){
                        response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
                        response.setMsg("status参数值不正确");
                        return JSONObject.fromObject(response).toString();
                    }
                    isDeleted = Integer.parseInt(status);
                }
                Map<String, Object> param = new HashMap<>(10);
                param.put("EQ_userId", userId);
                QueryParams<CmUserEntity> queryParamUser = new QueryParams<>();
                queryParamUser.setSearchParams(param);
                List<CmUserEntity> list = iCmUserService.queryAll(queryParamUser);
                if(CollectionUtils.isNotEmpty(list)){
                    CmUserEntity entity = list.get(0);
                    entity.setIsDeleted(isDeleted);
                    entity.setUpdateTime(new Date());
                    iCmUserService.update(entity);
                    //更新完用户清除缓存
                    RedisUtilsInterface redisUtils = (RedisUtilsInterface) SpringContextUtil.getBean("redisUtils");
                    String cacheKey = "USERINFO:" + id;
                    redisUtils.deleteByKeyNew(cacheKey);
                } else {
                    response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
                    response.setMsg("根据id查询用户为空");
                    return JSONObject.fromObject(response).toString();
                }
                response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
                response.setMsg("同步用户状态成功");
            } else {
                response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
                response.setMsg("data参数不能为空");
            }

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("同步用户状态失败");
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg((ReturnAppResult.APP_FAIL.getResultMessage() + ":" + e.getMessage()));
        }
        return JSONObject.fromObject(response).toString();
    }

    private String getJsonValueByKey(String key, JSONObject obj, String defaultValue) {
        String value = "";
        if (obj.containsKey(key) && obj.get(key) != null && !Strings.isNullOrEmpty(String.valueOf(obj.get(key)))) {
            value = String.valueOf(obj.get(key));
        }

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

    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 boolean isControlService() {
        return false;
    }

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

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

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

    @Override
    public void commit() {

    }
}
