package org.dromara.mp.service.impl;

import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.dromara.common.core.enums.SignType;
import org.dromara.common.core.service.BaseService;
import org.dromara.common.core.utils.DateUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.PageQuery;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.satoken.utils.MpLoginHelper;
import org.dromara.mp.domain.MerTaskEnroll;
import org.dromara.mp.domain.MerTaskSure;
import org.dromara.mp.domain.UserWorkerBiz;
import org.dromara.mp.domain.bo.UserWorkCheckinBo;
import org.dromara.mp.domain.vo.*;
import org.dromara.mp.mapper.MerTaskEnrollMapper;
import org.dromara.mp.mapper.MyTaskMapper;
import org.dromara.mp.mapper.UserWorkCheckinMapper;
import org.dromara.mp.service.IMyTaskService;
import org.dromara.mp.service.IUserWorkCheckinService;
import org.dromara.mp.service.IUserWorkerService;
import org.dromara.resource.api.RemoteDhqService;
import org.dromara.resource.api.RemoteJzqService;
import org.dromara.resource.api.domain.RemoteDhq;
import org.dromara.resource.api.domain.RemoteJzq;
import org.dromara.resource.api.domain.SignatoryReq;
import org.dromara.system.api.RemoteConfigService;
import org.dromara.system.api.domain.RemoteSysUnitDomainVo;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

/**
 * @author sunzexing
 * @version 1.0
 * @title MyTaskServiceImpl
 * @description
 * @create 2024-05-08 18:44
 */
@Service
@Slf4j
public class MyTaskServiceImpl extends BaseService implements IMyTaskService {


    @Resource
    public MyTaskMapper myTaskMapper;

    @Resource
    public MerTaskEnrollMapper merTaskEnrollMapper;

    @Resource
    public UserWorkCheckinMapper checkinMapper;

    @Resource
    public IUserWorkCheckinService userWorkerCheckinService;


    @DubboReference
    public  RemoteDhqService remoteDhqService;

    @DubboReference
    public RemoteJzqService remoteJzqService;



    @DubboReference
    private RemoteConfigService remoteConfigService;


    /****
     * 确认单
     * @param id
     * @param domain
     * @return
     * @throws Exception
     */
    @Override
    public String   signSurePro(Long id,String domain)throws Exception{

        RemoteSysUnitDomainVo site = remoteConfigService.queryByDomainName(domain);

        if(site == null || StringUtils.isEmpty(site.getSignConfig())){
            throw new Exception("未找到该域名的签约配置信息");
        }

        JSONObject signConfig = JSONObject.parseObject(site.getSignConfig());
        JSONObject workerSignConfig = signConfig.getJSONObject("user_worker_conf");
        MerTaskSure uwb = this.myTaskMapper.selectTaskSure(id);
        if(uwb == null){
            this.invalidationParamsException("参数无效");
        }

        if(uwb.getSignStatus() == null && StringUtils.isNotEmpty(uwb.getSignUrl())){
            return uwb.getSignUrl();
        }

        String originaNumber = "DHQQRD"+ IdUtil.getSnowflakeNextIdStr();
        RemoteDhq   dhq = new RemoteDhq();
        dhq.setLaunchType("1");
        dhq.setContractName("用工确认单");//合同名称
        dhq.setContractModelNum(workerSignConfig.getString("tempCode"));
        dhq.setLaunchType("1"); //发起类型 0-个人发起 1-企业发起
        dhq.setLaunchSubject(uwb.getConPhone());//发起用户手机号
        dhq.setLaunchName(uwb.getConName());
        dhq.setLaunchEnterpriseName(uwb.getSysName());//发起企业名称(launchType为1企业发起合同时必传)
//        dhq.setSignEnterpriseName(uwb.getSysName());
        dhq.setCustomerOriginationNumber(originaNumber);//客户发起时定义的编号
//        dhq.setInputValues(uwb.getProNo()+","+originaNumber+","+uwb.getSysName()+","+uwb.getCost()+","+uwb.getCreateTime()+","
//            +uwb.getWorkName()+","+uwb.getCardId()+","+uwb.getPhone()+","+uwb.getProContent());//输入内容设置模板签署位置时要签署的内容    多个用逗号分隔


        List<Map> mapList=new ArrayList<>();
        Map map2 = new HashMap();
        map2.put("controlNumber",workerSignConfig.getString("pro_controlNumber"));
        map2.put("writeContent",uwb.getProNo());
        mapList.add(map2);
        Map map1 = new HashMap();
        map1.put("controlNumber",workerSignConfig.getString("xy_controlNumber"));
        map1.put("writeContent",originaNumber);
        mapList.add(map1);
        Map map3 = new HashMap();
        map3.put("controlNumber",workerSignConfig.getString("fbf_controlNumber"));
        map3.put("writeContent",uwb.getSysName());
        mapList.add(map3);
        Map map4 = new HashMap();
        map4.put("controlNumber",workerSignConfig.getString("je_controlNumber"));
        map4.put("writeContent",uwb.getCost());
        mapList.add(map4);
        Map map51 = new HashMap();
        map51.put("controlNumber",workerSignConfig.getString("time_controlNumber"));
        map51.put("writeContent",uwb.getCreateTime());
        mapList.add(map51);
        Map map6 = new HashMap();
        map6.put("controlNumber",workerSignConfig.getString("user_controlNumber"));
        map6.put("writeContent",uwb.getWorkName());
        mapList.add(map6);
        Map map7 = new HashMap();
        map7.put("controlNumber",workerSignConfig.getString("card_controlNumber"));
        map7.put("writeContent",uwb.getCardId());
        mapList.add(map7);
        Map map8 = new HashMap();
        map8.put("controlNumber",workerSignConfig.getString("phone_controlNumber"));
        map8.put("writeContent",uwb.getPhone());
        mapList.add(map8);
//        int length = uwb.getProContent().replace("\t","").length();
//        int size = (length +38 -1) / 38 ;
//        for(int i = 0; i < size ; i++){
//            if(i > 3){
//                break;
//            }
//            Map map9 = new HashMap();
//            map9.put("controlNumber",workerSignConfig.getString("txt1"+i+"_controlNumber"));
//            map9.put("writeContent",uwb.getProContent().substring(i*38,i*38+38 > length?length -1:i*38+38));
//            mapList.add(map9);
//        }

//        if(size < 4){
//            for( int i = size  ; i < 4; i++){
//                Map map9 = new HashMap();
//                map9.put("controlNumber",workerSignConfig.getString("txt1"+i+"_controlNumber"));
//                map9.put("writeContent","");
//                mapList.add(map9);
//            }
//
//        }


        dhq.setInputValues(mapList);


        List<Map<String,String>> data=new ArrayList<>();
        Map<String,String> map = new HashMap<>();
        map.put("userName",uwb.getConName());//经办人姓名
        map.put("userPhone",uwb.getConPhone());//经办人手机号
        map.put("type","1");//类型 0-个人 1-企业
        map.put("signMode","3");//签署印章 1用户手绘章 2用户模板章 3企业章  4合同章 5法人章，多个用逗号分隔
        map.put("silenceSign","1"); //是否需要静默签：0不需要 1需要
        map.put("enterpriseName",uwb.getSysName());//企业名称(类型type为1时必传)
        map.put("signNumber",workerSignConfig.getString("signNumber1")); //0签署方编号

        Map<String,String> map5 = new HashMap<>();
        map5.put("userName",uwb.getWorkName());//经办人姓名
        map5.put("userPhone",uwb.getPhone());//经办人手机号
        map5.put("type","0");//类型 0-个人 1-企业
        map5.put("signMode","1");//签署印章 1用户手绘章 2用户模板章 3企业章  4合同章 5法人章，多个用逗号分隔
        map5.put("silenceSign","0"); //是否需要静默签：0不需要 1需要
        map5.put("signNumber",workerSignConfig.getString("signNumber2")); //0签署方编号
        data.add(map);
        data.add(map5);
        String s = JSONObject.toJSONString(data);



        String result = this.remoteDhqService.becomeSign(dhq,domain, SignType.USER_WORKER_CONFIRMATION);
        if(StringUtils.isEmpty(result)){
            this.invalidationParamsException("获取签约连接失败");
        }
        String signWebUrl = null;
        String contractNum = null;
        JSONObject  resultObj = JSONObject.parseObject(result);
        String code = resultObj.getString("code");
        if(StringUtils.isNotEmpty(code) && code.equals("200")){
            JSONObject jno = resultObj.getJSONObject("result");
            if(jno != null){
                JSONArray signWebUrls = jno.getJSONArray("signUrls");
                signWebUrl =signWebUrls.getJSONObject(0).getString("signUserUrl");
                contractNum = jno.getString("contractNum");
            }
        }
        if(StringUtils.isEmpty(signWebUrl)){
            this.invalidationParamsException("获取签约连接失败");
        }else{
            MerTaskSure  uwBiz = new MerTaskSure();
            uwBiz.setId(id);
            uwBiz.setSignUrl(signWebUrl);
            uwBiz.setSignNo(originaNumber);
            this.myTaskMapper.updateTaskSure(uwBiz);
        }
        return signWebUrl;
    }

    /****
     * 确认单
     * @param id
     * @param domain
     * @return
     * @throws Exception
     */
    @Override
    public String   signSureProJzq(Long id,String domain)throws Exception{

        RemoteSysUnitDomainVo site = remoteConfigService.queryByDomainName(domain);

        if(site == null || StringUtils.isEmpty(site.getSignConfig())){
            throw new Exception("未找到该域名的签约配置信息");
        }

        JSONObject signConfig = JSONObject.parseObject(site.getSignConfig());
        JSONObject workerSignConfig = signConfig.getJSONObject("user_worker_conf");
        MerTaskSure uwb = this.myTaskMapper.selectTaskSure(id);
        if(uwb == null){
            this.invalidationParamsException("参数无效");
        }

        if(uwb.getSignStatus() == null && StringUtils.isNotEmpty(uwb.getSignUrl())){
            return uwb.getSignUrl();
        }




        RemoteJzq remoteJzq = new RemoteJzq();
        remoteJzq.setContractName("用工确认单"); //合同名称
        remoteJzq.setTemplateNo(workerSignConfig.getString("tempCode"));
        remoteJzq.setServerCa(1);
        remoteJzq.setDealType(5);
        remoteJzq.setFileType(4);
        String originaNumber = "4FDCA706A6D042D5A3FFF417A7C006A6";
        remoteJzq.setTemplateNo(originaNumber);
        remoteJzq.setNotifyUrl("http://116.255.147.51/prod-api/resource/sign/acceptSure");
        Map<String, String> mapList = new HashMap<>();
        mapList.put("corporatename", "薪资社");
        String  jsonString = JSONObject.toJSONString(mapList);
        remoteJzq.setTemplateParams(jsonString);





        List<SignatoryReq>  signatoryReqs = new ArrayList<>();

        SignatoryReq signatoriesReq = new SignatoryReq();
        signatoriesReq.setFullName(uwb.getSysName());


        signatoriesReq.setIdentityType(11);
        signatoriesReq.setIdentityCard(uwb.getNsrSbh());
        signatoriesReq.setEmail(uwb.getConEmail());
        signatoriesReq.setServerCaAuto(1);
        signatoriesReq.setChapteJson("[{\"page\":4,\"chaptes\":[{\"offsetX\":0.121,\"offsetY\":0.3941}]}]");//坐标（X Y）定位签字位置
        signatoriesReq.setSignLevel(0);
        signatoriesReq.setNoNeedVerify(1);
        signatoryReqs.add(signatoriesReq);


        signatoriesReq = new SignatoryReq();
        signatoriesReq.setFullName(uwb.getWorkName());
        signatoriesReq.setIdentityType(1);
        signatoriesReq.setIdentityCard(uwb.getCardId());
        signatoriesReq.setMobile(uwb.getPhone());
        signatoriesReq.setServerCaAuto(0);
        signatoriesReq.setChapteJson("[{\"page\":0,\"chaptes\":[{\"offsetX\":0.3047,\"offsetY\":0.2677}]},{\"page\":4,\"chaptes\":[{\"offsetX\":0.2378,\"offsetY\":0.1681}]}]");//坐标（X Y）定位签字位置
        signatoriesReq.setNoNeedVerify(1); //取消签约前短信校验
        signatoriesReq.setServerCaAuto(0);//是否使用自动签署完成，0或null不使用，1自动(当且只当合同处理方式为部份自动或收集批量签时有效)
        signatoriesReq.setSignLevel(1);//签字类型，标准图形章或公章:0标准图形章,1公章或手写,2公章手写或手写,3个人方形标准章（用户类型是个人且姓名2-4个字符生效，其他情况默认使用系统标准图形章）


        signatoryReqs.add(signatoriesReq);


        remoteJzq.setSignatories(signatoryReqs);




        String result = this.remoteJzqService.becomeSign(remoteJzq,domain, SignType.USER_WORKER_PROTOCOL);
        JSONObject jsonObject = JSONObject.parseObject(result);

        if(jsonObject.getString("success").equals("false")){

            this.invalidationParamsException(jsonObject.getString("msg"));
        }

        String code = jsonObject.getString("data");

        String data = this.remoteJzqService.link(code,uwb.getWorkName(),uwb.getCardId(),1);

        JSONObject resultObj = JSONObject.parseObject(data);

        if (resultObj.getString("success").equals("false")){
            this.invalidationParamsException("获取签约连接失败");
        }

        String signWebUrl = resultObj.getString("data");

        MerTaskSure  uwBiz = new MerTaskSure();
        uwBiz.setId(id);
        uwBiz.setSignUrl(signWebUrl);
        uwBiz.setSignNo(code);
        this.myTaskMapper.updateTaskSure(uwBiz);

        return signWebUrl;
    }

//
//    public static void main(String[] args) {
//        String result = "{\"success\":true,\"message\":\"操作成功！\",\"code\":200,\"result\":{\"businessId\":\"95d6eb9ae14b4b6f8770467a37132c82\",\"contractNum\":\"2024081416141723623293870089\",\"applicationId\":\"2205026100\",\"signUrls\":[{\"signUserPhone\":\"15981832697\",\"signUserUrl\":\"https://openapi.signzg.com/copilot/index.html#/sign-info?dXNlcklkPTIzMjI1JnNpZ25JZD0xMzk1NQ==\"}]},\"timestamp\":1723623294932}";
//        JSONObject  resultObj = JSONObject.parseObject(result);
//        String code = resultObj.getString("code");
//        String signWebUrl ="中信银行(03020000)".replaceAll("[\\d()]","");
//        String contractNum ="";
//        if(StringUtils.isNotEmpty(code) && code.equals("200")){
//            JSONObject jno = resultObj.getJSONObject("result");
//            if(jno != null){
//                JSONArray signWebUrls = jno.getJSONArray("signUrls");
//                signWebUrl =signWebUrls.getJSONObject(0).getString("signUserUrl");
//                contractNum = jno.getString("contractNum");
//            }
//        }
//
//    }

    /****
     * 签约
     * @param id
     * @param domain
     * @return
     * @throws Exception
     */
    @Override
    public String   signPro(Long id,String domain)throws Exception{

        RemoteSysUnitDomainVo site = remoteConfigService.queryByDomainName(domain);

        if(site == null || StringUtils.isEmpty(site.getSignConfig())){
            throw new Exception("未找到该域名的签约配置信息");
        }

        JSONObject signConfig = JSONObject.parseObject(site.getSignConfig());
        JSONObject workerSignConfig = signConfig.getJSONObject("user_worker_pro");

        UserWorkerBiz uwb = this.myTaskMapper.selectHtInfoByUwbId(id);
        if(uwb == null){
            this.invalidationParamsException("参数无效");
        }

        if(StringUtils.isNotEmpty(uwb.getSignUrl())){
            return uwb.getSignUrl();
        }

        String originaNumber = "DHQUZ"+ IdUtil.getSnowflakeNextIdStr();
        RemoteDhq   dhq = new RemoteDhq();
        dhq.setApplicationId(signConfig.getString("appId"));
        dhq.setBusinessId(signConfig.getString("businessId"));
        dhq.setContractName("用工签约");//合同名称
        dhq.setLaunchType("1"); //发起类型 0-个人发起 1-企业发起
        dhq.setLaunchSubject(uwb.getConPhone());//发起用户手机号
        dhq.setContractModelNum(workerSignConfig.getString("tempCode"));
        dhq.setLaunchName(uwb.getConName());
        dhq.setLaunchEnterpriseName(uwb.getGsmc());//发起企业名称(launchType为1企业发起合同时必传)
//        dhq.setSignEnterpriseName(uwb.getGsmc());
        dhq.setCustomerOriginationNumber(originaNumber);//客户发起时定义的编号
//        dhq.setInputValues(uwb.getGsmc()+","+uwb.getConName()+","+uwb.getCardId()+","+uwb.getName()+","+uwb.getGsmc()+","+uwb.getGsmc()+","+uwb.getGsmc()+","+uwb.getGsmc()+","+ DateUtils.getDate());//输入内容设置模板签署位置时要签署的内容    多个用逗号分隔




        List<Map> mapList=new ArrayList<>();
        Map map2 = new HashMap();
        map2.put("controlNumber",workerSignConfig.getString("jf_controlNumber"));
        map2.put("writeContent",uwb.getGsmc());
        mapList.add(map2);
        Map map1 = new HashMap();
        map1.put("controlNumber",workerSignConfig.getString("jfuser_controlNumber"));
        map1.put("writeContent",uwb.getConName());
        mapList.add(map1);
        Map map3 = new HashMap();
        map3.put("controlNumber",workerSignConfig.getString("yf_controlNumber"));
        map3.put("writeContent",uwb.getName());
        mapList.add(map3);
        Map map4 = new HashMap();
        map4.put("controlNumber",workerSignConfig.getString("yfuser_controlNumber"));
        map4.put("writeContent",uwb.getCardId());
        mapList.add(map4);
        Map map51 = new HashMap();
        map51.put("controlNumber",workerSignConfig.getString("sys0_controlNumber"));
        map51.put("writeContent",uwb.getGsmc());
        mapList.add(map51);
        Map map6 = new HashMap();
        map6.put("controlNumber",workerSignConfig.getString("sys1_controlNumber"));
        map6.put("writeContent",uwb.getGsmc());
        mapList.add(map6);
        Map map7 = new HashMap();
        map7.put("controlNumber",workerSignConfig.getString("sys2_controlNumber"));
        map7.put("writeContent",uwb.getGsmc());
        mapList.add(map7);
        Map map8 = new HashMap();
        map8.put("controlNumber",workerSignConfig.getString("sys3_controlNumber"));
        map8.put("writeContent",uwb.getGsmc());
        mapList.add(map8);
        Map map9 = new HashMap();
        map9.put("controlNumber",workerSignConfig.getString("time_controlNumber"));
        map9.put("writeContent",DateUtils.getDate());
        mapList.add(map9);
        dhq.setInputValues(mapList);

        List<Map<String,String>> data=new ArrayList<>();
        Map<String,String> map = new HashMap<>();
        map.put("userName",uwb.getConName());//经办人姓名
        map.put("userPhone",uwb.getConPhone());//经办人手机号
        map.put("type","1");//类型 0-个人 1-企业
        map.put("signMode","3");//签署印章 1用户手绘章 2用户模板章 3企业章  4合同章 5法人章，多个用逗号分隔
        map.put("silenceSign","1"); //是否需要静默签：0不需要 1需要
        map.put("enterpriseName",uwb.getGsmc());//企业名称(类型type为1时必传)
        map.put("signNumber",workerSignConfig.getString("signNumber1")); //0签署方编号

        Map<String,String> map5 = new HashMap<>();
        map5.put("userName",uwb.getName());//经办人姓名
        map5.put("userPhone",uwb.getVPhone());//经办人手机号
        map5.put("type","0");//类型 0-个人 1-企业
        map5.put("signMode","1");//签署印章 1用户手绘章 2用户模板章 3企业章  4合同章 5法人章，多个用逗号分隔
        map5.put("silenceSign","0"); //是否需要静默签：0不需要 1需要
        map5.put("signNumber",workerSignConfig.getString("signNumber2")); //0签署方编号
        data.add(map);
        data.add(map5);
        String s = JSONObject.toJSONString(data);
        dhq.setSignatoryInfos(s);//签署方相关信息



//        List<Map<String,String>> data=new ArrayList<>();
//        Map<String,String> map = new HashMap<>();
//        map.put("userName",uwb.getName());//经办人姓名
//        map.put("userPhone",uwb.getVPhone());//经办人手机号
//        map.put("type","0");//类型 0-个人 1-企业
//        map.put("signMode","1");//签署印章 1用户手绘章 2用户模板章 3企业章  4合同章 5法人章，多个用逗号分隔
//        // map.put("type","1");//类型 0-个人 1-企业
//        // map.put("signMode","3");//签署印章 1用户手绘章 2用户模板章 3企业章  4合同章 5法人章，多个用逗号分隔
//        // map.put("enterpriseName","贵州省七进制科技有限公司");//企业名称(类型type为1时必传)
//        data.add(map);
//        String s = JSONObject.toJSONString(data);
//        dhq.setSignatoryInfos(s);//签署方相关信息


        String result = this.remoteDhqService.becomeSign(dhq,domain, SignType.USER_WORKER_PROTOCOL);
        if(StringUtils.isEmpty(result)){
            this.invalidationParamsException("获取签约连接失败");
        }
        String signWebUrl = null;
        String contractNum = null;
            JSONObject  resultObj = JSONObject.parseObject(result);
        String code = resultObj.getString("code");
        if(StringUtils.isNotEmpty(code) && code.equals("200")){
            JSONObject jno = resultObj.getJSONObject("result");
            if(jno != null){
                JSONArray signWebUrls = jno.getJSONArray("signUrls");
                signWebUrl =signWebUrls.getJSONObject(0).getString("signUserUrl");
                contractNum = jno.getString("contractNum");
            }


        }
        if(StringUtils.isEmpty(signWebUrl)){
            this.invalidationParamsException("获取签约连接失败");
        }else{
            UserWorkerBiz  uwBiz = new UserWorkerBiz();
            uwBiz.setId(id);
            uwBiz.setSignUrl(signWebUrl);
            uwBiz.setHtCode(originaNumber);
            this.myTaskMapper.updateUserWorkerHtInfoByBizId(uwBiz);
        }
        return signWebUrl;
    }

    /****
     * 签约
     * @param id
     * @param domain
     * @return
     * @throws Exception
     */
    @Override
    public String   signProJzq(Long id,String domain)throws Exception{

        RemoteSysUnitDomainVo site = remoteConfigService.queryByDomainName(domain);

        if(site == null || StringUtils.isEmpty(site.getSignConfig())){
            throw new Exception("未找到该域名的签约配置信息");
        }

        JSONObject signConfig = JSONObject.parseObject(site.getSignConfig());
        JSONObject  workerSignConfig = signConfig.getJSONObject("user_worker_pro");


        log.info(id+"!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");

        UserWorkerBiz uwb = this.myTaskMapper.selectHtInfoByUwbId(id);

        if(uwb == null){
            this.invalidationParamsException("参数无效");
        }

        if(StringUtils.isNotEmpty(uwb.getSignUrl())){
            return uwb.getSignUrl();
        }

        if(ObjectUtils.isEmpty(uwb.getIsCA()) || uwb.getIsCA()==0){
            String name = uwb.getName();
            String identityCard = uwb.getCardId();
            String cardPositive = uwb.getCardPositive();
            String cardBack = uwb.getCardBack();
            // 保存文件的目录（使用临时目录）
            String saveDir = "/www/wwwroot";
            // 保存的文件名
            String fileName = "downloaded_image.jpeg";
            String fileName1 = "downloaded_image1.jpeg";
            File file = createFileFromURL(cardPositive, saveDir, fileName);
            File file1 = createFileFromURL(cardBack, saveDir, fileName1);


            String s = remoteJzqService.cloudCertiPerInfo(name, identityCard, file, file1);
            JSONObject parse = JSONObject.parseObject(s);
            if (parse.getString("success").equals("false")){
                throw new Exception(parse.getString("msg"));
            }

            this.myTaskMapper.updateCAStatus(name);
        }



        RemoteJzq remoteJzq = new RemoteJzq();
        remoteJzq.setContractName("用工签约"); //合同名称
        remoteJzq.setTemplateNo(workerSignConfig.getString("tempCode"));
        remoteJzq.setServerCa(1);
        remoteJzq.setDealType(5);
        remoteJzq.setFileType(4);
        String originaNumber = "3B1EF1A9BD8B47E7A9E23BBE16408658";
        remoteJzq.setTemplateNo(originaNumber);
        remoteJzq.setNotifyUrl("http://116.255.147.51/prod-api/resource/sign/accept");
        Map<String, String> mapList = new HashMap<>();
        mapList.put("corporatename", "薪资社");
        String  jsonString = JSONObject.toJSONString(mapList);
        remoteJzq.setTemplateParams(jsonString);





        List<SignatoryReq>  signatoryReqs = new ArrayList<>();

        SignatoryReq signatoriesReq = new SignatoryReq();
        signatoriesReq.setFullName(uwb.getGsmc());
        signatoriesReq.setIdentityType(11);
        signatoriesReq.setIdentityCard(uwb.getNsrSbh());
        signatoriesReq.setEmail(uwb.getConEmail());
        signatoriesReq.setServerCaAuto(1);
        signatoriesReq.setChapteJson("[{\"page\":4,\"chaptes\":[{\"offsetX\":0.121,\"offsetY\":0.3941}]}]");//坐标（X Y）定位签字位置
        signatoriesReq.setSignLevel(0);
        signatoriesReq.setNoNeedVerify(1);
        signatoryReqs.add(signatoriesReq);


        signatoriesReq = new SignatoryReq();
        signatoriesReq.setFullName(uwb.getName());
        signatoriesReq.setIdentityType(1);
        signatoriesReq.setIdentityCard(uwb.getCardId());
        signatoriesReq.setMobile(uwb.getVPhone());
        signatoriesReq.setServerCaAuto(0);
        signatoriesReq.setChapteJson("[{\"page\":0,\"chaptes\":[{\"offsetX\":0.3047,\"offsetY\":0.2677}]},{\"page\":4,\"chaptes\":[{\"offsetX\":0.2378,\"offsetY\":0.1681}]}]");//坐标（X Y）定位签字位置
        signatoriesReq.setNoNeedVerify(1); //取消签约前短信校验
        signatoriesReq.setServerCaAuto(0);//是否使用自动签署完成，0或null不使用，1自动(当且只当合同处理方式为部份自动或收集批量签时有效)
        signatoriesReq.setSignLevel(1);//签字类型，标准图形章或公章:0标准图形章,1公章或手写,2公章手写或手写,3个人方形标准章（用户类型是个人且姓名2-4个字符生效，其他情况默认使用系统标准图形章）


        signatoryReqs.add(signatoriesReq);


        remoteJzq.setSignatories(signatoryReqs);


        String result = this.remoteJzqService.becomeSign(remoteJzq,domain, SignType.USER_WORKER_PROTOCOL);
        JSONObject jsonObject = JSONObject.parseObject(result);

        if(jsonObject.getString("success").equals("false")){

            this.invalidationParamsException(jsonObject.getString("msg"));
        }

        String code = jsonObject.getString("data");

        String data = this.remoteJzqService.link(code,uwb.getName(),uwb.getCardId(),1);

        JSONObject resultObj = JSONObject.parseObject(data);

        if (resultObj.getString("success").equals("false")){
            this.invalidationParamsException("获取签约连接失败");
        }

        String signWebUrl = resultObj.getString("data");

        UserWorkerBiz  uwBiz = new UserWorkerBiz();
        uwBiz.setId(id);
        uwBiz.setSignUrl(signWebUrl);
        uwBiz.setHtCode(code);
        this.myTaskMapper.updateUserWorkerHtInfoByBizId(uwBiz);

        return signWebUrl;
    }


    public static File createFileFromURL(String fileUrl, String saveDir, String fileName) throws Exception {
        // 确保保存目录存在
        File savePath = new File(saveDir);
        if (!savePath.exists()) {
            savePath.mkdirs();
        }

        // 创建目标文件
        File file = new File(saveDir, fileName);

        // 从URL下载文件并保存到本地
        try (InputStream inputStream = new URL(fileUrl).openStream();
             FileOutputStream outputStream = new FileOutputStream(file)) {
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        }

        return file;
    }


    @Override
    public TableDataInfo<MyTaskVo> selTastList(String name, PageQuery pageQuery) {
        Long workId = MpLoginHelper.getUserId();
        return TableDataInfo.build(this.myTaskMapper.selTastList(name,workId,pageQuery.build()));
    }

    @Override
    public TableDataInfo<MyTaskVo> selMyTastList(String name, PageQuery pageQuery) {
        Long workId = MpLoginHelper.getUserId();
        return TableDataInfo.build(this.myTaskMapper.selectMyTaskList(name,workId,pageQuery.build()));
    }

    @Override
    public TaskVo selTaskListDetail(Long id) {
        if(id == null){
            this.invalidationParamsException("任务ID不能为空");
        }

        TaskVo vo = this.myTaskMapper.selTaskListDetail(id);
        vo.setMerIsAuth(1);
        vo.setVerifyStatus(0);
        return vo;
    }


    @Override
    public Boolean acceptTask(Long id,String no){
        if(id == null){
            this.invalidationParamsException("任务ID不能为空");
        }

        if(StringUtils.isEmpty(no)){
            this.invalidationParamsException("任务编码不能为空");
        }

        MerTaskEnroll enroll = new MerTaskEnroll();
        enroll.setTaskId(id);
        enroll.setTaskNo(no);
        enroll.setCreateTime(new Date());
        enroll.setCreateBy(MpLoginHelper.getUserId());
        enroll.setVerifyStatus(1L);
        enroll.setWorkId(MpLoginHelper.getUserId());
        enroll.setNo("ST"+StringUtils.randmNumber(12));
        this.getAddEnroll(enroll);
        return true;
    }

    @Override
    public List<MyTaskVo> selMyCheckPro() {
        return this.myTaskMapper.selMyCheckPro(MpLoginHelper.getUserId());
    }

    @Override
    public TaskVo selMyTaskDetail(Long id) {
        if(id == null){
            this.invalidationParamsException("任务ID不能为空");
        }
        Long workId = MpLoginHelper.getUserId();
        TaskVo  taskVo = myTaskMapper.selMyTaskDetail(id,workId);
        UserWorkCheckinBo bo = new UserWorkCheckinBo();
        bo.setUserWorkId(workId);
        bo.setProId(taskVo.getTaskId());
        List<UserWorkCheckinVo>  checkInList = this.userWorkerCheckinService.queryList(bo);
        taskVo.setCheckInVolist(checkInList);
        return taskVo;

    }

    @Override
    public int updOverReport(MerTaskEnroll enroll) {

        if(enroll.getId() == null){
            this.invalidationParamsException("ID不能为空");
        }
        if(StringUtils.isEmpty(enroll.getTaskDesc())){
            this.invalidationParamsException("交付内容不能为空");
        }

        if(StringUtils.isEmpty(enroll.getTaskPic())){
            this.invalidationParamsException("交付图片不能为空");
        }
        enroll.setUpdateBy(MpLoginHelper.getUserId());
        enroll.setUpdateTime(new Date());
        enroll.setTaskStatus(1);
        return this.merTaskEnrollMapper.updateById(enroll);
    }

    @Override
    public MerTaskEnrollVo selOverReport(Long id) {
        if(id == null){
            this.invalidationParamsException("ID不能为空");
        }
        MerTaskEnrollVo  mtev = this.merTaskEnrollMapper.selectVoById(id);

        MerTaskEnrollVo result = new MerTaskEnrollVo();
        if(mtev != null){
            result.setId(mtev.getId());
            result.setTaskDesc(mtev.getTaskDesc());
            result.setTaskPic(mtev.getTaskPic());
        }
        return result;
    }

    @Override
    public TableDataInfo<UserWorkerBus> selMyHtList(String name, PageQuery pageQuery) {
        Long workId = MpLoginHelper.getUserId();
        return TableDataInfo.build(this.myTaskMapper.selHtListByWorkId(workId,pageQuery.build()));
    }


    @Override
    public TableDataInfo<MerTaskEnrollVo> selProSureDoc(String name, PageQuery pageQuery) {
        Long workId = MpLoginHelper.getUserId();
        return TableDataInfo.build(this.myTaskMapper.selProSureDoc(workId,pageQuery.build()));
    }


    private void getAddEnroll(MerTaskEnroll enroll) {
        try{
            this.merTaskEnrollMapper.insert(enroll);
        }catch (DuplicateKeyException e){
            enroll.setNo("ST"+StringUtils.randmNumber(12));
            this.getAddEnroll(enroll);
        }
    }


}
