package org.dromara.resource.service.impl;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.URLUtil;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.resource.api.RemoteFileService;
import org.dromara.resource.api.domain.RemoteFile;
import org.dromara.resource.domain.*;
import org.dromara.resource.mapper.SysSignLogMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author sunzexing
 * @version 1.0
 * @title DhqSignServiceImpl
 * @description  大鸿签签约
 * @create 2024-05-15 14:53
 */

@Service
@Slf4j
public class DhqSignServiceImpl {


    @Resource
    public SysSignLogMapper sysSignLogMapper;

    @Resource
    public RemoteFileService remoteFileService;

    /***
     * 发起签约
     * @param sign
     * @return
     * @throws Exception
     */


    public String  becomeSign(DhqSign sign) throws Exception
    {
//        String apiUrl = "https://openapi.signzg.com/openAPI/contractSign/v3/becomeSilentSaveSign"; // 替换为实际的API地址

        String apiUrl = "https://openapi.signzg.com/openAPI/contractSign/pro/addContractSign";
        SysSignLog  signLog = new SysSignLog();
        String response = null;
        try{
             response = callThirdPartyApi(apiUrl, sign,signLog);
             log.info("调用大鸿签发起合同返回结果====》"+ response);
        }catch (Exception e){
            signLog.setResultException(e.getMessage());
            response = null;
        }finally {
            this.sysSignLogMapper.insert(signLog);
        }
        return response;
    }


    public static void main(String[] args) throws Exception{
        String apiUrl = "https://openapi.signzg.com/openAPI/contractSign/signTemplateList"; // 替换为实际的API地址


        System.out.println(URLUtil.encode(Base64.encode("https://c.woxin666.com/wxre/2024/08/15/74a87e99d4d5485692c8d9eba169f992.pdf")));



//        String apiUrl = "https://openapi.signzg.com/openAPI/contractSign/pro/addContractSign";

//        Map paraMap = new HashMap();
//
//        paraMap.put("applicationId","2205026100");
//        paraMap.put("businessId","95d6eb9ae14b4b6f8770467a37132c82");
//        paraMap.put("contractName","测试合同");
//        paraMap.put("launchType",1);
//        paraMap.put("launchName","陈总");
//        paraMap.put("launchSubject","15981832653");
//        paraMap.put("launchEnterpriseName","上海欣度网络科技有限公司");
//        paraMap.put("customerOriginationNumber","159818326531231");
//        paraMap.put("contractModelNum","2024081415531723622014701172");
//        paraMap.put("signatureType",0);
//
//        //签署文本控件
//        List<Map> mapList=new ArrayList<>();
//        Map map2 = new HashMap();
//        map2.put("controlNumber","76505d7668304283aa727d40809f20f7");
//        map2.put("writeContent","20248088");
//        Map map1 = new HashMap();
//        map1.put("controlNumber","2bd867b199b4426e986faeb6508fb3d0");
//        map1.put("writeContent","郑州限公司");
//        Map map3 = new HashMap();
//        map3.put("controlNumber","495e5b2ac1614ed9a08375187cd67888");
//        map3.put("writeContent","张");
//
//        mapList.add(map2);
//        mapList.add(map1);
//        mapList.add(map3);
//
//        paraMap.put("inputValues",mapList);
//
//        List<Map<String,String>> data=new ArrayList<>();
//        Map<String,String> map = new HashMap<>();
//        map.put("userName","石杰");//经办人姓名
//        map.put("userPhone","15981832653");//经办人手机号
//        map.put("type","1");//类型 0-个人 1-企业
//        map.put("signMode","3");//签署印章 1用户手绘章 2用户模板章 3企业章  4合同章 5法人章，多个用逗号分隔
//        map.put("silenceSign","1"); //是否需要静默签：0不需要 1需要
//        map.put("enterpriseName","上海欣度网络科技有限公司");//企业名称(类型type为1时必传)
//        map.put("signNumber","e746ad74069443349cabc975e5b8d25a"); //0签署方编号
//
//        Map<String,String> map5 = new HashMap<>();
//        map5.put("userName","孙泽星");//经办人姓名
//        map5.put("userPhone","15981832697");//经办人手机号
//        map5.put("type","0");//类型 0-个人 1-企业
//        map5.put("signMode","1");//签署印章 1用户手绘章 2用户模板章 3企业章  4合同章 5法人章，多个用逗号分隔
//        map5.put("silenceSign","0"); //是否需要静默签：0不需要 1需要
//        map5.put("signNumber","c65ba6bb0b7944beba1f664ec8cc5fd4"); //0签署方编号
//        data.add(map);
//        data.add(map5);
//        String s = JSONObject.toJSONString(data);
//        paraMap.put("signatoryInfos",s);//签署方相关信息
//
//
//
//
//
//        paraMap.clear();
//
////        Map paraMap = new HashMap();
//
//        paraMap.put("applicationId","2205026100");
//        paraMap.put("businessId","95d6eb9ae14b4b6f8770467a37132c82");
//        paraMap.put("isOpen","1");
//
//        CloseableHttpClient httpClient = HttpClients.createDefault();
//        HttpPost httpPost = new HttpPost(apiUrl);
//        ObjectMapper objectMapper = new ObjectMapper();
//        String requestBody = objectMapper.writeValueAsString(paraMap);
//
//        System.out.println(requestBody);
//        StringEntity requestEntity = new StringEntity(requestBody, ContentType.APPLICATION_JSON);
//        httpPost.setEntity(requestEntity);
//
//        CloseableHttpResponse response = httpClient.execute(httpPost);
//        try {
//            HttpEntity entity = response.getEntity();
//            BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
//            StringBuilder responseBuilder = new StringBuilder();
//            String line;
//            while ((line = reader.readLine()) != null) {
//                responseBuilder.append(line);
//            }
//            System.out.println(responseBuilder.toString());
//        } finally {
//            response.close();
//        }

    }


    public static String callThirdPartyApi(String apiUrl, DhqSign becomeSilentSaveSignDto,SysSignLog  signLog ) throws IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(apiUrl);
        signLog.setBizId(becomeSilentSaveSignDto.getCustomerOriginationNumber());


        ObjectMapper objectMapper = new ObjectMapper();
        String requestBody = objectMapper.writeValueAsString(becomeSilentSaveSignDto);
        signLog.setSendBody(requestBody);
        signLog.setHtCode(becomeSilentSaveSignDto.getContractModelNum());

        log.info("请求报文===>"+requestBody);
        StringEntity requestEntity = new StringEntity(requestBody, ContentType.APPLICATION_JSON);
        httpPost.setEntity(requestEntity);

        CloseableHttpResponse response = httpClient.execute(httpPost);
        try {
            HttpEntity entity = response.getEntity();
            BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
            StringBuilder responseBuilder = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                responseBuilder.append(line);
            }
            signLog.setContent(responseBuilder.toString());
            return responseBuilder.toString();

        } finally {
            response.close();
        }
    }


    public void accpet(JSONObject jsonObject)throws Exception{
        log.info("签约接收回调结果["+jsonObject.toString()+"]");
        //客户发起合同时定义的编号
        String customerOriginationNumber = jsonObject.getString("customerOriginationNumber");
        //应用 id
        String businessId = jsonObject.getString("businessId");
        //合同签署编号
        String contractNum = jsonObject.getString("contractNum");
        //0 签署中 1 签署完成 2-拒绝签署 3 解除中 4 解除完成 5 拒绝解除
        //6-已撤回 7 已过期
        String signState = jsonObject.getString("signState");
        //合同文件
        String contractFile = jsonObject.getString("contractFile");
        //合同名称
        String contractName = jsonObject.getString("contractName");

        if(StringUtils.isNotEmpty(customerOriginationNumber)){
            SysSignLog signLog = new SysSignLog();
            signLog.setSignState(signState);
            signLog.setContractFile(contractFile);
            signLog.setAppId(businessId);
            signLog.setBizId(customerOriginationNumber);


            this.sysSignLogMapper.updateSysSignLog(signLog);


            if(customerOriginationNumber.startsWith("DHQUZ")){
                //更新用工协议
                UserWorkerBiz uwb = new UserWorkerBiz();
                uwb.setNo(customerOriginationNumber);
                if("1".equals(signState)){
                    uwb.setSignStatus(1);
                }else if("2".equals(signState)){
                    uwb.setSignStatus(2);
                }
                String fileUrl = upLoadOss(contractFile);
                fileUrl = fileUrl.replaceAll("http://","https://");
                uwb.setSignFileUrl(fileUrl);
                this.sysSignLogMapper.updateUserWorkerBiz(uwb);
            }else if(customerOriginationNumber.startsWith("DHQQRD")){
                //确认单
                MerTaskEnroll enroll = new MerTaskEnroll();
                enroll.setSignNo(customerOriginationNumber);
                if("1".equals(signState)){
                    enroll.setSignStatus(1);
                }else if("2".equals(signState)){
                    enroll.setSignStatus(2);
                }
                String fileUrl = upLoadOss(contractFile);
                fileUrl = fileUrl.replaceAll("http://","https://");
                enroll.setTaskConfirmFile(fileUrl);
                this.sysSignLogMapper.updateMerTaskEnrollInfo(enroll);
            }else if(customerOriginationNumber.startsWith("DHQWT")){
                //运营商委托协议
                UserWorkAuth uwa = new UserWorkAuth();
                uwa.setNo(customerOriginationNumber);
                if("1".equals(signState)){
                    uwa.setSignStatus(1);
                }else if("2".equals(signState)){
                    uwa.setSignStatus(2);
                }
                String fileUrl = upLoadOss(contractFile);
                uwa.setSignFileUrl(fileUrl);
                this.sysSignLogMapper.updateUserWorkerAuth(uwa);
            }


        }
    }

    private String upLoadOss(String contractFile) throws Exception {

       InputStream inputStream =  URLUtil.getStream(new URL(contractFile));
       try{
           if(inputStream != null){
               byte[] arrayBytes = IoUtil.readBytes(inputStream);
                String fileName = IdUtil.getSnowflakeNextIdStr()+".pdf";
                RemoteFile remoteFile =  this.remoteFileService.upload(fileName,fileName,"application/pdf",arrayBytes);
                return remoteFile.getUrl();
           }
       }finally {
           if(inputStream != null){
               inputStream.close();
           }
       }
        return "";
    }
}
