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 com.weaver.seconddev.chapanda.qunjie.dao.SealsManageDao;
import okhttp3.*;
import org.apache.commons.lang3.StringUtils;
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.ContentType;
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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


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

    @Autowired
    private Esb2QunjieTokenUtil esb2QunjieTokenUtil;

    @Autowired
    private FileDownloadService fileDownloadService;

    @Autowired
    SealsManageDao sealsManageDao;

    public Map<String, Object> applySealRequest(String requestid,String requestName,String fileids) {
        Map<String, Object> messageMap = new HashMap<String, Object>();

//        MultipartBody.Builder multipartBodyBuilder = new MultipartBody.Builder().setType(MediaType.get("multipart/form-data;charset=utf-8"));

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

        InputStream inputStream = null;
        try {
            String[] fileidArray = fileids.split(",");
            for(int i=0;i<fileidArray.length;i++){
                Long fileid = Long.valueOf(fileidArray[i]);
                FileData fileData = fileDownloadService.downloadFile(fileid);
                FileObj fileObj = fileData.getFileObj();
                String fileName = fileObj.getName();
                log.error("fileName:{}",fileName);
//                String encodedFileName = URLEncoder.encode(fileName, "UTF-8");
                inputStream = fileData.getInputStream();
                if (inputStream.available() > 0) {
                    byte[] fileByte = convertInputStreamToBytes(inputStream);
                    log.error("fileByte:{}", fileByte.length);
                    if (fileByte.length > 0) {
//                        multipartBodyBuilder.addFormDataPart("file",encodedFileName, RequestBody.create(MediaType.parse("application/octet-stream"),fileByte));
                        builder.addBinaryBody("file", fileByte, ContentType.MULTIPART_FORM_DATA,fileName);
                    }
                }
            }
            inputStream.close();
        }catch (IOException e){
            log.error("e:{}",e);
        }finally {
            if(inputStream !=null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }

        JSONObject bodyJson = new JSONObject();
        JSONArray usedSealParamList = new JSONArray();
        List<Map<String,Object>> userSealList = sealsManageDao.querySealsDetailByRequestid(requestid);
        log.error("userSealList:{}",userSealList.size());
        if(userSealList.size() > 0){
            for(int i=0;i<userSealList.size();i++){
                Map<String,Object> sealMap = userSealList.get(i);
                String sealId = String.valueOf(sealMap.get("ykyyzid"));
                String applyCount = String.valueOf(sealMap.get("yysl"));
                String applyCrossPageSealCount = String.valueOf(sealMap.get("qfzcs"));

                log.error("sealId:{}",sealId);
                log.error("applyCount:{}",applyCount);
                log.error("applyCrossPageSealCount:{}",applyCrossPageSealCount);

                JSONObject usedSealParam = new JSONObject();
                usedSealParam.put("sealId",sealId);
                usedSealParam.put("takeOut","0");
                usedSealParam.put("applyCount",applyCount);
                usedSealParam.put("applyCrossPageSealCount",applyCrossPageSealCount);
                usedSealParamList.add(usedSealParam);
            }
            log.error("usedSealParamList:{}",usedSealParamList.size());

            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);

            bodyJson.put("title",requestName);
            bodyJson.put("applyerUserName",Constants.applyerUserName);
            bodyJson.put("usedSealParamList",usedSealParamList);
            bodyJson.put("option",optionJson);
        }
        log.error("bodyJson:"+bodyJson.toJSONString());

        String token = esb2QunjieTokenUtil.getAccessToken();
        log.error("token:"+token);
        if(StringUtils.isNotBlank(token)){
//            multipartBodyBuilder.addFormDataPart("workflowApplyParam",bodyJson.toJSONString());
//            RequestBody body = multipartBodyBuilder.build();
//            String message= doFormDataPost(bodyJson.toJSONString(),token,body);

            builder.addTextBody("workflowApplyParam", bodyJson.toJSONString(),ContentType.create("multipart/form-data", Charset.forName("UTF-8")));
            String message= doFormDataPost(bodyJson.toJSONString(),token,builder);

            log.error("message:{}",message);
            messageMap = convertBodyDataToMap(message);
        }
        return messageMap;
    }

    public String doPostReqeustByOkHttp(String bodyData,String token,RequestBody body){
        String msg = "";
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();


        try {
            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",status);
                    messageMap.put("applyStatus",applyStatus);
                }else{
                    messageMap.put("status",status);
                    String data =returnData.getString("data") ;
                    log.error("data:{}",data);
                    messageMap.put("data",data);
                    messageMap.put("message",returnData.getString("message"));
                }
            }
        }

        return messageMap;
    }

    public String doFormDataPost(String bodyData,String token,MultipartEntityBuilder builder) {

        String resEntity = "";
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(Constants.qunjieHost+ Constants.applyUrl);
        //传递文件参数以及文本参数
        httpPost.setHeader("charset", "utf-8");
        httpPost.setHeader("Accept", "*/*");
        httpPost.setHeader("Accept-Encoding", "UTF-8");
        httpPost.setHeader("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{
            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;
    }
}
