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.junziqian.common.JzqUtils;
import org.dromara.resource.junziqian.common.bean.sign.JzqSign;
import org.dromara.resource.mapper.SysSignLogMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.*;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

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

@Service
@Slf4j
public class JzqSignServiceImpl {


    @Resource
    public SysSignLogMapper sysSignLogMapper;

    @Resource
    public RemoteFileService remoteFileService;

    @Autowired
    public JzqUtils jzqUtils;

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


    public String  becomeSign(JzqSign sign)
    {

        return jzqUtils.applySign(sign);
    }

    public String bankThreeVerify(String name ,String identityCard,String cardNo){
        return jzqUtils.bankThreeVerify(name ,identityCard,cardNo);
    }

    public String link(String applyNo,String fullName,String identityCard,int identityType){
        return jzqUtils.link(applyNo,fullName,identityCard,identityType);
    }

    public String userValid(String name ,String identityCard){
        return jzqUtils.userValid(name ,identityCard);
    }

    public String ocrIdentity(String file, Integer front) {
        return jzqUtils.ocrIdentity(file,front);
    }

    public String bankFourVerify(String name,String identityCard,String cardNo,String mobilePhone){
        return jzqUtils.bankFourVerify(name,identityCard,cardNo,mobilePhone);
    }

    public String ocrBank(File file){
        return jzqUtils.ocrBank(file);
    }
    public String startH5Face(String orderNo,String name,String identityCard,String backUrl,Integer startFrom){
        String s = jzqUtils.startH5Face(orderNo, name, identityCard, backUrl, startFrom);
        return s;
    }

    public String organizationCreate(String emailOrMobile,String name,Integer organizationType,Integer identificationType,String organizationRegNo,
                                     File organizationRegImg,String legalName,String legalIdentityCard,String legalMobile){
        return jzqUtils.organizationCreate(emailOrMobile, name, organizationType, identificationType, organizationRegNo, organizationRegImg, legalName, legalIdentityCard, legalMobile);
    }

    public String cloudCertiPerInfo(String fullName,String identityCard,File idenFront,File idenReverse){
        return jzqUtils.cloudCertiPerInfo(fullName, identityCard, idenFront, idenReverse);
    }

    public String linkFile(String applyNo){
        return jzqUtils.linkFile(applyNo);
    }

    public String accpet(Map<String,Object> map)throws Exception{
        Object data = map.get("data");
        JSONObject jsonObject = JSONObject.parseObject(data.toString());
        log.info("签约接收回调结果["+jsonObject.toString()+"]");

        String customerOriginationNumber = jsonObject.getString("applyNo");

        String signState = jsonObject.getString("signStatus");

        if(StringUtils.isNotEmpty(customerOriginationNumber)){
            SysSignLog signLog = new SysSignLog();
            signLog.setSignState(signState);
            signLog.setBizId(customerOriginationNumber);
            this.sysSignLogMapper.updateSysSignLog(signLog);
                UserWorkerBiz uwb = new UserWorkerBiz();
                uwb.setNo(customerOriginationNumber);
                if("0".equals(signState)){
                    uwb.setSignStatus(0);
                }else {
                    uwb.setSignStatus(1);
                }
            String s = jzqUtils.linkFile(customerOriginationNumber);
            JSONObject json = JSONObject.parseObject(s);
            String fileUrl= null;
            if (json.getString("success").equals("true")) {
                 fileUrl = json.getString("data");
            }
            signLog.setContractFile(fileUrl);
                fileUrl = upLoadOss(fileUrl);
                uwb.setSignFileUrl(fileUrl);
                this.sysSignLogMapper.updateUserWorkerBiz(uwb);
        }

        return "{\"success\":true}";
    }

    public String accpetSure(Map<String,Object> map)throws Exception{
        Object data = map.get("data");
        JSONObject jsonObject = JSONObject.parseObject(data.toString());
        log.info("签约接收回调结果["+jsonObject.toString()+"]");

        String customerOriginationNumber = jsonObject.getString("applyNo");

        String signState = jsonObject.getString("signStatus");

        log.info("确认单####################"+signState+"!!!!!!!!!!!!!!!!!!!!!!");

        if(StringUtils.isNotEmpty(customerOriginationNumber)){
            SysSignLog signLog = new SysSignLog();
            signLog.setSignState(signState);
            signLog.setBizId(customerOriginationNumber);
            this.sysSignLogMapper.updateSysSignLog(signLog);
            MerTaskEnroll enroll = new MerTaskEnroll();
            enroll.setSignNo(customerOriginationNumber);
            if("0".equals(signState)){
                enroll.setSignStatus(0);
            }else {
                enroll.setSignStatus(1);
            }
            String s = jzqUtils.linkFile(customerOriginationNumber);
            JSONObject json = JSONObject.parseObject(s);
            String fileUrl= null;
            if (json.getString("success").equals("true")) {
                fileUrl = json.getString("data");
            }
            signLog.setContractFile(fileUrl);
            fileUrl = upLoadOss(fileUrl);
            enroll.setTaskConfirmFile(fileUrl);
            this.sysSignLogMapper.updateMerTaskEnrollInfo(enroll);
        }

        return "{\"success\":true}";
    }




    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 "";
    }
}
