package com.house365.ws.interfaces.rest;

import com.google.common.base.Strings;
import com.house365.beans.entity.BaseAttachment;
import com.house365.beans.entity.DepartmentEntity;
import com.house365.beans.entity.ProjectSalerEntity;
import com.house365.beans.entity.UserEntity;
import com.house365.beans.po.UserPo;
import com.house365.beans.system.Page;
import com.house365.beans.system.QueryParams;
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.StringUtils;
import com.house365.ws.service.interfaces.*;
import com.house365.ws.system.ReturnAppResult;
import net.sf.json.JSONObject;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>Title: 获取直销人员推荐楼盘</p>
 * <p>Description: </p>
 * <p>Date: 16/9/15</p>
 *
 * @author XN
 * @version 1.0
 */
@Service("getUsersByCity")
public class GetUsersByCityImpl implements IGetUsersByCity {

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

    @Autowired
    private IDepartmentService<DepartmentEntity> departmentService;
    @Autowired
    private IUserService<UserEntity> userService;
    @Autowired
    private ICustomerStatusLogService customerStatusLogService;
    @Autowired
    private IAttachmentService attachmentService;
    @Autowired
    private IProjectSalerService projectSalerService;

    @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);
            response.setData(data);
            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 city = getMapValueByKey("city", map, "");
        String currentPage = getMapValueByKey("page", map, "");
        String pageSize = getMapValueByKey("pageSize", map, "");
        String randOrder = getMapValueByKey("randOrder", map, "");

        //淘房汇直销
        String source = getMapValueByKey("source", map, "");
        String realName = getMapValueByKey("name", map, "");
        String mobile = getMapValueByKey("mobile", map, "");

        DepartmentEntity departmentEntity = departmentService.getDepartmentIdByCity(city);

        Page page = new Page();
        page.setCurrentPage(Integer.valueOf(StringUtils.isBlank(currentPage) ? "1" : currentPage));
        page.setPageSize(Integer.valueOf(StringUtils.isBlank(pageSize) ? "10" : pageSize));

        Map<String, Object> userQueryMap = new HashMap<>();
        userQueryMap.put("REGEXP_deptUrlPath",
                         "^" + departmentEntity.getUrlPath() + "$|^" + departmentEntity.getUrlPath() + "/");
        if (Strings.isNullOrEmpty(source)) {
            userQueryMap.put("EQ_hotlinephoneNotnull", "1");
            userQueryMap.put("EQ_goodatNotnull", "1");
            userQueryMap.put("EQ_descriptionNotnull", "1");
            userQueryMap.put("EQ_headImgNotnull", "1");
            userQueryMap.put("EQ_fullImgNotnull", "1");
        }
        userQueryMap.put("EQ_enabled", "1");
        userQueryMap.put("LIKE_realName", realName);
        userQueryMap.put("LIKE_mobile", mobile);

        QueryParams queryParams = new QueryParams(userQueryMap);

        queryParams.setPaging(page);
        if (Strings.isNullOrEmpty(randOrder)) {
            queryParams.setOrderColumn("rand()");
        } else {
            queryParams.setOrderColumn("id");
            queryParams.setOrderMode("asc");
        }

        List<UserEntity> userEntities = userService.queryByPage(queryParams);
        int total = queryParams.getPaging().getRecords();

        List<UserPo> resultList = new ArrayList<>();
        for (UserEntity userEntity : userEntities) {

            UserPo user = new UserPo();
            user.setId(userEntity.getId());
            user.setRealName(userEntity.getRealName());
            user.setName(userEntity.getName());

            if (Strings.isNullOrEmpty(user.getHeadImgURL())) {
                List<BaseAttachment> headImg = attachmentService.queryByResourceIdAndResouceType(String.valueOf(userEntity.getId()), "hgs_user_headImg");
                if(CollectionUtils.isNotEmpty(headImg)){
                    user.setHeadImgURL(headImg.get(0).getRemotePath());
                } else {
                    user.setHeadImgURL("http://img33.house365.com/M00/1B/86/rBEBp1pu2JyAIp4jAAAGEjOUX2M365.jpg");
                }
            }

            if (Strings.isNullOrEmpty(user.getFullImgURL())) {
                List<BaseAttachment> fullImg = attachmentService.queryByResourceIdAndResouceType(String.valueOf(userEntity.getId()), "hgs_user_fullImg");
                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(userEntity.getScore().toString());
            user.setEvaluateCount(null==userEntity.getEvaluateCount()?0:userEntity.getEvaluateCount());
            user.setMobile(userEntity.getMobile());

            //获取带看次数
            int seeCount = customerStatusLogService.getSeeCount(userEntity.getId());
            seeCount += userEntity.getDefaultVisit();
            user.setSeeCount(seeCount);
            user.setDefaultVisit(userEntity.getDefaultVisit());

            //400短号分机号前加公司固话
            if (StringUtils.isBlank(userEntity.getHotlinephone())) {
                user.setHotlinephone("4008908365");
                user.setCornet("4008908365");
            } else {
                user.setHotlinephone("4008908365," + userEntity.getHotlinephone());
                user.setCornet("4008908365," + userEntity.getHotlinephone());
            }

            //绑定楼盘列表
            List<Map<String,String>> houseList = new ArrayList<>();
            Map<String,Object> searchMap = new HashMap<>();
            QueryParams salerParam = new QueryParams();
            searchMap.put("EQ_userId",userEntity.getId());
            salerParam.setSearchParams(searchMap);
            List<ProjectSalerEntity> proUsers = projectSalerService.queryAll(salerParam);
            for(ProjectSalerEntity projectUser:proUsers){
                Map<String,String> houseMap = new HashMap<>();
                houseMap.put("id", String.valueOf(projectUser.getProjectId()));
                houseMap.put("name", String.valueOf(projectUser.getProjectName()));
                houseMap.put("channel", String.valueOf(projectUser.getChannel()));
                houseList.add(houseMap);
            }
            user.setHouseList(houseList);
            resultList.add(user);
        }

        restObject.setList(resultList);
        restObject.setTotal(String.valueOf(total));

        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;
    }
}
