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.House365RestObject;
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.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * im直销组 上线人员信息表
 *
 * @author Created by 365 on 2020/12/30.
 */
@Service("getNewUserInfo")
public class GetNewUserInfoImpl implements IGetNewUserInfo {

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

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserMessageMapper messageMapper;

    /**
     * 对于纯新咨询的客户，随机分配给一位在线IM房博士； 
     * 对于非全新咨询的客户，每次咨询时需判断下上次咨询的人员账号是否在线，如在线直接分配上回的人员，如不在线，随机分配给其他在线人员；
     * 若所有组员都不在线时，默认分配给组长，保证有人接待客户；
     * 组长使用原新房房博士的账号，accid是qlt_527
     *
     * @param parameter 服务输入，不包含服务配置和控制信息
     * @return
     * @throws ServiceRunException
     */
    @Override
    public Object exectue(Parameter parameter) throws ServiceRunException {
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<Map<String, Object>> response = new House365RestResponse<>();
        // 业务层统一处理
        try {
            House365RestObject<Map<String, Object>> data = new House365RestObject<>();
            Map<String, Object> putMap = new HashMap<>(5);
            String tfId = getMapValueByKey("tfId", map, "");
            String city = getMapValueByKey("city", map, "");
            if (StringUtils.isBlank(tfId) || StringUtils.isBlank(city)) {
                response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
                response.setMsg("接口参数不全");
                return JSONObject.fromObject(response).toString();
            }
            if (!"nj".equals(city) || !tfId.startsWith("tf_")) {
                response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
                response.setMsg("参数不正确");
                return JSONObject.fromObject(response).toString();
            }
            String defaultId = "qlt_527";
            //查询在线客服list
            Map<String, Object> queryMap = new HashMap<>(5);
            //测试临时新加部门，上线需要调整
            queryMap.put("deptUrlPath", "/1/2/69/70/567/568");
            queryMap.put("onlineStatus", 1);
            List<UserEntity> userList = userMapper.queryByConditions(queryMap);

            Map<String, Object> searchMap = new HashMap<>(5);
            searchMap.put("sender", tfId);
            searchMap.put("order", 1);
            List<UserMessageEntity> messList = messageMapper.queryByConditions(searchMap);
            String accId;
            //判断该淘房用户是否聊过天
            if (CollectionUtils.isNotEmpty(messList)) {
                UserMessageEntity messageEntity = messList.get(0);
                queryMap.put("accId", messageEntity.getReceiver());
                List<UserEntity> userListNew = userMapper.queryByConditions(queryMap);
                if (CollectionUtils.isNotEmpty(userListNew)) {
                    accId = messageEntity.getReceiver();
                } else {
                    //如不在线，随机分配给其他在线人员
                    //有在线房博士，随机分配一个，没有则默认组长
                    if (CollectionUtils.isNotEmpty(userList)) {
                        int pick = getRandom(userList.size());
                        accId = userList.get(pick).getAccId();
                    } else {
                        //没有聊天 取默认值组长的的id
                        accId = defaultId;
                    }
                }
                putMap.put("accId", accId);
                data.setEntity(putMap);
            } else {
                //有在线房博士，随机分配一个，没有则默认组长
                if (CollectionUtils.isNotEmpty(userList)) {
                    int pick = getRandom(userList.size());
                    accId = userList.get(pick).getAccId();
                } else {
                    //没有聊天 取默认值组长的的id
                    accId = defaultId;
                }
                putMap.put("accId", accId);
                data.setEntity(putMap);
            }
            response.setData(data);
            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
            response.setMsg("查询成功");
        } catch (Exception e) {
            e.printStackTrace();
            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;
    }

    /**
     * 获取随机数
     *
     * @param bound 范围 0 - bound-1
     * @return
     */
    private int getRandom(int bound) {
        Random random = new Random();
        return random.nextInt(bound);
    }

    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() {

    }
}
