package com.tax.token.service.util;

import com.alibaba.fastjson.JSON;
import com.tax.token.constants.TokenConstants;
import com.tax.token.model.SmsResFulModel;
import com.tax.token.model.SmsSendReq;
import com.tax.token.service.api.SmsSendLogService;
import com.yxcheng.token.common.enumutil.ResultEnum;
import com.yxcheng.token.common.model.TaxUserInfo;
import com.yxcheng.token.utils.*;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class SmsUtil {

	private static final Logger logger = Logger.getLogger(SmsUtil.class);
	
	private static SmsSendLogService smsSendLogService =  SpringUtil.getBean(SmsSendLogService.class);
	
	public static SmsResFulModel pushSms(String timeFlag, String phone, String zoneCode, String smsCode, String smsFrom, String userCode, SmsSendReq smsSendReq) {
		Date requestTime = DateUtils.getDate();
		SmsResFulModel smsModel = new SmsResFulModel();
		
		String requestUrl = TokenConstants.PUSH_COOKIE_URL;
		String reqParams = "";
		String reqContext = "";
		try {
			JSONObject jsonMap = new JSONObject();
			
            jsonMap.put("sjhm", phone);
            jsonMap.put("dqdm", zoneCode);
            jsonMap.put("smsCode", smsCode);
            jsonMap.put("userCode", userCode);
			jsonMap.put("taxno", smsSendReq.getTaxno());

            TaxUserInfo taxUserInfo = smsSendReq.getUserInfoJson();
            String userInfo = smsSendReq.getUserInfo();
            boolean jsonFlag = false;
            String secret = null;
            if(null != taxUserInfo) {
                secret = taxUserInfo.toString();
                jsonFlag = true;
            } else {
                if(StringUtils.isNotEmpty(userInfo)) {
                    try {
                        secret = new String(Base64Util.decode(userInfo), "UTF-8");
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }
            }
            if(jsonFlag) {
                jsonMap.put("loginInfoJson", JSON.toJSON(taxUserInfo));
            } else {
                jsonMap.put("loginInfo", StringUtil.transNullToEmpty(secret));
            }

			
            reqParams = jsonMap.toString();
            logger.info(timeFlag + " pushSms " + requestUrl + ", params " + reqParams);
            ResponseContent ret = HttpHelper.postJsonEntity(requestUrl, reqParams);
			logger.info(timeFlag + " pushSms " + requestUrl + ", result info is : " + ret.getContent());
			reqContext = ret.getContent();
//			reqContext = "{\"code\" : \"0\",\"message\" : \"成功\",\"data\" : \"123456\",\"proxyip\" : \"127.0.0.1:3762\",\"taxno\" : \"1234567890\"}";
			Map<String, Object> retMap = JSONHelper.parserToMap(reqContext);
			//{"code" : "0","message" : "成功"}
			String errCode = String.valueOf(retMap.get("code"));
			if (!errCode.equals("0")) {
				smsModel.setCode(ResultEnum.sms_push_fail.getCode());
				smsModel.setMessage(String.valueOf(retMap.get("message")));
			} else {
				smsModel.setToken((String)retMap.get("token"));
				smsModel.setTaxno((String)retMap.get("taxno"));
				smsModel.setProxyip((String)retMap.get("proxyip"));
				smsModel.setSession((String)retMap.get("session"));
				smsModel.setUserName((String)retMap.get("userName"));
			}
		} catch (Exception e) {
			e.printStackTrace();
			smsModel.setCode(ResultEnum.sms_push_fail.getCode());
			smsModel.setMessage(ResultEnum.sms_push_fail.getMessage());
			logger.error(timeFlag + "pushSms" + phone + " is error!" + e.getMessage());
		}
		smsSendLogService.saveSmsLog(timeFlag, phone, smsModel, requestTime, requestUrl, smsFrom, reqParams, reqContext, userCode);
		return smsModel;
	}
	
	
	public static final String BASE_NUMBER = "0123456789";
	public static String getRandomNum() {
	    StringBuilder sb = new StringBuilder(6);
	    for (int i = 0; i < 6; i++) {
	        int num = ThreadLocalRandom.current().nextInt(BASE_NUMBER.length());
	        sb.append(BASE_NUMBER.charAt(num));
	    }
	    return sb.toString();
	}
	
	public static String getYzmFromSms(String smsCode) {
		Pattern pattern = Pattern.compile("\\d{6}");
		Matcher matcher = pattern.matcher(smsCode);
		if(matcher.find()) {
			return matcher.group();
		}
		return "";
	}
}
