package com.muzhi.mt.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.*;
import com.dingtalk.api.response.*;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.pdf.*;
import com.muzhi.mt.service.DingAccessTokenService;
import com.muzhi.mt.service.MiandengService;
import com.muzhi.mt.service.OAhetongService;
import com.taobao.api.ApiException;
import com.taobao.api.FileItem;
import com.taobao.api.internal.util.WebUtils;
import org.springframework.beans.factory.NoUniqueBeanDefinitionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.lang.reflect.Field;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;


/**
 * @Author ZhangKan
 * @Data 15:39
 */

@Service
public class OAhetongServiceImpl implements OAhetongService {


    @Autowired
    private DingAccessTokenService dingAccessTokenService;

    //审批详情
    public static String shenpiXQ = null;

    //合同名称
    public static String hetongMc = null;
    //合同编号
    public static String hetongId= null;

    //审批附件id
    public static String fileId = null;
    //审批附件名称
    public static String fileName = null;
    //审批附件长度
    public static Long fileSize = 0L;
    //审批附件类型
    public static String fileType = null;
    //审批钉盘空间id
    public static String spaceId = null;

    //审批单提交人员id
    public static String originator_userid = null;
    //审批单提交人员部门id
    public static Long originator_dept_id = 0L;

    //审批附件
    public static String shenpiFJ = null;

    // 水印透明度
    private static float alpha = 0.5f;
    // 水印之间的间隔
    private static final int XMOVE = 200;
    // 水印之间的间隔
    private static final int YMOVE = 200;


    public static void setPdfWatermark(String inputPath, String outPath, String markStr) {
        File file = new File(outPath);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
//                log.error("setPdfWatermark fail: 创建输出文件IO异常", e);
//                throw new MyException(ResultCode.FAILURE, "setPdfWatermark fail: 创建输出文件IO异常");
                e.printStackTrace();
            }
        }
        BufferedOutputStream bufferOut = null;
        try {
            bufferOut = new BufferedOutputStream(new FileOutputStream(file));
        } catch (FileNotFoundException e) {
//            log.error("setPdfWatermark fail: 源文件不存在", e);
//            throw new MyException(ResultCode.FAILURE, "setPdfWatermark fail: 源文件不存在");
            e.printStackTrace();
        }
        PdfStamper stamper = null;
        int total = 0;
        PdfContentByte content;
        Rectangle pageSizeWithRotation = null;
        BaseFont base = null;
        PdfReader reader = null;
        try {
            reader = new PdfReader(inputPath);
            //解决PdfReader not opened with owner password
            Field f = PdfReader.class.getDeclaredField("ownerPasswordUsed");
            f.setAccessible(true);
            f.set(reader, Boolean.TRUE);
            stamper = new PdfStamper(reader, bufferOut);
            total = reader.getNumberOfPages() + 1;
            base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
        } catch (IOException e) {
//            log.error("setPdfWatermark fail:", e);
//            throw new MyException(ResultCode.FAILURE, "setPdfWatermark fail");
            e.printStackTrace();
        } catch (DocumentException e) {
//            log.error("setPdfWatermark fail:", e);
//            throw new MyException(ResultCode.FAILURE, "setPdfWatermark fail");
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
        // 获取水印文字的高度和宽度
        int textH = 0, textW = 0;
        JLabel label = new JLabel();
        label.setText(markStr);
        FontMetrics metrics = label.getFontMetrics(label.getFont());
        textH = metrics.getHeight();
        textW = metrics.stringWidth(label.getText());
        PdfGState gs = new PdfGState();
        for (int i = 1; i < total; i++) {
            //在内容上方加水印
            content = stamper.getOverContent(i);
            gs.setFillOpacity(0.5f);
            content.saveState();
            content.setGState(gs);
            content.beginText();
            //设置水印文字颜色
            content.setRGBColorFill(220, 220, 220);
            content.setFontAndSize(base, 20);
            // 获取每一页的高度、宽度
            com.itextpdf.text.Rectangle pageSizeWithRotation1 = reader.getPageSizeWithRotation(i);
            float pageHeight = pageSizeWithRotation1.getHeight();
            float pageWidth = pageSizeWithRotation1.getWidth();

            // 根据纸张大小多次添加， 水印文字成30度角倾斜
            for (int height = -5 + textH; height < pageHeight; height = height + YMOVE) {
                for (int width = -5 + textW; width < pageWidth + textW; width = width + XMOVE) {
                    content.showTextAligned(Element.ALIGN_LEFT, markStr, width - textW, height - textH, 30);
                }
            }
            content.endText();
        }
        try {
            stamper.close();
            bufferOut.flush();
            bufferOut.close();
            reader.close();
        } catch (IOException e) {
//            log.error("setPdfWatermark fail:", e);
//            throw new MyException(ResultCode.FAILURE, "setPdfWatermark fail");
            e.printStackTrace();
        } catch (DocumentException e) {
//            log.error("setPdfWatermark fail:", e);
//            throw new MyException(ResultCode.FAILURE, "setPdfWatermark fail");
            e.printStackTrace();
        }
    }

    @SuppressWarnings("finally")
    public static File downloadFile(String urlPath, String downloadDir) {
        File file = null;
        try {

            URL url = new URL(urlPath);

            URLConnection urlConnection = url.openConnection();

            HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;// http的连接类

            //String contentType = httpURLConnection.getContentType();//请求类型,可用来过滤请求，

            httpURLConnection.setConnectTimeout(1000*5);//设置超时

            httpURLConnection.setRequestMethod("GET");//设置请求方式，默认是GET

            httpURLConnection.setRequestProperty("Charset", "UTF-8");// 设置字符编码


            httpURLConnection.connect();// 打开连接

            BufferedInputStream bin = new BufferedInputStream(httpURLConnection.getInputStream());

            //TODO 修改成动态文件名称：当前审批单的文件名称
//            String fileName = "ceshi.pdf";// 指定文件名称

            String path = downloadDir + File.separatorChar + fileName;// 指定存放位置，此处使用的是全局变量的文件名称
            file = new File(path);
            // 校验文件夹目录是否存在，不存在就创建一个目录
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }

            OutputStream out = new FileOutputStream(file);
            int size = 0;

            byte[] b = new byte[2048];
            //把输入流的文件读取到字节数据b中，然后输出到指定目录的文件
            while ((size = bin.read(b)) != -1) {
                out.write(b, 0, size);
            }
            // 关闭资源
            bin.close();
            out.close();
            System.out.println("文件下载成功！");
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println("文件下载失败！");
        } finally {
            return file;
        }

    }

    //下载、上传合同附件，并创建新的审批单传入添加水印的合同附件【***正式合同审批单***】
    @Override
    public String OAhetong(String processid){
        System.out.println("通过连接器获取的审批单实例id：" + processid);

        //***审批详情***
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/processinstance/get");
            OapiProcessinstanceGetRequest req = new OapiProcessinstanceGetRequest();

            //TODO 审批单实例id（通过OA审批连接器获取到）
            req.setProcessInstanceId(processid);
//            req.setProcessInstanceId("u7qh0maSSkSY-8_YhEPNVg05101645173772");

            OapiProcessinstanceGetResponse rsp = client.execute(req, dingAccessTokenService.getMaoTaiAccessToken());
            shenpiXQ = rsp.getBody();
            System.out.println(rsp.getBody());
        } catch (ApiException e) {
            e.printStackTrace();
        }

        JSONObject jsonObject = JSON.parseObject(shenpiXQ);
        JSONObject processInstance = jsonObject.getJSONObject("process_instance");
        JSONArray form_component_values = processInstance.getJSONArray("form_component_values");


        JSONObject ext_value = form_component_values.getJSONObject(0).getJSONObject("ext_value");

        JSONArray list = ext_value.getJSONArray("list");
        hetongId = list.getJSONObject(0).getJSONArray("rowValue").getJSONObject(0).getString("value");
        System.out.println("关联审批合同编号：" + hetongId);

        //***严格按照OA审批模板中的顺序来填写数组下标，获取附件控件的value值***
        String value = form_component_values.getJSONObject(9).getString("value");
        System.out.println("审批实例详情文件附件控件的数据：" + value);

        hetongMc = form_component_values.getJSONObject(1).getString("value");
        System.out.println("审批实例详情合同名称控件返回值：" + hetongMc);
//        hetongId = form_component_values.getJSONObject(10).getString("value");
//        System.out.println("审批实例详情第一个控件合同编号返回值：" + hetongId);

        originator_userid = processInstance.getString("originator_userid");
        System.out.println("提交人id：" + originator_userid);

        originator_dept_id = processInstance.getLong("originator_dept_id");
        System.out.println("提交人部门id：" + originator_dept_id);

        JSONArray jsonArray = JSON.parseArray(value);

//        循环判断审批单附件控件中有几个合同pdf附件，依次拿到附件相关信息
        for (int i = 0; i <jsonArray.size() ; i++) {
            fileId = jsonArray.getJSONObject(i).getString("fileId");
            System.out.println("审批钉盘文件id：" + fileId);

            fileName = jsonArray.getJSONObject(i).getString("fileName");
            System.out.println("审批钉盘文件名称：" + fileName);

            fileSize = jsonArray.getJSONObject(i).getLong("fileSize");
            System.out.println("审批钉盘文件长度：" + fileSize);

            fileType = jsonArray.getJSONObject(i).getString("fileType");
            System.out.println("审批钉盘文件类型：" + fileType);

            spaceId = jsonArray.getJSONObject(i).getString("spaceId");
            System.out.println("审批钉盘空间id：" + spaceId);


            //***下载审批附件***
            //调用钉钉下载审批附件的接口来下载审批单中的附件（合同pdf文件）
            try {
                DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/processinstance/file/url/get");
                OapiProcessinstanceFileUrlGetRequest req = new OapiProcessinstanceFileUrlGetRequest();
                OapiProcessinstanceFileUrlGetRequest.GrantCspaceRequest obj1 = new OapiProcessinstanceFileUrlGetRequest.GrantCspaceRequest();

                //TODO 审批单实例id（通过OA审批连接器获取到）
                obj1.setProcessInstanceId(processid);

                //TODO 审批实例详情接口中解析出的文件id
                obj1.setFileId(fileId);

                req.setRequest(obj1);
                OapiProcessinstanceFileUrlGetResponse rsp = client.execute(req, dingAccessTokenService.getMaoTaiAccessToken());
                shenpiFJ = rsp.getBody();
                System.out.println(rsp.getBody());
            } catch (ApiException e) {
                e.printStackTrace();
            }

            JSONObject jsonObject1 = JSON.parseObject(shenpiFJ);
            JSONObject result1 = jsonObject1.getJSONObject("result");
            String download_uri = result1.getString("download_uri");
            System.out.println("下载审批钉盘文件返回结果解析出来的url下载地址：" + download_uri);

            //获取当前日期，用于创建文件保存目录中增加当前日期的文件夹作区分
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式 yyyy-MM-dd HH:mm:ss
            String format = df.format(new Date());
            System.out.println(format);// new Date()为获取当前系统时间

//        downloadFile(download_uri,"D:\\pdf\\" + format);//windows端下载文件保存路径
            downloadFile(download_uri,format);//Linux端下载文件保存路径



            //***合同添加水印方法***
            //【Linux下面的路径】
            String strFile = format + File.separator + fileName;
            String strFile1 = format + File.separator + "AAA-" + fileName;

            //【windows下面的路径】
            //原始文件路径
            String a = "D:\\pdf\\" + format + "\\" + fileName;
            //添加水印后保存路径
            String b = "D:\\pdf\\" + format + "\\ABC-" + fileName;
            //生成合同编号
            String c = hetongId + "茅台（上海）融资租赁有限公司";

            setPdfWatermark(strFile, strFile1, c);


            //***单步文件上传***
            String DB_id = null;

            try {
                OapiFileUploadSingleRequest request = new OapiFileUploadSingleRequest();
                //文件大小
                request.setFileSize(fileSize);
                //应用id（自建应用id即可）
                request.setAgentId("1418526292");
                DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/file/upload/single?" + WebUtils.buildQuery(request.getTextParams(), "utf-8"));
                // 必须重新new一个请求
                request = new OapiFileUploadSingleRequest();

                //待上传文件本地路径
                request.setFile(new FileItem(strFile1));

                OapiFileUploadSingleResponse response = client.execute(request, dingAccessTokenService.getMaoTaiAccessToken());
                DB_id = response.getBody();
                System.out.println(response.getBody());
            }catch (ApiException e){
                e.printStackTrace();
            }catch (IOException e){
                e.printStackTrace();
            }

            JSONObject jsonObject_DB = JSON.parseObject(DB_id);
            String media_id = jsonObject_DB.getString("media_id");
            System.out.println("单步上传文件返回的media_id：" + media_id);



            //发送钉盘文件给指定用户
            try {
                OapiCspaceAddToSingleChatRequest request = new OapiCspaceAddToSingleChatRequest();
                request.setAgentId("1418526292");
                request.setUserid(originator_userid);
                request.setMediaId(media_id);
                request.setFileName(fileName);
                DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/cspace/add_to_single_chat?"+WebUtils.buildQuery(request.getTextParams(),"utf-8"));
                OapiCspaceAddToSingleChatResponse response = client.execute(request, dingAccessTokenService.getMaoTaiAccessToken());
                System.out.println(response.getBody());
            }catch (ApiException e){
                e.printStackTrace();
            }catch (IOException e){
                e.printStackTrace();
            }
        }









//        //***获取审批钉盘空间信息（企业审批附件钉盘空间，需通过获取审批钉盘空间信息接口进行【授权】）***
//        String space_XX = null;
//
//        try {
//            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/processinstance/cspace/info");
//            OapiProcessinstanceCspaceInfoRequest req = new OapiProcessinstanceCspaceInfoRequest();
//            //用户id
//            req.setUserId(originator_userid);
//            //企业应用标识，此处可以不传
////            req.setAgentId(1418526292L);
//            OapiProcessinstanceCspaceInfoResponse rsp = client.execute(req, dingAccessTokenService.getMaoTaiAccessToken());
//            space_XX = rsp.getBody();
//            System.out.println(rsp.getBody());
//        } catch (ApiException e) {
//            e.printStackTrace();
//        }
//
//        JSONObject jsonObject_space = JSON.parseObject(space_XX);
//        JSONObject result_space = jsonObject_space.getJSONObject("result");
//        String space_id = result_space.getString("space_id");
//        System.out.println("审批钉盘空间id：" + space_id);



//        //***保存文件到自定义或审批钉盘空间***2
//        String DP = null;
//
//        try {
//            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/cspace/add");
//            OapiCspaceAddRequest req = new OapiCspaceAddRequest();
//
//            //应用id（自建应用id即可）
//            req.setAgentId("1418526292");
//
//            //TODO H5应用免登接口返回的免登授权码code（获取的免登授权码有效期5分钟，且只能使用一次）
//            req.setCode("2820fff89d3b350ba593016db52cd2a1");
//
//            //单步文件上传接口返回的media_id
//            req.setMediaId(media_id);
//            //space_id是审批附件钉盘，folder_id参数传0
//            req.setFolderId("0");
//            //审批钉盘id（一个架构中，审批钉盘id是唯一的）
//            req.setSpaceId("257306648");
//            //上传文件名称
//            req.setName(fileName);
//            //上传至钉盘审批空间是否覆盖同名文件（true：覆盖;false：不覆盖）
//            req.setOverwrite(true);
//
//            req.setHttpMethod("GET");
//            OapiCspaceAddResponse rsp = client.execute(req, dingAccessTokenService.getMaoTaiAccessToken());
//            DP = rsp.getBody();
//            System.out.println(rsp.getBody());
//        } catch (ApiException e) {
//            e.printStackTrace();
//        }
//
//        JSONObject jsonObject_DP = JSON.parseObject(DP);
//        JSONObject dentry = jsonObject_DP.getJSONObject("dentry");
//        String id = dentry.getString("id");
//        System.out.println("保存文件至审批钉盘后返回的钉盘审批文件id：" + id);
//
//
//        //***发起审批实例（最终创建的OA审批单）***
//        try {
//            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/processinstance/create");
//            OapiProcessinstanceCreateRequest req = new OapiProcessinstanceCreateRequest();
//
////            //TODO 审批模板编号（牧之测试架构4）
////            req.setProcessCode("PROC-E148EDE8-EF20-4573-BA7E-22F26BC53A33");
////            //TODO 发起人编号
////            req.setOriginatorUserId("manager5889");
////            //TODO 发起人所在部门，根部门填写-1
////            req.setDeptId(-1L);
//
//            //TODO 审批模板编号（茅台架构）
//            req.setProcessCode("PROC-F65266C2-B28E-4553-91AB-E668F0AA1BDB");
//            //TODO 发起人编号
//            req.setOriginatorUserId(originator_userid);
//            //TODO 发起人所在部门，根部门填写-1
//            req.setDeptId(originator_dept_id);
//
//            ArrayList<OapiProcessinstanceCreateRequest.FormComponentValueVo> formComponentValueVoArrayList = new ArrayList<>();
//
//            OapiProcessinstanceCreateRequest.FormComponentValueVo formComponentValueVo = new OapiProcessinstanceCreateRequest.FormComponentValueVo();
//            OapiProcessinstanceCreateRequest.FormComponentValueVo formComponentValueVo1 = new OapiProcessinstanceCreateRequest.FormComponentValueVo();
//            OapiProcessinstanceCreateRequest.FormComponentValueVo formComponentValueVo10 = new OapiProcessinstanceCreateRequest.FormComponentValueVo();
//
//            formComponentValueVo.setName("合同名称");
//            formComponentValueVo.setValue(hetongMc);
//
//            formComponentValueVo1.setName("合同编号");
//            formComponentValueVo1.setValue(hetongId);
//
//            JSONObject jsonObject_OA = new JSONObject();
//            //TODO 批钉盘空间id（每个架构只有一个唯一的钉盘空间id）
//            jsonObject_OA.put("spaceId", "257306648");
//            //上传文件名称，带后缀
//            jsonObject_OA.put("fileName", fileName);
//            //文件大小，可不传，但是审批单进入后看不到文件大小
//            jsonObject_OA.put("fileSize", fileSize);
//            //上传文件格式
//            jsonObject_OA.put("fileType", fileType);
//            //TODO 审批钉盘文件id
//            jsonObject_OA.put("fileId", id);
//            Object o[] = new Object[]{jsonObject_OA};
//            String s = JSON.toJSONString(o);
//            formComponentValueVo10.setName("附件");
//            formComponentValueVo10.setValue(s);
//
//            formComponentValueVoArrayList.add(formComponentValueVo);
//            formComponentValueVoArrayList.add(formComponentValueVo1);
//            formComponentValueVoArrayList.add(formComponentValueVo10);
//
//            req.setFormComponentValues(formComponentValueVoArrayList);
//            OapiProcessinstanceCreateResponse rsp = client.execute(req, dingAccessTokenService.getMaoTaiAccessToken());
//            System.out.println(rsp.getBody());
//        } catch (ApiException e) {
//            e.printStackTrace();
//        }
//
//        return "创建审批单成功！";

        return "附件已发送给发起人，请查收！";
    }

    //下载、上传合同附件，并创建新的审批单传入添加水印的合同附件【***测试合同审批单***】
    @Override
    public String OAhetongTEST(String processid){
        System.out.println("通过连接器获取的审批单实例id：" + processid);

        //***审批详情***
        try {
            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/processinstance/get");
            OapiProcessinstanceGetRequest req = new OapiProcessinstanceGetRequest();

            //TODO 审批单实例id（通过OA审批连接器获取到）
            req.setProcessInstanceId(processid);

            OapiProcessinstanceGetResponse rsp = client.execute(req, dingAccessTokenService.getMaoTaiAccessToken());
            shenpiXQ = rsp.getBody();
            System.out.println(rsp.getBody());
        } catch (ApiException e) {
            e.printStackTrace();
        }

        JSONObject jsonObject = JSON.parseObject(shenpiXQ);
        JSONObject processInstance = jsonObject.getJSONObject("process_instance");
        JSONArray form_component_values = processInstance.getJSONArray("form_component_values");

        //***严格按照OA审批模板中的顺序来填写数组下标，获取附件控件的value值***
        String value = form_component_values.getJSONObject(2).getString("value");
        System.out.println("审批实例详情第三个控件文件的数据：" + value);

        hetongMc = form_component_values.getJSONObject(0).getString("value");
        System.out.println("审批实例详情第一个控件合同名称返回值：" + hetongMc);
        hetongId = form_component_values.getJSONObject(1).getString("value");
        System.out.println("审批实例详情第一个控件合同编号返回值：" + hetongId);

        originator_userid = processInstance.getString("originator_userid");
        System.out.println("提交人id：" + originator_userid);

        originator_dept_id = processInstance.getLong("originator_dept_id");
        System.out.println("提交人部门id：" + originator_dept_id);

        JSONArray jsonArray = JSON.parseArray(value);

        //循环判断审批单附件控件中有几个合同pdf附件，依次拿到附件相关信息
        for (int i = 0; i <jsonArray.size() ; i++) {
            fileId = jsonArray.getJSONObject(i).getString("fileId");
            System.out.println("审批钉盘文件id：" + fileId);

            fileName = jsonArray.getJSONObject(i).getString("fileName");
            System.out.println("审批钉盘文件名称：" + fileName);

            fileSize = jsonArray.getJSONObject(i).getLong("fileSize");
            System.out.println("审批钉盘文件长度：" + fileSize);

            fileType = jsonArray.getJSONObject(i).getString("fileType");
            System.out.println("审批钉盘文件类型：" + fileType);

            spaceId = jsonArray.getJSONObject(i).getString("spaceId");
            System.out.println("审批钉盘空间id：" + spaceId);


            //***下载审批附件***
            //调用钉钉下载审批附件的接口来下载审批单中的附件（合同pdf文件）
            try {
                DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/processinstance/file/url/get");
                OapiProcessinstanceFileUrlGetRequest req = new OapiProcessinstanceFileUrlGetRequest();
                OapiProcessinstanceFileUrlGetRequest.GrantCspaceRequest obj1 = new OapiProcessinstanceFileUrlGetRequest.GrantCspaceRequest();

                //TODO 审批单实例id（通过OA审批连接器获取到）
                obj1.setProcessInstanceId(processid);

                //TODO 审批实例详情接口中解析出的文件id
                obj1.setFileId(fileId);

                req.setRequest(obj1);
                OapiProcessinstanceFileUrlGetResponse rsp = client.execute(req, dingAccessTokenService.getMaoTaiAccessToken());
                shenpiFJ = rsp.getBody();
                System.out.println(rsp.getBody());
            } catch (ApiException e) {
                e.printStackTrace();
            }

            JSONObject jsonObject1 = JSON.parseObject(shenpiFJ);
            JSONObject result1 = jsonObject1.getJSONObject("result");
            String download_uri = result1.getString("download_uri");
            System.out.println("下载审批钉盘文件返回结果解析出来的url下载地址：" + download_uri);

            //获取当前日期，用于创建文件保存目录中增加当前日期的文件夹作区分
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置日期格式 yyyy-MM-dd HH:mm:ss
            String format = df.format(new Date());
            System.out.println(format);// new Date()为获取当前系统时间

            downloadFile(download_uri,"D:\\pdf\\" + format);



            //***合同添加水印方法***
            //原始文件路径
            String a = "D:\\pdf\\" + format + "\\" + fileName;
            //添加水印后保存路径
            String b = "D:\\pdf\\" + format + "\\AAA-" + fileName;
            //生成合同编号
            String c = hetongId;

            setPdfWatermark(a, b, c);


            //***单步文件上传***
            String DB_id = null;

            try {
                OapiFileUploadSingleRequest request = new OapiFileUploadSingleRequest();
                //文件大小
                request.setFileSize(fileSize);
                //应用id（自建应用id即可）
                request.setAgentId("1418526292");
                DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/file/upload/single?" + WebUtils.buildQuery(request.getTextParams(), "utf-8"));
                // 必须重新new一个请求
                request = new OapiFileUploadSingleRequest();

                //待上传文件本地路径
                request.setFile(new FileItem(b));

                OapiFileUploadSingleResponse response = client.execute(request, dingAccessTokenService.getMaoTaiAccessToken());
                DB_id = response.getBody();
                System.out.println(response.getBody());
            }catch (ApiException e){
                e.printStackTrace();
            }catch (IOException e){
                e.printStackTrace();
            }

            JSONObject jsonObject_DB = JSON.parseObject(DB_id);
            String media_id = jsonObject_DB.getString("media_id");
            System.out.println("单步上传文件返回的media_id：" + media_id);



            //发送钉盘文件给指定用户
            try {
                OapiCspaceAddToSingleChatRequest request = new OapiCspaceAddToSingleChatRequest();
                request.setAgentId("1418526292");
                request.setUserid(originator_userid);
                request.setMediaId(media_id);
                request.setFileName(fileName);
                DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/cspace/add_to_single_chat?"+WebUtils.buildQuery(request.getTextParams(),"utf-8"));
                OapiCspaceAddToSingleChatResponse response = client.execute(request, dingAccessTokenService.getMaoTaiAccessToken());
                System.out.println(response.getBody());
            }catch (ApiException e){
                e.printStackTrace();
            }catch (IOException e){
                e.printStackTrace();
            }
        }











//        //***获取审批钉盘空间信息（企业审批附件钉盘空间，需通过获取审批钉盘空间信息接口进行【授权】）***
//        String space_XX = null;
//
//        try {
//            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/processinstance/cspace/info");
//            OapiProcessinstanceCspaceInfoRequest req = new OapiProcessinstanceCspaceInfoRequest();
//            //用户id
//            req.setUserId(originator_userid);
//            //企业应用标识，此处可以不传
////            req.setAgentId(1418526292L);
//            OapiProcessinstanceCspaceInfoResponse rsp = client.execute(req, dingAccessTokenService.getMaoTaiAccessToken());
//            space_XX = rsp.getBody();
//            System.out.println(rsp.getBody());
//        } catch (ApiException e) {
//            e.printStackTrace();
//        }
//
//        JSONObject jsonObject_space = JSON.parseObject(space_XX);
//        JSONObject result_space = jsonObject_space.getJSONObject("result");
//        String space_id = result_space.getString("space_id");
//        System.out.println("审批钉盘空间id：" + space_id);



//        //***保存文件到自定义或审批钉盘空间***
//        String DP = null;
//
//        try {
//            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/cspace/add");
//            OapiCspaceAddRequest req = new OapiCspaceAddRequest();
//
//            //应用id（自建应用id即可）
//            req.setAgentId("1418526292");
//
//            //TODO H5应用免登接口返回的免登授权码code（获取的免登授权码有效期5分钟，且只能使用一次）
//            req.setCode("2820fff89d3b350ba593016db52cd2a1");
//
//            //单步文件上传接口返回的media_id
//            req.setMediaId(media_id);
//            //space_id是审批附件钉盘，folder_id参数传0
//            req.setFolderId("0");
//            //审批钉盘id（一个架构中，审批钉盘id是唯一的）
//            req.setSpaceId("257306648");
//            //上传文件名称
//            req.setName(fileName);
//            //上传至钉盘审批空间是否覆盖同名文件（true：覆盖;false：不覆盖）
//            req.setOverwrite(true);
//
//            req.setHttpMethod("GET");
//            OapiCspaceAddResponse rsp = client.execute(req, dingAccessTokenService.getMaoTaiAccessToken());
//            DP = rsp.getBody();
//            System.out.println(rsp.getBody());
//        } catch (ApiException e) {
//            e.printStackTrace();
//        }
//
//        JSONObject jsonObject_DP = JSON.parseObject(DP);
//        JSONObject dentry = jsonObject_DP.getJSONObject("dentry");
//        String id = dentry.getString("id");
//        System.out.println("保存文件至审批钉盘后返回的钉盘审批文件id：" + id);
//
//
//        //***发起审批实例（最终创建的OA审批单）***
//        try {
//            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/processinstance/create");
//            OapiProcessinstanceCreateRequest req = new OapiProcessinstanceCreateRequest();
//
////            //TODO 审批模板编号（牧之测试架构4）
////            req.setProcessCode("PROC-E148EDE8-EF20-4573-BA7E-22F26BC53A33");
////            //TODO 发起人编号
////            req.setOriginatorUserId("manager5889");
////            //TODO 发起人所在部门，根部门填写-1
////            req.setDeptId(-1L);
//
//            //TODO 审批模板编号（茅台架构）
//            req.setProcessCode("PROC-F65266C2-B28E-4553-91AB-E668F0AA1BDB");
//            //TODO 发起人编号
//            req.setOriginatorUserId(originator_userid);
//            //TODO 发起人所在部门，根部门填写-1
//            req.setDeptId(originator_dept_id);
//
//            ArrayList<OapiProcessinstanceCreateRequest.FormComponentValueVo> formComponentValueVoArrayList = new ArrayList<>();
//
//            OapiProcessinstanceCreateRequest.FormComponentValueVo formComponentValueVo = new OapiProcessinstanceCreateRequest.FormComponentValueVo();
//            OapiProcessinstanceCreateRequest.FormComponentValueVo formComponentValueVo1 = new OapiProcessinstanceCreateRequest.FormComponentValueVo();
//            OapiProcessinstanceCreateRequest.FormComponentValueVo formComponentValueVo10 = new OapiProcessinstanceCreateRequest.FormComponentValueVo();
//
//            formComponentValueVo.setName("合同名称");
//            formComponentValueVo.setValue(hetongMc);
//
//            formComponentValueVo1.setName("合同编号");
//            formComponentValueVo1.setValue(hetongId);
//
//            JSONObject jsonObject_OA = new JSONObject();
//            //TODO 批钉盘空间id（每个架构只有一个唯一的钉盘空间id）
//            jsonObject_OA.put("spaceId", "257306648");
//            //上传文件名称，带后缀
//            jsonObject_OA.put("fileName", fileName);
//            //文件大小，可不传，但是审批单进入后看不到文件大小
//            jsonObject_OA.put("fileSize", fileSize);
//            //上传文件格式
//            jsonObject_OA.put("fileType", fileType);
//            //TODO 审批钉盘文件id
//            jsonObject_OA.put("fileId", id);
//            Object o[] = new Object[]{jsonObject_OA};
//            String s = JSON.toJSONString(o);
//            formComponentValueVo10.setName("附件");
//            formComponentValueVo10.setValue(s);
//
//            formComponentValueVoArrayList.add(formComponentValueVo);
//            formComponentValueVoArrayList.add(formComponentValueVo1);
//            formComponentValueVoArrayList.add(formComponentValueVo10);
//
//            req.setFormComponentValues(formComponentValueVoArrayList);
//            OapiProcessinstanceCreateResponse rsp = client.execute(req, dingAccessTokenService.getMaoTaiAccessToken());
//            System.out.println(rsp.getBody());
//        } catch (ApiException e) {
//            e.printStackTrace();
//        }
//
//        return "创建审批单成功！";

        return "附件已发送给发起人，请查收！";
    }
}
