package com.zzwtec.wechat.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zzwtec.third.utils.StringUtil;
import com.zzwtec.wechat.util.CommonUtil;
import com.zzwtec.wechat.util.SessionKeyUtil;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName SMSService
 * @Author llf
 * @Date 2018/12/18 0018 9:52
 */
@Service
public class SMSService {

    private static final Logger log = LoggerFactory.getLogger(SMSService.class);

    public final static String content = "验证码为[num]。此验证码只用于验证你的账号是否合法";


    @Value("${sms.yzx.appid}")
    private String yzxAppid;
    @Value("${sms.yzx.sid}")
    private String yzxSid;
    @Value("${sms.yzx.token}")
    private String yzxToken;
    @Value("${sms.yzx.templateid}")
    private String yzxTemplateid;
    @Value("${sms.yzx.url}")
    private String yzxUrl;


    @Autowired
    private OkHttpClient okHttpClient;

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 云之讯短信服务
     */
    private boolean sendSMSByYunZhiXun(String phone, String num, String tmp){
        String uid = CommonUtil.getUUID();
        JSONObject json = JSONObject.parseObject("{}");
        json.put("sid",yzxSid);
        json.put("token",yzxToken);
        json.put("appid",yzxAppid);
        json.put("templateid",yzxTemplateid);
        json.put("param",num);
        json.put("mobile",phone);
        json.put("uid",uid);
        String result_mt = mtByYunZhiXun(yzxUrl,json);
        String msg = tmp.replace("[num]",num);

        if (!result_mt.equals("000000")) {
            // 发送短信，如果不是 000000 就是发送失败。
            System.out.print("发送失败！返回值为："+result_mt+"请查看 http://docs.ucpaas.com/doku.php?id=error_code");
//			logger.error("发送["+phone+"]短信验证失败！返回值为："+result_mt+"请查看webservice返回值对照表");
            return false;
        } else {
            // System.out.print("发送成功，返回值为："+result_mt);

            String key = SessionKeyUtil.getSMSRedisKey(phone);
            redisTemplate.opsForValue().set(key, String.format("%s-%d",num,System.currentTimeMillis()));//存储格式 "验证码-时间戳"，如"1234-1516670934102"
            redisTemplate.expire(key, 5, TimeUnit.MINUTES);
            return true;
        }
    }
    private String mtByYunZhiXun(String url,JSON json){
        try {

            Request request = new Request.Builder()
                    .url(url)
                    .addHeader("Accept", "application/json")
                    .addHeader("Content-Type", "application/json;charset=utf-8")
                    .post(okhttp3.RequestBody.create(MediaType.parse("application/json;charset=utf-8"),json.toJSONString()))
                    .build();
            Response response = okHttpClient.newCall(request).execute();
            if(response.isSuccessful()){
                String result = response.body().string();
                JSONObject revJSON = JSONObject.parseObject(result);
                if(revJSON!=null){
                    return revJSON.getString("code");
                }
                return "";
            }else{
                return "";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    public boolean sendMsg(String phone) {
        if(StringUtil.isEmpty(phone)){
            return false;
        }
        log.info(String.format("send msg to phone: %s",phone));
        String num = CommonUtil.makeVerifyNum(true,4); // 生成验证码
        return sendSMSByYunZhiXun(phone, num, content); // 发送短信 云之讯
    }
}
