package com.house365.ws.util;

import com.google.common.base.Strings;
import com.house365.commons.system.HttpClientUtil;
import com.house365.rest.context.CmConstant;
import com.house365.rest.exception.IllegalServiceParameterException;
import com.house365.web.util.MemoryPropertyPlaceholderConfigurer;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Pattern;

/**
 * 邀请码工具<br>
 * 〈功能详细描述〉
 *
 * @author yinchangming
 * @version [v1.0.0, 2015年10月15日]
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
public class CmCommonUtils {
    private static final Logger LOGGER = LoggerFactory.getLogger(CmCommonUtils.class);
    private static ExecutorService executor = Executors.newCachedThreadPool();

    /**
     * 功能描述: <br>
     * 通过连续签到日期来确定当日获得的积分(没有加上基础积分)
     *
     * @param signCount
     * @return
     * @author yinchangming
     * @version [v1.0.0, 2015年10月22日]
     * @since [产品/模块版本](可选)
     */
    public static Integer getSignCreditsByContinuousSignCount(Integer signCount) {
        if (signCount == 0) {
            return 0;
        }
        if (signCount % 5 == 0) {
            //30天一个循环
            switch (signCount % 30 / 5) {
                case 1:
                    return 10;
                case 2:
                    return 20;
                case 4:
                    return 30;
                case 0:
                    return 40;
            }
        }
        return 0;
    }

    public static void checkInterfaceParameter(
        String[] checkParams, Map<String, Object> map
    ) throws IllegalServiceParameterException {
        // 方法所需参数
        for (String str : checkParams) {
            // 如果不存在跳出 同时抛出相应异常
            if (!map.containsKey(str)) {
                throw new IllegalServiceParameterException("业务入口参数异常：" + str + "参数为空!");
            }
        }
    }

    public static void callCRM(
        final String mobile, final String city, final String activeFrom, final String activeName
    ) {
        if (Strings.isNullOrEmpty(mobile) || Strings.isNullOrEmpty(city) || Strings.isNullOrEmpty(
            activeFrom) || Strings.isNullOrEmpty(activeName)) {
            LOGGER.warn("CALL CRM parameters warn, mobile:{} city:{} activeFrom:{} activeName:{}", mobile, city,
                        activeFrom, activeName);
        } else {
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        final String name = java.net.URLEncoder.encode(activeName, "UTF-8");

                        final String CRMTRIGGER = MemoryPropertyPlaceholderConfigurer.getContextProperty("callCRM");
                        if (!Strings.isNullOrEmpty(CRMTRIGGER) && "1".equals(CRMTRIGGER)) {
                            List<NameValuePair> paramList = new ArrayList<>();
                            paramList.add(new BasicNameValuePair("mobile", mobile));
                            paramList.add(new BasicNameValuePair("activefrom", activeFrom));
                            paramList.add(new BasicNameValuePair("city", city));
                            paramList.add(new BasicNameValuePair("activename", name));
                            final String urlString = "http://crm.house365.com:81/index.php/Simulate/sea";
                            String response = HttpClientUtil.doGet(urlString, paramList, "UTF-8");
                            LOGGER.info("CALL_CRM_LOG:[{}]",
                                        urlString + "_" + mobile + "_" + activeFrom + "_" + city + "_" + name + "_" + response);
                        }
                    } catch (java.io.IOException e) {
                        LOGGER.error(e.getMessage(), e);
                    }
                }
            });
        }
    }

    //判断是否为数字
    public static boolean isNumeric(String str) {
        Pattern pattern = Pattern.compile("[0-9]*");
        return pattern.matcher(str).matches();
    }

    public static String getCityFromMap(Map<String, Object> map) {
        String city = null;
        if (map.get(CmConstant.USER_CITY_KEY) != null) {
            if (((String[]) map.get(CmConstant.USER_CITY_KEY)).length > 0) {
                city = ((String[]) map.get(CmConstant.USER_CITY_KEY))[0];
            }
        }
        return city;
    }

    public static boolean versionCheck(String v, String requiredVersion) {
        try {
            if (Strings.isNullOrEmpty(v) || Strings.isNullOrEmpty(requiredVersion)) {
                return false;
            }

            String[] split = v.split("\\.");
            String[] requiredVersionSplit = requiredVersion.split("\\.");
            if (split.length < 3 || requiredVersionSplit.length < 3) {
                return false;
            }

            for (int i = 0; i < 3; i++) {
                if (Strings.isNullOrEmpty(split[i]) || Strings.isNullOrEmpty(requiredVersionSplit[i])) {
                    return false;
                }
            }

            int largeV = Integer.valueOf(split[0]);
            int middleV = Integer.valueOf(split[1]);
            int smallV = Integer.valueOf(split[2]);

            int rLargeV = Integer.valueOf(requiredVersionSplit[0]);
            int rMiddleV = Integer.valueOf(requiredVersionSplit[1]);
            int rSmallV = Integer.valueOf(requiredVersionSplit[2]);

            if (largeV < rLargeV) {
                return false;
            }

            if (largeV > rLargeV) {
                return true;
            }

            if (middleV < rMiddleV) {
                return false;
            }

            if (middleV > rMiddleV) {
                return true;
            }

            if (smallV < rSmallV) {
                return false;
            }

            if (smallV >= rSmallV) {
                return true;
            }

            return false;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static void main(String[] args) {
        for (int i = 0; i <= 60; i++) {
            int count = getSignCreditsByContinuousSignCount(i) + 5;
            System.out.println(i + ":" + count);
        }
        //        System.out.println("is number : " + isNumeric("1234a98888888888888"));

        //        System.out.println(versionCheck("6.2.0.0", "6.1.8"));

    }

}
