package com.tzld.piaoquan.growth.common.service.Impl;

import com.alibaba.fastjson.JSON;
import com.tzld.piaoquan.growth.common.component.HttpPoolClient;
import com.tzld.piaoquan.growth.common.model.vo.SendRequestParam;
import com.tzld.piaoquan.growth.common.service.WeComSendService;
import com.tzld.piaoquan.growth.common.utils.LarkRobotUtil;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.util.Base64;

@Slf4j
@Service
public class WeComSendServiceImpl implements WeComSendService {

    @Autowired
    private HttpPoolClient httpPoolClient;

    @Value("${sendRequestIp:}")
    private String sendRequestIp;


    @Override
    public String sendPost(String url, String param) throws IOException {
        if (StringUtils.isEmpty(sendRequestIp)) {
            LarkRobotUtil.sendMessage("转发ip获取失败");
            return null;
        }
        String sendUrl = "http://" + sendRequestIp + "/wecom/server/send/post";
        SendRequestParam sendRequestParam = new SendRequestParam();
        sendRequestParam.setUrl(url);
        sendRequestParam.setParam(param);
        String res = httpPoolClient.post(sendUrl, JSON.toJSONString(sendRequestParam));
        log.info("sendPost res={}", res);
        return res;
    }

    @Override
    public String sendGet(String url) throws IOException {
        if (StringUtils.isEmpty(sendRequestIp)) {
            LarkRobotUtil.sendMessage("转发ip获取失败");
            return null;
        }
        String sendUrl = "http://" + sendRequestIp + "/wecom/server/send/get";
        sendUrl += "?url=" + Base64.getEncoder().encodeToString(url.getBytes());
        String res = httpPoolClient.get(sendUrl);
        log.info("sendGet res={}", res);
        return res;
    }

    @Override
    public String sendPostFile(String url, String cover) throws IOException {
        if (StringUtils.isEmpty(sendRequestIp)) {
            LarkRobotUtil.sendMessage("转发ip获取失败");
            return null;
        }
        String sendUrl = "http://" + sendRequestIp + "/wecom/server/send/post/file";
        sendUrl += "?url=" + Base64.getEncoder().encodeToString(url.getBytes());
        sendUrl += "&cover=" + Base64.getEncoder().encodeToString(cover.getBytes());
        String res = httpPoolClient.get(sendUrl);
        log.info("sendPostFile res={}", res);
        return res;
    }
}
