package com.izouma.dingdong.service.tencent;

import com.alibaba.fastjson.JSONObject;
import com.izouma.dingdong.domain.UserSig;
import com.izouma.dingdong.dto.Send;
import com.izouma.dingdong.repo.UserSigRepo;
import com.tencentyun.TLSSigAPIv2;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.time.LocalDateTime;

import static jodd.core.JoddCore.encoding;

@Slf4j
@Service
public class UserSigService {

    @Value("${IMConfig.sdkAppId}")
    private Long sdkAppId;

    @Value("${IMConfig.secretKey}")
    private String secretKey;

    @Autowired
    private UserSigRepo userSigRecordRepo;

    public String generateUserSig(Long userId) {
        TLSSigAPIv2 api = new TLSSigAPIv2(sdkAppId, secretKey);
        long expire = 86400L;
        String genSig = api.genSig(userId.toString(), expire);
        userSigRecordRepo.save(UserSig
                .builder()
                .userId(userId.toString())
                .sig(genSig)
                .expiresAt(LocalDateTime.now().plusSeconds(expire))
                .build());
        return genSig;
    }

    public String generateUserSig(String userId) {
        TLSSigAPIv2 api = new TLSSigAPIv2(sdkAppId, secretKey);
        long expire = 86400L;
        String genSig = api.genSig(userId, expire);
        userSigRecordRepo.save(UserSig
                .builder()
                .userId(userId)
                .sig(genSig)
                .expiresAt(LocalDateTime.now().plusSeconds(expire))
                .build());
        return genSig;
    }

    public void sendSms(Long userId, String text) {
        String usersig = "";
        String admin = "administrator";
        UserSig sig = userSigRecordRepo.findLastByUserIdAndExpiresAtAfter(admin, LocalDateTime
                .now());
        if (sig == null) {
            usersig = generateUserSig(admin);
        } else {
            usersig = sig.getSig();
        }

        String url = "https://console.tim.qq.com/v4/openim/sendmsg" +
                "?sdkappid=1400375593&identifier=administrator" +
                "&random=99999999&contenttype=json";
        url += "&usersig=" + usersig;

        Send send = new Send();
        send.setMsgRandom(1287657);
        send.setSyncOtherMachine(2);
        send.setToAccount(userId.toString());

        Send.MsgBody msgBody = Send.MsgBody.builder()
                .msgType("TIMTextElem")
                .msgContent(Send.MsgBody.MsgContent.builder()
                        .text(text)
                        .build())
                .build();

        Send.MsgBody[] msg = {msgBody};
        send.setMsgBody(msg);

        String s1 = JSONObject.toJSONString(send);
        System.out.println(s1);

        //http请求
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost(url);

        //添加请求头
        post.setHeader("User-Agent", "Mozilla/5.0");
        post.setHeader("Content-type", "application/json");

        //请求实体
        StringEntity stringEntity = new StringEntity(s1, "utf-8");
        stringEntity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
                "application/json"));

        try {
            post.setEntity(stringEntity);
            //执行请求操作，并拿到结果（同步阻塞）
            CloseableHttpResponse response = client.execute(post);
//            HttpResponse response = client.execute(post);

            /*BufferedReader rd = new BufferedReader(
                    new InputStreamReader(response.getEntity().getContent()));

            StringBuilder result = new StringBuilder();
            String line = "";
            while ((line = rd.readLine()) != null) {
                result.append(line);
            }*/

            //获取结果实体
            HttpEntity entity = response.getEntity();
            String body = "";
            if (entity != null) {
                //按指定编码转换结果实体为String类型
                body = EntityUtils.toString(entity, encoding);
            }
            EntityUtils.consume(entity);
            //释放链接
            response.close();
            System.out.println(body);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
