package com.house365.ws.interfaces.rest;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Strings;
import com.house365.beans.entity.BaseAttachment;
import com.house365.beans.entity.KefuEntity;
import com.house365.beans.entity.UserEntity;
import com.house365.beans.entity.UserProjectRecommendEntity;
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.interfaces.IUserDao;
import com.house365.ws.dao.mapper.KefuMapper;
import com.house365.ws.dao.mapper.ProjectRecommendMapper;
import com.house365.ws.service.interfaces.IAttachmentService;
import com.house365.ws.service.interfaces.ICustomerStatusLogService;
import com.house365.ws.service.interfaces.IUserService;
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.*;

/**
 * 获取楼盘推荐相关信息接口
 *
 * @author Created by Administrator on 2018/10/17.
 */
@Service("getRecommendByHouse")
public class GetRecommendByHouseImpl implements IGetRecommendByHouse {

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

    @Autowired
    private IUserDao userDao;

    @Autowired
    private ICustomerStatusLogService logService;

    @Autowired
    private IUserService userService;

    @Autowired
    private IAttachmentService attachmentService;

    @Autowired
    private KefuMapper kefumapper;
    @Autowired
    private ProjectRecommendMapper recommendMapper;

    @Override
    public Object exectue(Parameter parameter) throws ServiceRunException {
        House365RestResponse<Map<String, Object>> response = new House365RestResponse<>();
        try {
            //从淘房汇请求参数取出map
            Map<String, Object> map = parameter.getArgs();
            //取出map中的部分数据
            String city = getMapValueByKey("city", map, "");
            String projectId = getMapValueByKey("projectId", map, "");
            String channel = getMapValueByKey("channel", map, "1");
            //调用方来源 1pc端,2app端
            String source = getMapValueByKey("source", map, "0");

            String currentPage = getMapValueByKey("currentPage", map, "");
            String pageSize = getMapValueByKey("pageSize", map, "");

            Map<String, Object> map11 = new HashMap<>(10);
            map11.put("channel", channel);
            map11.put("projectId", projectId);
            map11.put("city", city);
            List<UserProjectRecommendEntity> list = recommendMapper.queryByConditions(map11);
            //过滤没有头像,全身照，400电话的的安家顾问
            if (CollectionUtils.isNotEmpty(list)) {
                Iterator<UserProjectRecommendEntity> iterator = list.iterator();
                while (iterator.hasNext()) {
                    UserProjectRecommendEntity recommendEntity = iterator.next();
                    String userId = recommendEntity.getUserId().toString();
                    UserEntity entity = (UserEntity) userDao.getById(recommendEntity.getUserId());
                    if (entity == null) {
                        iterator.remove();
                    } else {
                        List<BaseAttachment> imgList = attachmentService.queryByResourceIdAndResouceType(userId, "hgs_user_headImg");
                        List<BaseAttachment> fillImgList = attachmentService.queryByResourceIdAndResouceType(userId, "hgs_user_fullImg");
                        if (CollectionUtils.isEmpty(imgList) || CollectionUtils.isEmpty(fillImgList) || StringUtils.isBlank(entity.getHotlinephone())) {
                            iterator.remove();
                        }
                    }
                }
            }

            List<Map<String, Object>> mapList = new ArrayList<>();

            //获取城市客服accid
            KefuEntity kefuEntity = kefumapper.getKefuInfo(city);

            if (CollectionUtils.isNotEmpty(list)) {
                for (UserProjectRecommendEntity l : list) {
                    int userId = l.getUserId();
                    UserEntity entity = (UserEntity) userDao.getById(userId);
                    if (entity != null && entity.getEnabled()) {
                        String goodAt = entity.getGoodat();
                        int count = logService.getSeeCount(userId);
                        count += entity.getDefaultVisit();
                        String personHotline = "4008908365,," + entity.getHotlinephone();
                        Map<String, Object> map1 = new HashMap<>(10);
                        map1.put("seeCount", count);
                        map1.put("goodAt", goodAt);
                        map1.put("userId", userId);
                        map1.put("userName", l.getUserName());
                        map1.put("projectName", l.getProjectName());
                        map1.put("recommendReason", l.getRecommendReason());

                        if (kefuEntity != null && "1".equals(kefuEntity.getSetKefu())) {
                            map1.put("accId", kefuEntity.getKefuAccid());
                        } else {
                            map1.put("accId", entity.getAccId());
                        }

                        //400号码
                        map1.put("phone", entity.getHotlinephone());
                        map1.put("personHotline", personHotline);
                        map1.put("defaultVisit", entity.getDefaultVisit());
                        //云信id
                        map1.put("token", entity.getToken());
                        UserEntity imEntity = userService.getByCity(city);
                        if (imEntity != null) {
                            //im信息
                            map1.put("imShow", imEntity.getImshow());
                        }
                        List<BaseAttachment> headImg = attachmentService.queryByResourceIdAndResouceType(String.valueOf(userId), "hgs_user_headImg");

                        if (CollectionUtils.isNotEmpty(headImg)) {
                            //头像
                            map1.put("headImgUrl", headImg.get(0).getRemotePath());
                        } else {
                            map1.put("headImgUrl", "http://img33.house365.com/M00/1B/86/rBEBp1pu2JyAIp4jAAAGEjOUX2M365.jpg");
                        }

                        List<NameValuePair> param1 = new ArrayList<>();
                        param1.add(new BasicNameValuePair("serviceCode", "TaoFangHui"));
                        param1.add(new BasicNameValuePair("serviceName", "getHouseById"));
                        param1.add(new BasicNameValuePair("city", city));
                        param1.add(new BasicNameValuePair("channel", channel));
                        param1.add(new BasicNameValuePair("projectId", projectId));
                        String result1 = HttpClientUtil.doGet(MemoryPropertyPlaceholderConfigurer.getContextProperty("tangfanghui.server.url"), param1, null);
                        String newProjectId = "";
                        if (result1 != null) {
                            ObjectMapper objectMapper = new ObjectMapper();
                            Map<String, Map<String, Object>> resultMap = objectMapper.readValue(result1, Map.class);
                            Map<String, Object> map2 = (Map) resultMap.get("data").get("entity");
                            newProjectId = map2.get("projectId").toString();
                        }
                        if (org.apache.commons.lang.StringUtils.isNotBlank(newProjectId)) {
                            List<NameValuePair> param = new ArrayList<>();
                            param.add(new BasicNameValuePair("serviceCode", "TaoFangHui"));
                            param.add(new BasicNameValuePair("serviceName", "getBindById"));
                            param.add(new BasicNameValuePair("city", city));
                            String jobNumber = l.getUserId().toString();
                            param.add(new BasicNameValuePair("jobNumber", jobNumber));
                            param.add(new BasicNameValuePair("channel", channel));
                            param.add(new BasicNameValuePair("projectId", newProjectId));
                            String result = HttpClientUtil.doGet(MemoryPropertyPlaceholderConfigurer.getContextProperty("tangfanghui.server.url"), param, null);
                            if (result != null) {
                                ObjectMapper objectMapper = new ObjectMapper();
                                Map<String, Map<String, Object>> resultMap = objectMapper.readValue(result, Map.class);
                                Map<String, Object> map2 = (Map) resultMap.get("data").get("entity");
                                String webPhone;
                                String mobilePhone;
                                if (null != map2.get("webPhone")) {
                                    webPhone = map2.get("webPhone").toString();
                                } else {
                                    webPhone = "";
                                }
                                if (null != map2.get("mobilePhone")) {
                                    mobilePhone = map2.get("mobilePhone").toString();
                                } else {
                                    mobilePhone = "";
                                }

                                map1.put("webPhone", webPhone);
                                map1.put("mobilePhone", mobilePhone);
                            }
                        }
                        mapList.add(map1);
                    }
                }
            }

            House365RestObject<Map<String, Object>> restObject = new House365RestObject<>();
            List<Map<String, Object>> subList = new ArrayList<>();

            List<Map<String, Object>> mapList1 = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(mapList)) {
                Iterator<Map<String, Object>> iterator = mapList.iterator();
                while (iterator.hasNext()) {
                    Map<String, Object> iterMap = iterator.next();
                    if (null != iterMap.get("webPhone") && StringUtils.isNotBlank(iterMap.get("webPhone").toString())) {
                        mapList1.add(iterMap);
                        iterator.remove();
                    }
                }
            }
            mapList1.addAll(mapList);
            int total = mapList1.size();
            //手动分页，需要先查出全部然后筛选重新分页
            for (int i = 0; i <= total; i++) {
                // 开始索引
                int currentPage1 = Integer.parseInt(currentPage);
                int pageSize1 = Integer.parseInt(pageSize);
                int fromIndex = (currentPage1 - 1) * pageSize1;
                // 结束索引
                int toIndex = fromIndex + pageSize1;
                // 如果结束索引大于集合的最大索引，那么规定结束索引=集合大小
                if (toIndex > total) {
                    toIndex = total;
                }
                if (fromIndex <= total) {
                    subList = mapList1.subList(fromIndex, toIndex);
                    if (toIndex >= fromIndex) {
                        break;
                    }
                }
            }

            //app端删除没有绑定的人员
            if ("2".equals(source) && CollectionUtils.isNotEmpty(subList)) {
                Iterator<Map<String, Object>> iterator = subList.iterator();
                while (iterator.hasNext()) {
                    Map<String, Object> iterMap = iterator.next();
                    if (null == iterMap.get("mobilePhone") || (null != iterMap.get("mobilePhone") && StringUtils.isBlank(iterMap.get("mobilePhone").toString()))) {
                        iterator.remove();
                    }
                }
            }
            restObject.setList(subList);

            response.setData(restObject);
            response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());

        } catch (Exception e) {
            e.printStackTrace();
            logger.error("根据projectId获取直销人员楼盘推荐失败");
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg((ReturnAppResult.APP_FAIL.getResultMessage() + ":" + e.getMessage()));
        }
        return JSONObject.fromObject(response).toString();
    }

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

    }
}
