package com.house365.ws.interfaces.rest;

import com.google.common.base.Strings;
import com.house365.beans.entity.OnlineLogEntity;
import com.house365.beans.entity.UserEntity;
import com.house365.rest.context.Parameter;
import com.house365.rest.exception.ServiceRunException;
import com.house365.rest.parameter.House365RestObject;
import com.house365.rest.parameter.House365RestResponse;
import com.house365.ws.cached.RedisUtilsInterface;
import com.house365.ws.dao.mapper.OnlineLogMapper;
import com.house365.ws.dao.mapper.UserMapper;
import com.house365.ws.system.ReturnAppResult;
import net.sf.json.JSONObject;
import org.apache.commons.collections4.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.Service;

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

/**
 * 更新用户上线下线接口
 *
 * @author Created by 365 on 2020/12/30.
 */
@Service("updateUserStatus")
public class UpdateUserStatusImpl implements IUpdateUserStatus {

    private Logger logger = LoggerFactory.getLogger(UpdateUserStatusImpl.class);
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OnlineLogMapper logMapper;
    @Autowired
    private RedisUtilsInterface redisUtil;

    @Override
    public Object exectue(Parameter parameter) throws ServiceRunException {
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<UserEntity> response = new House365RestResponse<>();
        // 业务层统一处理
        try {
            House365RestObject<UserEntity> data = new House365RestObject<>();
            String phone = getMapValueByKey("phone", map, "");
            String status = getMapValueByKey("status", map, "");
            if (StringUtils.isBlank(phone) || StringUtils.isBlank(status)) {
                response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
                response.setMsg("接口参数不全");
                return JSONObject.fromObject(response).toString();
            }
            String key = "update_online_job_" + phone;
            String value = "onlineValue";
            long seconds = 10;
            if (redisUtil.setNX(key, value, seconds)) {
                Map<String, Object> searchMap = new HashMap<>(5);
                searchMap.put("telephone", phone);
                List<UserEntity> list = userMapper.queryByConditions(searchMap);
                if (CollectionUtils.isNotEmpty(list)) {
                    UserEntity user = list.get(0);
                    int oldStatus = user.getOnlineStatus();
                    Integer newStatus = Integer.parseInt(status);
                    if (oldStatus != newStatus) {
                        Map<String, Object> updateMap = new HashMap<>(5);
                        updateMap.put("mobile", phone);
                        updateMap.put("onlineStatus", status);
                        userMapper.updateUserStatus(updateMap);
                        OnlineLogEntity logEntity = new OnlineLogEntity();
                        logEntity.setOldStatus(oldStatus);
                        logEntity.setNewStatus(newStatus);
                        logEntity.setUserId(user.getId());
                        logEntity.setCreateTime(new Date());
                        logMapper.save(logEntity);
                        response.setData(data);
                        response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
                        response.setMsg("更新成功");
                    }
                } else {
                    response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
                    response.setMsg("更新失败，用户不存在");
                }
            }else {
                response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
                response.setMsg("更新太频繁，请稍后再尝试");
            }
        } catch (Exception e) {
            logger.error("更新用户上下线状态失败", e);
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg((ReturnAppResult.APP_FAIL.getResultMessage() + ":" + e.getMessage()));
        }
        String result = JSONObject.fromObject(response).toString();
        return result;
    }

    /**
     * 获取map中的值
     *
     * @param key          key
     * @param map          map
     * @param 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() {

    }
}
