package com.house365.ws.interfaces.rest;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Strings;
import com.house365.beans.entity.DepartmentEntity;
import com.house365.beans.entity.KefuEntity;
import com.house365.beans.entity.UserEntity;
import com.house365.beans.entity.UserMessageEntity;
import com.house365.commons.system.HttpClientUtil;
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.web.util.MemoryPropertyPlaceholderConfigurer;
import com.house365.ws.dao.mapper.DepartMapper;
import com.house365.ws.dao.mapper.KefuMapper;
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.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * IM 统一返回accId信息接口
 * IM规则调整之后统一封装的接口，区分南京站和其他站
 *
 * @author Created by 365 on 2021/1/8.
 */
@Service("getImUserInfo")
public class GetImUserInfoImpl implements IGetImUserInfo {

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

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserMessageMapper messageMapper;
    @Autowired
    private KefuMapper kefumapper;
    @Autowired
    private DepartMapper departMapper;

    @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 projectId = getMapValueByKey("houseId", map, "");
            String channel = getMapValueByKey("channel", map, "");
            String city = getMapValueByKey("city", map, "");
            String tfId = getMapValueByKey("tfId", map, "");
            if (StringUtils.isBlank(city)) {
                response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
                response.setMsg("城市参数不全");
                return JSONObject.fromObject(response).toString();
            }
            //南京站跟其他站不同的逻辑
            if ("nj".equals(city)) {
                if (StringUtils.isBlank(tfId)) {
                    response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
                    response.setMsg("接口参数不全");
                    return JSONObject.fromObject(response).toString();
                }

                //查询在线客服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 {
                        //有在线房博士，随机分配一个，没有则默认组长
                        accId = getAccId(userList);
                    }
                    putMap.put("accId", accId);
                    data.setEntity(putMap);
                } else {
                    //有在线房博士，随机分配一个，没有则默认组长
                    accId = getAccId(userList);
                    putMap.put("accId", accId);
                    data.setEntity(putMap);
                }
            } else {
                //非南京情况下，先判断是否直卖楼盘，非直卖楼盘；直卖楼盘调用淘房汇接口，有客服id取客服id,没有取accid，非直卖楼盘直接去新房房博士id
                if (StringUtils.isBlank(projectId) || StringUtils.isBlank(channel)) {
                    response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
                    response.setMsg("接口参数不全");
                    return JSONObject.fromObject(response).toString();
                }
                //查询各个城市的新房客服
                String accId = "";
                List<NameValuePair> param = new ArrayList<>();
                param.add(new BasicNameValuePair("serviceCode", "TaoFangHui"));
                param.add(new BasicNameValuePair("serviceName", "getBindInfo"));
                param.add(new BasicNameValuePair("city", city));
                param.add(new BasicNameValuePair("projectId", projectId));
                param.add(new BasicNameValuePair("channel", channel));
                String result = HttpClientUtil.doGet(MemoryPropertyPlaceholderConfigurer.getContextProperty("tangfanghui.server.url"), param, 4000, null);
                //根据条件查不到楼盘信息的情况下 即非直卖楼盘
                if ("".equals(result)) {
                    //非直卖楼盘，查询各个城市的新房客服
                    Map<String, Object> searchMap = new HashMap<>(10);
                    searchMap.put("descripition", city);
                    List<DepartmentEntity> deptList = departMapper.queryByConditions(searchMap);
                    if (CollectionUtils.isNotEmpty(deptList)) {
                        DepartmentEntity entity = deptList.get(0);
                        String urlPath = entity.getUrlPath();
                        searchMap.put("deptUrlPath", urlPath);
                        searchMap.put("identityType", 3);
                        List<UserEntity> userList = userMapper.queryByConditions(searchMap);
                        if (CollectionUtils.isNotEmpty(userList)) {
                            accId = userList.get(0).getAccId();
                        }
                    }
                } else {
                    //直卖楼盘去查询城市客服
                    if (result != null) {
                        KefuEntity kefuEntity = kefumapper.getKefuInfo(city);
                        if (null != kefuEntity && "1".equals(kefuEntity.getSetKefu())) {
                            accId = kefuEntity.getKefuAccid();
                        } else {
                            ObjectMapper objectMapper = new ObjectMapper();
                            Map<String, Map<String, Map>> webMap = objectMapper.readValue(result, Map.class);
                            List<Map<String, Object>> list = (List<Map<String, Object>>) webMap.get("data").get("entity").get("list");
                            if (CollectionUtils.isNotEmpty(list)) {
                                int pick = getRandom(list.size());
                                Map<String, Object> resultMap = list.get(pick);
                                int userId = Integer.parseInt(resultMap.get("userId").toString());
                                UserEntity userEntity = userMapper.getById(userId);
                                accId = userEntity.getAccId();
                            }
                        }
                    }
                }
                putMap.put("accId", accId);
                data.setEntity(putMap);
            }

            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg("查询IM信息成功");
            response.setData(data);

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg((ReturnAppResult.APP_FAIL.getResultMessage() + ":" + e.getMessage()));
        }
        return JSONObject.fromObject(response).toString();
    }

    private String getAccId(List<UserEntity> userList) {
        String accId;
        //南京站 accId qlt_527
        String defaultId = "qlt_527";
        //有在线房博士，随机分配一个，没有则默认组长
        if (CollectionUtils.isNotEmpty(userList)) {
            int pick = getRandom(userList.size());
            accId = userList.get(pick).getAccId();
        } else {
            //没有聊天 取默认值组长的的id
            accId = defaultId;
        }
        return accId;
    }

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

    /**
     * 获取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() {

    }
}
