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.po.UserPo;
import com.house365.commons.system.HttpClientUtil;
import com.house365.rest.context.Parameter;
import com.house365.rest.exception.IllegalServiceParameterException;
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.KefuMapper;
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.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.*;

/**
 * <p>Title: 绑定客户与客户经理</p>
 * <p>Description: </p>
 * <p>Date: 16/9/15</p>
 *
 * @author XN
 * @version 1.0
 */
@Service("getUserInfoByHouse")
public class GetUserInfoByHouseImpl implements IGetUserInfoByHouse {

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

    @Autowired
    private IUserService userService;

    @Autowired
    private ICustomerStatusLogService customerStatusLogService;

    @Autowired
    private IAttachmentService attachmentService;

    @Autowired
    private KefuMapper kefumapper;


    @Override
    public Object rollback() {
        return null;
    }

    @Override
    public void commit() {

    }

    @Override
    public Object exectue(Parameter parameter) throws ServiceRunException {
        // 取得所需参数
        Map<String, Object> map = parameter.getArgs();
        House365RestResponse<UserPo> response = new House365RestResponse<>();
        // 业务层统一处理
        try {
            House365RestObject<UserPo> data = doBusiness(map);
            if (data == null) {
                data = new House365RestObject<>();
                List<UserPo> list = Collections.emptyList();
                data.setList(list);
                response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
                response.setMsg("根据newHouseId,channel以及city查询不到楼盘信息");
                response.setData(data);
            } else {
                response.setData(data);
                if (CollectionUtils.isEmpty(data.getList())) {
                    response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
                    response.setMsg("该楼盘目前没有绑定人员");
                } else {
                    response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
                }
            }

        } 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 House365RestObject<UserPo> doBusiness(Map<String, Object> map) throws Exception {
        // 返回Json对象
        House365RestObject<UserPo> restObject = new House365RestObject<>();
        String projectId = getMapValueByKey("houseId", map, "");
        String channel = getMapValueByKey("channel", map, "");
        String city = getMapValueByKey("city", map, "");

        //调用淘房汇绑定直销人员list
        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 (result != null) {
            //根据条件查不到楼盘信息的情况下
            if ("".equals(result)) {
                return null;
            }
            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");
            List<UserPo> userPoList = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(list)) {
                for (Map<String, Object> l : list) {

                    UserPo user = new UserPo();
                    int userId = Integer.parseInt(l.get("userId").toString());
                    String mobilePhone = l.get("mobilePhone").toString();
                    String webPhone = l.get("webPhone").toString();
                    UserEntity userEntity = (UserEntity) userService.getById(userId);
                    //获取城市客服accid
                    KefuEntity kefuEntity = kefumapper.getKefuInfo(city);
                    if (kefuEntity != null) {
                        user.setKefuAccid(kefuEntity.getKefuAccid());
                        user.setSetKefu(kefuEntity.getSetKefu());
                    } else {
                        user.setKefuAccid("");
                        user.setSetKefu("");
                    }

                    //如果置业顾问被冻结，则不返回
                    if (userEntity != null && userEntity.getEnabled()) {
                        user.setId(userId);
                        user.setSellingId(Integer.valueOf(projectId));
                        user.setAccId(userEntity.getAccId());
                        //查询该城市是否展示IM窗口
                        UserEntity imentity = userService.getByCity(city);
                        if (imentity != null) {
                            user.setImshow(imentity.getImshow());
                        }

                        user.setRealName(userEntity.getRealName());
                        List<BaseAttachment> headImg = attachmentService.queryByResourceIdAndResouceType(String.valueOf(userId), "hgs_user_headImg");
                        List<BaseAttachment> fullImg = attachmentService.queryByResourceIdAndResouceType(String.valueOf(userId), "hgs_user_fullImg");

                        if (CollectionUtils.isNotEmpty(headImg)) {
                            user.setHeadImgURL(headImg.get(0).getRemotePath());
                        } else {
                            user.setHeadImgURL("http://img33.house365.com/M00/1B/86/rBEBp1pu2JyAIp4jAAAGEjOUX2M365.jpg");
                        }
                        if (CollectionUtils.isNotEmpty(fullImg)) {
                            user.setFullImgURL(fullImg.get(0).getRemotePath());
                        } else {
                            user.setFullImgURL("http://img31.house365.com/M00/52/5E/rBEBYFpu2HGAb7o1AAAJ0juvDio725.jpg");
                        }

                        user.setGoodat(userEntity.getGoodat());
                        user.setDescription(userEntity.getDescription());
                        user.setScore(String.format("%.1f", userEntity.getScore()));
                        user.setEvaluateCount(userEntity.getEvaluateCount());
                        user.setDefaultVisit(userEntity.getDefaultVisit());
                        user.setBuildingId(Integer.valueOf(projectId));

                        //获取带看次数
                        int seeCount = customerStatusLogService.getSeeCount(userId);
                        seeCount += userEntity.getDefaultVisit();
                        user.setSeeCount(seeCount);
                        //个人400电话
                        user.setPersonHotline("4008908365,," + userEntity.getHotlinephone());

                        //400大号绑定更新后重新赋值
                        user.setHotlinephone(mobilePhone);
                        user.setCornet(mobilePhone);
                        user.setWebPhone(webPhone);
                        user.setMobilePhone(mobilePhone);
                        userPoList.add(user);
                    }
                }
            }
            restObject.setList(userPoList);
            if (CollectionUtils.isNotEmpty(userPoList)) {
                Calendar c = Calendar.getInstance();
                int hour = c.get(Calendar.HOUR_OF_DAY);
                if (userPoList.size() == 1) {
                    restObject.setEntity(userPoList.get(0));
                } else if (userPoList.size() == 2) {
                    if (hour % 2 == 0) {
                        restObject.setEntity(userPoList.get(0));
                    } else {
                        restObject.setEntity(userPoList.get(1));
                    }
                } else {
                    if (hour % 3 == 0) {
                        restObject.setEntity(userPoList.get(0));
                    } else if (hour % 3 == 1) {
                        restObject.setEntity(userPoList.get(1));
                    } else {
                        restObject.setEntity(userPoList.get(2));
                    }
                }
            }

        }
        return restObject;
    }

    /**
     * 获取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;
    }

    /**
     * 业务层统校验自己所需参数是否存在
     * 所有参数都要存在
     *
     * @author hqc
     */
    protected void checkInterfaceParameter(
            Map<String, Object> map, String[] checkParams
    ) throws IllegalServiceParameterException {
        // 方法所需参数
        for (String str : checkParams) {
            // 如果不存在跳出 同时抛出相应异常
            if (!map.containsKey(str)) {
                throw new IllegalServiceParameterException("业务入口参数异常：" + str + "参数为空!");
            }
        }
    }

    @Override
    public boolean isControlService() {
        return false;
    }

    @Override
    public boolean isLogService() {
        return false;
    }

    @Override
    public boolean isMonitorService() {
        return false;
    }
}
