package com.house365.ws.interfaces.rest;

import com.google.common.base.Strings;
import com.house365.beans.entity.UserEntity;
import com.house365.beans.entity.UserMessageEntity;
import com.house365.rest.context.Parameter;
import com.house365.rest.exception.ServiceRunException;
import com.house365.rest.parameter.House365RestResponse;
import com.house365.ws.dao.mapper.UserMapper;
import com.house365.ws.dao.mapper.UserMessageMapper;
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;

/**
 * 用户上下线 im信息新增接口
 *
 * @author Created by 365 on 2020/12/30.
 */
@Service("saveNewMessage")
public class SaveNewMessage implements ISaveNewMessage {

    private static final Logger logger = LoggerFactory.getLogger(SaveNewMessage.class);
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserMessageMapper messageMapper;

    @Override
    public Object exectue(Parameter parameter) throws ServiceRunException {
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<UserMessageEntity> response = new House365RestResponse<>();
        try {
            String messageEntity = getMapValueByKey("data", map, "");
            if (!Strings.isNullOrEmpty(messageEntity)) {
                JSONObject message = JSONObject.fromObject(messageEntity);
                String sender = getJsonValueByKey("sender", message, "");
                String receiver = getJsonValueByKey("receiver", message, "");
                if (StringUtils.isBlank(sender) || StringUtils.isBlank(receiver)) {
                    response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
                    response.setMsg("接口参数不全");
                    return JSONObject.fromObject(response).toString();
                }
                //过滤不是IM咨询组的人信息
                if (receiver.startsWith("qlt_") && sender.startsWith("tf_")) {
                    Date now = new Date();
                    Map<String, Object> queryMap = new HashMap<>(5);
                    //测试临时新加部门，上线需要调整
                    queryMap.put("deptUrlPath", "/1/2/69/70/567/568");
                    queryMap.put("accId", receiver);
                    List<UserEntity> userList = userMapper.queryByConditions(queryMap);
                    if (CollectionUtils.isNotEmpty(userList)) {
                        Map<String, Object> searchMap = new HashMap<>(5);
                        searchMap.put("sender", sender);
                        searchMap.put("receiver", receiver);
                        List<UserMessageEntity> list = messageMapper.queryByConditions(searchMap);
                        //判断如果存在聊天，则更新时间，不存在则新增一条记录
                        if (CollectionUtils.isNotEmpty(list)) {
                            UserMessageEntity oldEntity = list.get(0);
                            oldEntity.setUpdateTime(now);
                            messageMapper.update(oldEntity);
                        } else {
                            UserMessageEntity entity = new UserMessageEntity();
                            entity.setSender(sender);
                            entity.setReceiver(receiver);
                            entity.setCreateTime(now);
                            entity.setUpdateTime(now);
                            messageMapper.save(entity);
                        }
                        response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
                        response.setMsg("同步message成功");
                    }
                }
            } else {
                response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
                response.setMsg("data参数不能为空");
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("同步IM信息失败", e);
            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() {

    }
}
