package com.malk.boyang;

import cn.hutool.core.date.DateUtil;
import com.malk.boyang.service.BoyangService;
import com.malk.server.dingtalk.DDR_New;
import com.malk.service.dingtalk.DDClient;
import com.malk.service.dingtalk.DDClient_Contacts;
import com.malk.service.dingtalk.DDClient_Workflow;
import com.malk.utils.UtilHttp;
import com.malk.utils.UtilMap;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import okio.BufferedSink;
import okio.Okio;
import okio.Sink;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@SpringBootTest
@RunWith(SpringRunner.class)
public class DdTest {
    @Autowired
    private DDClient ddClient;

    @Autowired
    private BoyangService boyangService;

    @Autowired
    private DDClient_Contacts ddClient_contacts;

    @Autowired
    private DDClient_Workflow ddClient_workflow;

    @Test
    public void test(){
        try {
            String downloadPath = "d:\\iwElAqNqcGcDBgTRBOEF0QNABrB2pIOfLsLZggjsjitQfgUABwAIAAmqcGF5SW52b2ljZQoACwA.jpg";

            /*String processInstanceId = "R9N-KN3tTOyNDTIWbxI7LA01161763691347";
            String fileId = "201425340171";

            Map body = new HashMap();
            body.put("processInstanceId",processInstanceId);
            body.put("fileId",fileId);

            DDR_New ddrNew = (DDR_New) UtilHttp.doPost("https://api.dingtalk.com/v1.0/workflow/processInstances/spaces/files/urls/download", ddClient.initTokenHeader(), null, body, DDR_New.class);

            //2、执行下载
            Map result = (Map) ddrNew.getResult();*/

//            String downloadUri = UtilMap.getString(result, "downloadUri");
            String downloadUri = "https://down-cdn.dingtalk.com/ddmedia/iwElAqNqcGcDBgTRBOEF0QNABrB2pIOfLsLZggjsjitQfgUABwAIAAmqcGF5SW52b2ljZQoACwA.jpg";

            URL url = new URL(downloadUri);
            HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
            int responseCode = httpConn.getResponseCode();

            // 检查HTTP响应代码是否为200
            if (responseCode == HttpURLConnection.HTTP_OK) {
                InputStream inputStream = httpConn.getInputStream();
                FileOutputStream outputStream = new FileOutputStream(downloadPath);

                byte[] buffer = new byte[4096];
                int bytesRead = -1;

                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }

                outputStream.close();
                inputStream.close();
            } else {
                System.out.println("无法下载文件。HTTP响应代码: " + responseCode);
            }
            httpConn.disconnect();
        }catch (Exception e){
            throw new RuntimeException(e);
        }

    }

    @Test
    public void test2(){
        boyangService.eSignSubmit(UtilMap.map("processInstanceId","9L_PKi71S8W3kL_nftFpXw01161764152519"));
    }

    @Test
    //上传钉盘附件
    public void testUpload() {
        //获取当前时间戳
        long beginTimestamp = System.currentTimeMillis();
        System.out.println("开始上传附件：" + DateUtil.format(new Date(beginTimestamp), "yyyy-MM-dd HH:mm:ss"));

        //文件
        File file = new File("C:\\Users\\EDY\\Pictures\\2.png");

        //获取文件上传信息
        Map param = new HashMap();
        param.put("unionId","5PK3cMYhiStn7HDoNabweEgiEiE");//wzy
        Map body = new HashMap();
        body.put("protocol","HEADER_SIGNATURE");
        body.put("multipart",false);

        Map header = UtilMap.map("x-acs-dingtalk-access-token","5747a3e5c3823be0bd982dccdf78289e");

        DDR_New ddr = (DDR_New) UtilHttp.doPost("https://api.dingtalk.com/v1.0/storage/spaces/" + "27105381865" + "/files/uploadInfos/query", header, param, body, DDR_New.class);
        String uploadKey = ddr.getUploadKey();
        Map headerSignatureInfo = ddr.getHeaderSignatureInfo();
        Map<String,String> headers = (Map<String,String>) headerSignatureInfo.get("headers");
        List<String> resourceUrls = (List<String>) headerSignatureInfo.get("resourceUrls");
        String resourceUrl = resourceUrls.get(0);

        Map dentry = new HashMap();
        //使用OSS的header加签方式上传文件
        try {
            URL url = new URL(resourceUrl);
            HttpURLConnection connection = (HttpURLConnection)url.openConnection();
            if (headers != null) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    connection.setRequestProperty(entry.getKey(), entry.getValue());
                }
            }
            connection.setDoOutput(true);
            connection.setRequestMethod("PUT");
            connection.setUseCaches(false);
            connection.setReadTimeout(10000);
            connection.setConnectTimeout(10000);
            connection.connect();
            OutputStream out = connection.getOutputStream();
            InputStream is = new FileInputStream(file);
            byte[] b =new byte[1024];
            int temp;
            while ((temp=is.read(b))!=-1){
                out.write(b,0,temp);
            }
            out.flush();
            out.close();
            int responseCode = connection.getResponseCode();
            connection.disconnect();
            if (responseCode == 200) {
                System.out.println("上传成功");
            } else {
                System.out.println("上传失败");
            }
            //提交文件
            Map body2 = new HashMap();
            Map option = new HashMap();
            option.put("conflictStrategy","OVERWRITE");
            body2.put("uploadKey",uploadKey);
            body2.put("name",file.getName());
            body2.put("option",option);

//            param.put("unionId","58FDG7fqGyXrGziPavPO4kQiEiE");//lqy

            DDR_New ddrNew = (DDR_New) UtilHttp.doPost("https://api.dingtalk.com/v2.0/storage/spaces/files/"+ "DEN7dx2rn0JbYn37a7acrVMGjLRb3o1v" +"/commit", header, param, body2, DDR_New.class);
            dentry = ddrNew.getDentry();

        }catch (IOException e){
            log.info("上传文件异常:{}",e);
        }

        long endTimestamp = System.currentTimeMillis();
        System.out.println("上传文件结束：" + DateUtil.format(new Date(endTimestamp), "yyyy-MM-dd HH:mm:ss"));
        System.out.println("上传文件耗时：" + (endTimestamp - beginTimestamp)/1000.0 + "s");
        System.out.println(dentry);
    }

    @Test
    public void test3() {
        Map result = ddClient_workflow.getProcessInstanceId(ddClient.getAccessToken(), "yY-nxf1UTUWxEUXnjDv7Yg01161768554568");
        String originatorUserId = UtilMap.getString(result, "originatorUserId");

        Map userInfo = ddClient_contacts.getUserInfoById(ddClient.getAccessToken(), originatorUserId);

        String originatorUserIdUnionid = UtilMap.getString(userInfo, "unionid");

        System.out.println(originatorUserIdUnionid);

    }
}

