package thyyxxk.webserver.service.utilities;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import thyyxxk.webserver.config.envionment.WeCom;
import thyyxxk.webserver.service.TokenService;
import thyyxxk.webserver.service.outpatient.wxapi.SendWxInfoService;
import thyyxxk.webserver.utils.StreamWork;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;

@Slf4j
@Service
public class WxUploadFileService {
    private static final String upload_wechat_url = "https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&type=TYPE";
    private final TokenService tokenService;
    private final SendWxInfoService sendWxInfoService;
    private final WeCom weCom;

    @Autowired
    public WxUploadFileService(TokenService tokenService, SendWxInfoService sendWxInfoService, WeCom weCom) {
        this.tokenService = tokenService;
        this.sendWxInfoService = sendWxInfoService;
        this.weCom = weCom;
    }

    public void upload(String touserFrom, File file) throws Exception {
        String weComToken = tokenService.getWeComSendFileToken();
        if (StrUtil.isBlank(weComToken)) {
            log.error("无法上传文件，没有企业微信token");
            return;
        }
        if (StrUtil.isBlank(weCom.getWply())) {
            log.error("无法上传文件，没有设置物品领用接收人。");
            return;
        }
        JSONObject jsonObject = null;
        String last_wechat_url = upload_wechat_url
                .replace("ACCESS_TOKEN", weComToken)
                .replace("TYPE", "file");
        try {
            URL url = new URL(last_wechat_url);
            HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();  //打开链接
            httpUrlConn.setDoInput(true);
            httpUrlConn.setDoOutput(true);
            httpUrlConn.setUseCaches(false); // post方式不能使用缓存
            httpUrlConn.setRequestProperty("Connection", "Keep-Alive");
            httpUrlConn.setRequestProperty("Charset", "UTF-8");
            String BOUNDARY = "----------" + System.currentTimeMillis();
            httpUrlConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);

            String headStr = "--" + BOUNDARY + "\r\nContent-Disposition: form-data;name=\"media\";filelength=\""
                    + file.length() + "\";filename=\"" + file.getName() + "\"\r\nContent-Type:application/octet-stream\r\n\r\n";
            byte[] head = headStr.getBytes(StandardCharsets.UTF_8);

            OutputStream outputStream = new DataOutputStream(httpUrlConn.getOutputStream());
            outputStream.write(head);
            DataInputStream in = new DataInputStream(Files.newInputStream(file.toPath()));
            int bytes;
            byte[] bufferOut = new byte[1024];
            while ((bytes = in.read(bufferOut)) != -1) {
                outputStream.write(bufferOut, 0, bytes);
            }
            in.close();
            byte[] foot = ("\r\n--" + BOUNDARY + "--\r\n").getBytes(StandardCharsets.UTF_8);// 定义最后数据分隔线
            outputStream.write(foot);
            outputStream.flush();
            outputStream.close();
            jsonObject = StreamWork.start(httpUrlConn);

        } catch (IOException e) {
            e.printStackTrace();
        }
        if (jsonObject != null) {
            String result = jsonObject.getString("errmsg");
            if (result.equals("ok")) {
                String mediaId = jsonObject.getString("media_id");
                String touser = touserFrom + "|" + weCom.getWply();
                sendWxInfoService.sendFile(touser, mediaId);
            }
        }
    }
}
