package cn.iselab.mooctest.user.util;

import cn.iselab.mooctest.user.constants.VerifyConstants;
import com.cloopen.rest.sdk.CCPRestSmsSDK;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Author: xuexb
 * @Date: 2018.12.28 13:02
 */
@Component
public class MSUtil {

    private static final Logger LOG = LoggerFactory.getLogger(MSUtil.class);

    private static String accountSid;

    private static String accountToken;

    private static String appId;

    @Value("${mobile.accountSid}")
    public void setAccountSid(String accountSid) {
        MSUtil.accountSid = accountSid;
    }

    @Value("${mobile.accountToken}")
    public void setAccountToken(String accountToken) {
        MSUtil.accountToken = accountToken;
    }

    @Value("${mobile.appId}")
    public void setAppId(String appId) {
        MSUtil.appId = appId;
    }

    /**
     * @param receiver
     * @return null if failed vericode if success
     */
    public static String sendSmsVerification(String receiver, String veriCode) {

        // send short message by invoking SDK
        // HashMap<String, Object> result = sendSMSSDK(receiver, VerifyConstants.SMS_VERI_TEMPLATE_ID, veriCode, "5分钟");
        HashMap<String, Object> result = sendSMSSDK(receiver, "73686", veriCode, "5");
        // Check return result to see if process success
        if ("000000".equals(result.get("statusCode"))) {
            // success

            return (String)result.get("statusCode");
        } else {
            // fail, output stats code and message
            LOG.error("[SMS] Sending short message to " + receiver + " failed.");
            LOG.error("[SMS] SMS Error code=" + result.get("statusCode") + "  with information= "
                    + result.get("statusMsg"));

            return (String)result.get("statusCode");
        }
    }

    private static HashMap<String, Object> sendSMSSDK(String receiver, String templateID, String... args) {
        HashMap<String, Object> result = null;

        // Initialize SDK
        CCPRestSmsSDK restAPI = new CCPRestSmsSDK();

        // Initialize remote server and port
        // * Sandbox: restAPI.init("sandboxapp.cloopen.com", "8883");
        // * Production: restAPI.init("app.cloopen.com", "8883");
        restAPI.init("app.cloopen.com", "8883");

        // Initialize ACCOUNT SID & AUTH TOKEN
        // * Can be found by viewing developer's account in `Console` on
        // * website(http://www.yuntongxun.com)
        // restAPI.setAccount("aaf98f89521b91a301522abe22af1760", "356fff5595a14e32a2bc2856cc0f0f5a");
        restAPI.setAccount(accountSid, accountToken);
        // Initialize Target
        // * Can be found in Console:
        // * "Application - application list - specific app"
        restAPI.setAppId(appId);

        // Send SMS
        // * @Parameters
        // * @Parameter(0)
        // * phone number of receiver(split by ',', can support at most 100
        // numbers)
        // * @Parameter(1)
        // * template id(by default 1), can be found in `Console`
        // * @Parameter(2)
        // * An array consists of {verify_code, timeout}
        result = restAPI.sendTemplateSMS(receiver, templateID, args);

        LOG.error("[SMS] SMS Verification result=" + result);

        return result;
    }

    public static String generateRandomVeriCode() {
        int veriCode = (int) Math.round(100000 + Math.random() * 899999);
        return String.valueOf(veriCode);
    }

    public static boolean isMobileNO(String mobiles) {
        Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0-9])|(14[5,7])| (17[0,1,3,5-8]))\\d{8}$");
        Matcher m = p.matcher(mobiles);
        return m.matches();
    }

}
