package com.weaver.seconddev.chapanda.qunjie.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.weaver.eteams.file.client.file.FileData;
import com.weaver.eteams.file.client.file.FileObj;
import com.weaver.file.ud.api.FileDownloadService;
import com.weaver.seconddev.chapanda.qunjie.constant.Constants;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.message.BasicHeader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import java.util.Base64;
import java.nio.charset.Charset ;

@Component
public class Esb2QunjieCreateApplySealUtil {
    private final static Logger log = LoggerFactory.getLogger(Esb2QunjieCreateApplySealUtil.class);

    @Autowired
    private Esb2QunjieTokenUtil esb2QunjieTokenUtil;

    @Autowired
    private FileDownloadService fileDownloadService;

    public Map<String, Object> applySealRequest(String requestName,String sealId,String applyCount,String applyCrossPageSealCount,Long fileid) {
        log.error("applySealRequest start");
        Map<String, Object> messageMap = new HashMap<String, Object>();

        FileData fileData = fileDownloadService.downloadFile(fileid);
        FileObj fileObj = fileData.getFileObj();
        String fileName = fileObj.getName();
        log.error("fileName:{}",fileName);
        InputStream fileInputStream = null;
        try{
            fileInputStream = fileData.getInputStream();

            if(fileInputStream.available() > 0) {

                byte[] fileByte = convertInputStreamToBytes(fileInputStream);
                log.error("fileByte:{}",fileByte.length);

                if(fileByte.length > 0){
                    String token = esb2QunjieTokenUtil.getAccessToken();
                    log.error("token:"+token);
                    if(StringUtils.isNotBlank(token)){


//                        {
//                            "title": "测试20250704",
//                                "applyerUserName": "admin",
//                                "callBackUrl": "baidu.com",
//                                "usedSealParamList": [
//                            {
//                                "sealId": "4e22398d-0ab1-4226-8546-7f65f6f8622d",
//                                    "takeOut": "0",
//                                    "applyCount": "1"
//                            }
//    ],
//                            "option": {
//                            "watermark": "1",
//                                    "preventWaterMark": "1"
//                        }
//                        }


                        JSONArray usedSealParamList = new JSONArray();
                        JSONObject usedSealParam = new JSONObject();
                        usedSealParam.put("sealId",sealId);
                        usedSealParam.put("takeOut","0");
                        usedSealParam.put("applyCount",applyCount);
                        usedSealParam.put("applyCrossPageSealCount",applyCrossPageSealCount);
                        usedSealParamList.add(usedSealParam);

                        JSONObject optionJson = new JSONObject();
                        optionJson.put("ocr",Constants.ocr);
                        optionJson.put("preventOcrCompare",Constants.preventOcrCompare);
                        optionJson.put("watermark",Constants.watermark);
                        optionJson.put("preventWaterMark",Constants.preventWaterMark);
                        optionJson.put("preventPower",Constants.preventPower);
                        optionJson.put("prevent",Constants.prevent);
                        optionJson.put("remoteMonitoringSwitch",Constants.remoteMonitoringSwitch);
                        optionJson.put("oneCodeOneUseSwitch",Constants.oneCodeOneUseSwitch);
                        optionJson.put("compound",Constants.compound);
                        JSONObject bodyJson = new JSONObject();
                        bodyJson.put("title",requestName);
                        bodyJson.put("applyerUserName",Constants.applyerUserName);
                        bodyJson.put("usedSealParamList",usedSealParamList);
                        bodyJson.put("option",optionJson);

                        log.error("bodyJson:"+bodyJson.toJSONString());

                        String message= doFormDataPost(bodyJson.toJSONString(),token,fileName,fileByte);
//                        String message= doPostReqeustByOkHttp(bodyJson.toJSONString(),token,fileName,fileByte);
                        log.error("message:{}",message);
                        messageMap = convertBodyDataToMap(message);
                    }
                }
            }

            fileInputStream.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            if(fileInputStream !=null){
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }


        return messageMap;
    }

    public String doPostReqeustByOkHttp(String bodyData,String token,String fileName,byte[] fileByte){
        String msg = "";

        log.error("fileByte:{}",fileByte.length);
        log.error("fileName:{}",fileName);
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();



//        {
//            "title": "测试20250704",
//                "applyerUserName": "admin",
//                "callBackUrl": "baidu.com",
//                "usedSealParamList": [
//            {
//                "sealId": "5021257c-1002-491a-b111-6618914123f4",
//                    "takeOut": "0",
//                    "applyCount": "1"
//            }
//    ],
//            "option": {
//            "watermark": "1",
//                    "preventWaterMark": "1"
//        }
//        }

        try {
            String encodedFileName = new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8);
            RequestBody body = new MultipartBody.Builder().setType(MediaType.get("multipart/form-data;charset=utf-8"))
                    .addFormDataPart("workflowApplyParam",bodyData)
                    .addFormDataPart("file",encodedFileName, RequestBody.create(MediaType.parse("application/octet-stream"),fileByte))
                    .build();
            Request request = new Request.Builder()
                    .url(Constants.qunjieHost+ Constants.applyUrl)
                    .method("POST", body)
                    .addHeader("Authorization", "Bearer "+token)
                    .build();
            Response response = client.newCall(request).execute();
            int code = response.code();
            log.error("code:{}",code);
            msg = response.body().string();
            log.error("msg:"+msg);
        } catch (Exception e) {
            log.error("e:"+e);
        }
        return msg;
    }

    public byte[] convertInputStreamToBytes(InputStream inputStream) throws IOException {
        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
        log.error("inputStream2:{}",inputStream.available());
        byte[] buffer = new byte[4096];
        int bytesRead;
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            byteStream.write(buffer, 0, bytesRead);
        }
        log.error("byteStream:{}",byteStream.toByteArray().length);

        return byteStream.toByteArray();
    }


    public Map<String, Object> convertBodyDataToMap(String message) {
        Map<String, Object> messageMap = new HashMap<String, Object>();

        if(StringUtils.isNotBlank(message)){
            JSONObject returnData = JSONObject.parseObject(message);
            if(returnData.containsKey("status")){
                String status = returnData.getString("status");
                log.error("status:"+status);
                if("0".equals(status)){
                    JSONObject dataJson = returnData.getJSONObject("data");
                    String applyId = dataJson.getString("applyId");
                    String workflowBaseId = dataJson.getString("workflowBaseId");
                    String formId = dataJson.getString("formId");
                    String applyNo = dataJson.getString("applyNo");
                    String safeCode = dataJson.getString("safeCode");
                    String applyStatus = dataJson.getString("status");

                    log.error("applyId:{}",applyId);
                    log.error("workflowBaseId:{}",workflowBaseId);
                    log.error("formId:{}",formId);
                    log.error("applyNo:{}",applyNo);
                    log.error("safeCode:{}",safeCode);
                    log.error("applyStatus:{}",applyStatus);
                    if("null".equals(applyStatus)){
                        applyStatus = "";
                    }

                    String vrCode = "";
                    if(dataJson.containsKey("usedSealParamList")){
                        JSONArray usedSealParamArray = dataJson.getJSONArray("usedSealParamList");
                        log.error("usedSealParamArray:{}",usedSealParamArray.size());
                        for(int i=0;i<usedSealParamArray.size();i++){
                            JSONObject usedSealJson = usedSealParamArray.getJSONObject(i);
                            log.error("usedSealJson:{}",usedSealJson.toJSONString());
                            if(usedSealJson.containsKey("takeOrPutQrCode")){
                                JSONObject takeOrPutQrCode = usedSealJson.getJSONObject("takeOrPutQrCode");
                                if(takeOrPutQrCode.containsKey("takeCode") || takeOrPutQrCode.containsKey("putCode")){
                                    JSONObject takeCode = takeOrPutQrCode.getJSONObject("takeCode");
                                    JSONObject putCode = takeOrPutQrCode.getJSONObject("putCode");
                                    if(takeCode.containsKey("vrCode")){
                                        vrCode = takeCode.getString("vrCode");
                                    }else if(putCode.containsKey("vrCode")){
                                        vrCode = putCode.getString("vrCode");
                                    }
                                }
                            }
                        }
                    }

                    log.error("vrCode:"+vrCode);

                    messageMap.put("applyId",applyId);
                    messageMap.put("workflowBaseId",workflowBaseId);
                    messageMap.put("formId",formId);
                    messageMap.put("applyNo",applyNo);
                    messageMap.put("safeCode",safeCode);
                    messageMap.put("vrCode",vrCode);
                    messageMap.put("status",applyStatus);
                }
            }
        }

        return messageMap;
    }



    public String doFormDataPost(String bodyData,String token,String fileName,byte[] fileByte) {

        String resEntity = "";
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(Constants.qunjieHost+ Constants.applyUrl);
        //传递文件参数以及文本参数
        httpPost.setHeader("charset", "utf-8");
        httpPost.addHeader("Accept", "*/*");
        httpPost.addHeader("Accept-Encoding", "UTF-8");
        httpPost.addHeader("User-Agent", " Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36");

        try{

            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setCharset(StandardCharsets.UTF_8);//设置编码，解决中文乱码问题
            builder.setMode(HttpMultipartMode.RFC6532);

            builder.addBinaryBody("file", fileByte,ContentType.MULTIPART_FORM_DATA,fileName);
            ContentType contentType = ContentType.create("multipart/form-data",Charset.forName("UTF-8"));  //重新设置UTF-8编码，默认编码是ISO-8859-1
            builder.addTextBody("workflowApplyParam", bodyData,contentType);
            httpPost.setHeader("Authorization", "Bearer "+token);
            //发送post请求
            httpPost.setEntity(builder.build());
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity responseEntity = response.getEntity();
            resEntity = EntityUtils.toString(responseEntity, "UTF-8");
            log.error("resEntity:{}",resEntity);
        }catch (Exception e){
            log.error("e:{}",e);
        }
        return resEntity;
    }



    public static void main(String[] args) throws IOException {
        JSONObject bodyData = new JSONObject();

        bodyData.put("title","测试20250730-10");
        bodyData.put("applyerUserName","admin");

        JSONArray usedSealParamList = new JSONArray();
        JSONObject usedSealParam = new JSONObject();
        usedSealParam.put("sealId","4e22398d-0ab1-4226-8546-7f65f6f8622d");
        usedSealParam.put("takeOut","0");
        usedSealParam.put("applyCount","1");
        usedSealParamList.add(usedSealParam);

        JSONObject option = new JSONObject();
        option.put("watermark","1");
        option.put("preventWaterMark","1");
        bodyData.put("option",option);
        bodyData.put("usedSealParamList",usedSealParamList);

        String token = "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ7XCJhcHBfa2V5XCI6bnVsbCxcImNvbXBhbnlfaWRcIjpcImFiZGVlYzdiLTY0N2EtNDhjMy1iNDE0LTNiOWJkZDZlMGE0MFwiLFwidXNlcl9pZFwiOlwiMTBcIixcInVzZXJfbmFtZVwiOlwiYXBpYWRtaW5cIixcImFwcF9pZFwiOm51bGwsXCJhcHBfc2VjcmV0XCI6bnVsbH0iLCJpc3MiOiJhcG9sbG8tYXBpIiwiaWF0IjoxNzUzOTI0ODU4LCJleHAiOjE3NTM5MzIwNTh9.keGXQmbdw5ayZHBeyBJlaiHCKzf4lB-2MBExJuNb5dc";
//        doPostReqeustByOkHttp2(bodyData.toJSONString(),token);
//        doFormDataPost(bodyData.toJSONString(),token);
    }


}
