package com.house365.ws.interfaces.rest;

import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.house365.beans.entity.CustomerEntity;
import com.house365.beans.vo.CrmVisitAndSignCustomer;
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.DateTimeUtils;
import com.house365.ws.cached.RedisUtilsInterface;
import com.house365.ws.service.interfaces.ICustomerService;
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.*;
import java.util.concurrent.TimeUnit;

/**
 * <p>Title: 400新增客户信息</p>
 * <p>Description: </p>
 * <p>Date: 16/9/15</p>
 *
 * @author XN
 * @version 1.0
 */
@Service("getCusForCRM")
public class CrmVisitAndSignImpl implements ICrmVisitAndSignCustomers {
    /**
     * 跟踪状态：有效
     */
    private final Logger LOGGER = LoggerFactory.getLogger(CrmVisitAndSignImpl.class);
    @Autowired
    private ICustomerService<CustomerEntity> customerService;
    @Autowired
    private RedisUtilsInterface redisUtil;

    @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<Map<String, List<CrmVisitAndSignCustomer>>> response = new House365RestResponse<Map<String, List<CrmVisitAndSignCustomer>>>();
        // 业务层统一处理
        String result = "";
        try {
            House365RestObject<Map<String, List<CrmVisitAndSignCustomer>>> data = null;
            String state = getMapValueByKey("state", map, "");
            String month = getMapValueByKey("month", map, "");
            String city = getMapValueByKey("city", map, "");
            String cacheKey = new StringBuilder("GetCusForCRM_v4_").append(state).append("_").append(month).append("_").append(
                    city).toString();

            if (!redisUtil.hasKey(cacheKey)) {
                data = doBusiness(map);
                String msg = ReturnAppResult.APP_SUCCESS.getResultMessage();
                if (data.getParaMap() != null && data.getParaMap().containsKey("msg")) {
                    msg = ReturnAppResult.APP_SUCCESS.getResultMessage() + "[" + String.valueOf(
                            data.getParaMap().get("msg") + "]");
                }

                response.setData(data);
                response.setResult(ReturnAppResult.APP_SUCCESS.getResultCode());
                response.setMsg(msg);
                result = JSONObject.fromObject(response).toString();
                redisUtil.setValueExpireNew(cacheKey, result, 30, TimeUnit.DAYS);
            } else {
                result = redisUtil.getValByKeyNew(cacheKey);
            }

        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            response.setResult(ReturnAppResult.APP_FAIL.getResultCode());
            response.setMsg((ReturnAppResult.APP_FAIL.getResultMessage() + ":" + e.getMessage()));
        }
        return result;
    }

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

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

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

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

        if (Strings.isNullOrEmpty(month)) {
            Date lastMonth = DateTimeUtils.getMonthAgo(new Date(), 1);
            month = DateTimeUtils.parseDate(lastMonth, "yy-MM");
        } else {
            Date date = DateTimeUtils.parseDate(month, "yy-MM");
            month = DateTimeUtils.parseDate(date, "yy-MM");
            if (null == date) {
                throw new ServiceRunException("日期参数有误");
            }
        }

        List<String> stateList = new ArrayList<>();
        if (Strings.isNullOrEmpty(state)) {
            stateList = Lists.newArrayList("2","4","5");
        } else {
            for (String stat : state.split(",")) {
                if ("2".equalsIgnoreCase(stat)) {
                    stateList.add("2");
                } else if ("4".equalsIgnoreCase(stat)) {
                    stateList.add("4");
                } else if ("5".equalsIgnoreCase(stat)) {
                    stateList.add("5");
                }
            }
        }

        Map<String, List<CrmVisitAndSignCustomer>> resultMap = new HashMap<>();

        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("state", stateList);
        queryMap.put("month", month);
        queryMap.put("city", city);

        List<CrmVisitAndSignCustomer> list = customerService.crmVisitAndSignCustomer(queryMap);

        for (CrmVisitAndSignCustomer customer : list) {

            if (resultMap.containsKey(customer.getBuildingId())) {
                List<CrmVisitAndSignCustomer> projectList = resultMap.get(customer.getBuildingId());
                projectList.add(customer);

            } else {
                List<CrmVisitAndSignCustomer> projectList = new ArrayList<>();
                projectList.add(customer);
                resultMap.put(customer.getBuildingId(), projectList);

            }

        }

        restObject.setEntity(resultMap);
        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;
    }

    private String getJsonValueByKey(String key, JSONObject obj, String defaultValue) {
        String value = "";
        if (obj.containsKey(key) && obj.get(key) != null && !Strings.isNullOrEmpty(String.valueOf(obj.get(key)))) {
            value = String.valueOf(obj.get(key));
        }

        if (Strings.isNullOrEmpty(value)) {
            value = defaultValue;
        }
        return value;
    }

    /**
     * 业务层统校验自己所需参数是否存在
     * 所有参数都要存在
     *
     * @author hqc
     */
    protected void checkInterfaceParameter(
            Map<String, Object> map, String[] checkParams
    ) throws IllegalServiceParameterException {
        if (map.containsKey("type") && "batch".equalsIgnoreCase(((String[]) map.get("type"))[0])) {

        } else {
            // 方法所需参数
            for (String str : checkParams) {
                // 如果不存在跳出 同时抛出相应异常
                if (!map.containsKey(str)) {
                    throw new IllegalServiceParameterException("业务入口参数异常：" + str + "参数为空!");
                }
            }
        }
    }

}
