package com.community.huiju.common.code.impl;

import com.community.commom.constant.Constant;
import com.community.huiju.common.code.ICode;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 手机验证码
 * @author weiximei
 */
@Service("phoneCodeImpl")
@Slf4j
public class PhoneCodeImpl implements ICode {

    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");


    public OkHttpClient getClient() {
        OkHttpClient client  = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10,TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS)
                .build();
        return client;
    }

    @Override
    public boolean sendCode(String phone, String code) {
        boolean bool = false;

        try {
            String result = null;
            OkHttpClient client = getClient();
            RequestBody body = RequestBody.create(JSON, "{\"code\":\""+Constant.CODE+"\"," + "\"tel\":\""+phone+"\"," + "\"params\":[\""+code+"\"]}");
            Request request = new Request.Builder()
                    .url(Constant.REQUEST_URL)
                    .post(body)
                    .build();
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                result = response.body().string();
            } else {
                throw new IOException("Unexpected code " + response);
            }



            if ("发送成功".equals(result)) {
                bool = true;
                log.info("手机号 {} 验证码 {} 发送成功!",phone,code);
            }else {
                bool = false;
                log.error("短信发送验证码失败!{}", result);
            }
        } catch (Exception e){
            e.printStackTrace();
            log.error("短信发送错误!",e);
            bool = false;
        }

        return bool;
    }
}
