package com.house365.ws.interfaces.rest;

import com.google.common.base.Strings;
import com.house365.beans.entity.ProjectSalerEntity;
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.IProjectSalerService;
import com.house365.ws.system.ReturnAppResult;
import net.sf.json.JSONObject;
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;

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

    private static final Logger LOGGER = LoggerFactory.getLogger(GetGetDirectIdsByCityImpl.class);
    @Autowired
    private IProjectSalerService<ProjectSalerEntity> 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<ProjectSalerEntity> response = new House365RestResponse<>();
        // 业务层统一处理
        try {
            House365RestObject<ProjectSalerEntity> 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()));
        }
        String result = JSONObject.fromObject(response).toString();
        return result;
    }

    /**
     * 业务层统逻辑处理
     */
    private House365RestObject<ProjectSalerEntity> doBusiness(Map<String, Object> map) throws Exception {
        // 返回Json对象
        House365RestObject<ProjectSalerEntity> restObject = new House365RestObject<>();
        String city = getMapValueByKey("city", map, "");
        String currentPage = getMapValueByKey("currentPage", map, "");
        String pageSize = getMapValueByKey("pageSize", map, "");


        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("EQ_city", city);
        QueryParams queryParams = new QueryParams(userQueryMap);
        queryParams.setPaging(page);

        List<ProjectSalerEntity> projectSalerEntities = projectSalerService.queryAll(queryParams);

        StringBuilder directString = new StringBuilder();
        int count = 1;
        for (ProjectSalerEntity projectSalerEntity : projectSalerEntities) {
            JSONObject ps = new JSONObject();
            ps.put("listid", projectSalerEntity.getProjectId());

            String channel = "";
            String[] channels = null;
            //数据不规范
            if(projectSalerEntity.getChannel().contains(",")) {
                channels = projectSalerEntity.getChannel().split(",");
            }else if(projectSalerEntity.getChannel().contains("、")){
                channels = projectSalerEntity.getChannel().split("、");
            }else{
                channels = new String[]{projectSalerEntity.getChannel()};
            }

            int channelCount = 1;
            for (String channelString : channels) {
                switch (channelString) {
                    case "住宅":
                        channel = "1";
                        break;
                    case "写字楼":
                        channel = "2";
                        break;
                    case "别墅":
                        channel = "3";
                        break;
                    case "商业":
                        channel = "4";
                        break;
                    case "公寓":
                        channel = "5";
                        break;
                    default:
                }
                directString.append(projectSalerEntity.getProjectId()).append(",").append(channel)
                        .append(",").append(projectSalerEntity.getUserId());
                if (count < projectSalerEntities.size() || channelCount < channels.length) {
                    directString.append("|");
                }
                channelCount++;
            }
            count++;
        }
        Map result = new HashMap<>();
        result.put("directString", directString.toString());
        restObject.setParaMap(result);
        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;
    }
}
