package com.jeeplus.finance.signatureDaily.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jeeplus.common.TokenProvider;
import com.jeeplus.core.query.QueryWrapperGenerator;
import com.jeeplus.finance.contractRegistration.mapper.ContractInfoMapper;
import com.jeeplus.finance.invoice.util.SignaturePostUtil;
import com.jeeplus.finance.projectRecords.mapper.CwProjectRecordsMapper;
import com.jeeplus.finance.projectRecords.service.dto.CwProjectRecordsDTO;
import com.jeeplus.finance.projectReport.domain.Action;
import com.jeeplus.finance.projectReport.domain.Location;
import com.jeeplus.finance.projectReport.domain.SignatorieInfo;
import com.jeeplus.finance.projectReport.domain.SignatureContract;
import com.jeeplus.finance.projectReport.mapper.CwProjectReportMapper;
import com.jeeplus.finance.signatureDaily.domain.SignatureProjectReportRelation;
import com.jeeplus.finance.signatureDaily.domain.SignatureProjectReportRelevanceNumber;
import com.jeeplus.finance.signatureDaily.mapper.SignatureProjectReportMapper;
import com.jeeplus.finance.signatureDaily.mapper.SignatureProjectReportRelevanceNumberMapper;
import com.jeeplus.finance.signatureDaily.service.dto.SignatureProjectReportRelationDTO;
import com.jeeplus.finance.utils.Global;
import com.jeeplus.flowable.feign.IFlowableApi;
import com.jeeplus.sys.domain.WorkAttachmentInfo;
import com.jeeplus.sys.feign.IUserApi;
import com.jeeplus.sys.feign.IWorkAttachmentApi;
import com.jeeplus.sys.service.dto.UserDTO;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.File;
import java.util.*;

@Service
@Transactional
public class SignatureProjectReportService {

    private static final byte[] SYN_BYTE = new byte[0];
    private static final String HTTPTOP = Global.getConfig("signature_http_top");

    /**
     * 公司圆章-横
     */
    private static final String COMPANYROUNDSEALID = Global.getConfig("company_round_seal_finance_id");
    //日常签章申请流程id
    private static final String SIGNATUREREPORTCAREGORYID = Global.getConfig("signature_report_caregory_id");

    @Resource
    private SignatureProjectReportMapper signatureProjectReportMapper;

    @Resource
    private SignatureProjectReportRelevanceNumberMapper relevanceNumberMapper;

    @Resource
    private CwProjectRecordsMapper cwProjectRecordsMapper;

    @Resource
    private ContractInfoMapper mapper;

    @Resource
    private IFlowableApi flowTaskService;


    @Resource
    private CwProjectReportMapper reportMapper;

    /**
     * 列表查询
     * @param page
     * @param dto
     * @return
     * @throws Exception
     */
    public IPage<SignatureProjectReportRelationDTO> list(Page<SignatureProjectReportRelationDTO> page, SignatureProjectReportRelationDTO dto) throws Exception {
        QueryWrapper<SignatureProjectReportRelationDTO> queryWrapper = QueryWrapperGenerator.buildQueryCondition(dto, SignatureProjectReportRelationDTO.class);
        /**
         * a表是reimbursementInfo
         * b表是reimbursementDetailInfo
         * c表是sysUser
         */
        queryWrapper.eq("a.del_flag", 0);

        // 创建时间
        if (dto.getDates() != null) {
            queryWrapper.between("a.create_time", dto.getDates()[0], dto.getDates()[1]);
        }
        // 创建人
        if (StringUtils.isNotEmpty(dto.getCreateById())) {
            queryWrapper.eq("a.create_by_id",dto.getCreateById()).like("c.name",dto.getCreateById());
        }

        // 状态
        if (StringUtils.isNotEmpty(dto.getStatus())) {
            queryWrapper.eq("a.status", dto.getStatus());
        }
        // 部门
        if (StringUtils.isNotEmpty(dto.getOfficeId())) {
            queryWrapper.eq("so.id", dto.getOfficeId());
        }

        // 签章类型
        if (StringUtils.isNotBlank(dto.getSignatureType())) {
            queryWrapper.eq("a.signature_type", dto.getSignatureType());
        }

        // 签章描述
        if (StringUtils.isNotEmpty(dto.getSignatureName())) {
            queryWrapper.like("a.signature_name", dto.getSignatureName());
        }


        IPage<SignatureProjectReportRelationDTO> list = signatureProjectReportMapper.findList(page, queryWrapper);

        return list;
    }
    /*8
    用于导出数据
     */
    public IPage<SignatureProjectReportRelationDTO> list2(Page<SignatureProjectReportRelationDTO> page, SignatureProjectReportRelationDTO dto) throws Exception {
        QueryWrapper<SignatureProjectReportRelationDTO> queryWrapper = QueryWrapperGenerator.buildQueryCondition(dto, SignatureProjectReportRelationDTO.class);
        /**
         * a表是reimbursementInfo
         * b表是reimbursementDetailInfo
         * c表是sysUser
         */
        queryWrapper.eq("a.del_flag", 0);

        // 创建时间
        if (dto.getDates() != null) {
            queryWrapper.between("a.create_time", dto.getDates()[0], dto.getDates()[1]);
        }
        // 创建人
        if (StringUtils.isNotEmpty(dto.getCreateById())) {
            queryWrapper.apply("(a.create_by_id",dto.getCreateById());
        }

        // 状态
        if (StringUtils.isNotEmpty(dto.getStatus())) {
            queryWrapper.eq("a.status", dto.getStatus());
        }
        // 部门
        if (StringUtils.isNotEmpty(dto.getOfficeId())) {
            queryWrapper.eq("so.id", dto.getOfficeId());
        }

        // 签章类型
        if (StringUtils.isNotBlank(dto.getSignatureType())) {
            queryWrapper.eq("a.signature_type", dto.getSignatureType());
        }

        // 签章描述
        if (StringUtils.isNotEmpty(dto.getSignatureName())) {
            queryWrapper.like("a.signature_name", dto.getSignatureName());
        }


        IPage<SignatureProjectReportRelationDTO> list = signatureProjectReportMapper.findList2(page, queryWrapper);

        return list;
    }

    public SignatureProjectReportRelationDTO findById(String id) {
        SignatureProjectReportRelationDTO dto = new SignatureProjectReportRelationDTO();
        SignatureProjectReportRelationDTO reportRelationDTO=signatureProjectReportMapper.findById(id);
        if (ObjectUtil.isNotEmpty(reportRelationDTO)){
            BeanUtils.copyProperties(reportRelationDTO, dto);
            List<CwProjectRecordsDTO> dtoList = new ArrayList<>();
            //查询报告签章表所关联的项目id
            List<SignatureProjectReportRelevanceNumber> relevanceNumberList = relevanceNumberMapper.selectList(new QueryWrapper<SignatureProjectReportRelevanceNumber>().eq("signature_project_report_id", id));
            if (CollectionUtils.isNotEmpty(relevanceNumberList)){
                for (SignatureProjectReportRelevanceNumber number : relevanceNumberList) {
                    CwProjectRecordsDTO projectRecordsDTO = cwProjectRecordsMapper.getInfoById(number.getProjectId());
                    dtoList.add(projectRecordsDTO);
                }
                dto.setProjectList(dtoList);
            }
            //查询附件信息
            List<WorkAttachmentInfo> fileList = signatureProjectReportMapper.findFiles(id,"signatureReport");
            if (CollectionUtils.isNotEmpty(fileList)) {
                for (WorkAttachmentInfo i : fileList) {
                    i.setCreateBy(SpringUtil.getBean ( IUserApi.class ).getById(i.getBy()));
                }
            }
            dto.setFiles(fileList);
            //查询已签章附件
            List<WorkAttachmentInfo> fileList1 = signatureProjectReportMapper.findFiles(id,"signatured_report");
            if (CollectionUtils.isNotEmpty(fileList1)) {
                for (WorkAttachmentInfo i : fileList1) {
                    i.setCreateBy(SpringUtil.getBean ( IUserApi.class ).getById(i.getBy()));
                }
            }
            dto.setSignatureFiles(fileList1);

        }
        return dto;
    }

    public SignatureProjectReportRelation save(SignatureProjectReportRelationDTO dto) throws Exception {
        UserDTO userDTO = SpringUtil.getBean(IUserApi.class).getByToken(TokenProvider.getCurrentToken());
        if (StringUtils.isNotBlank(dto.getId())){
            return update(dto,userDTO);
        }
        return add(dto,userDTO);
    }

    private SignatureProjectReportRelation update(SignatureProjectReportRelationDTO dto, UserDTO userDTO) {
        // 修改基础信息
        SignatureProjectReportRelation signatureProjectReportRelation = new SignatureProjectReportRelation();
        BeanUtils.copyProperties(dto, signatureProjectReportRelation);
        signatureProjectReportRelation.setUpdateById(userDTO.getId());
        signatureProjectReportRelation.setUpdateTime(new Date());
        signatureProjectReportMapper.updateById(signatureProjectReportRelation);
        //根据id删除签章项目关联表中的信息
        relevanceNumberMapper.delete(new QueryWrapper<SignatureProjectReportRelevanceNumber>().eq("signature_project_report_id",dto.getId()));
        //将新的项目信息存到关联表中
        if (CollectionUtils.isNotEmpty(dto.getProjectList())){
            for (CwProjectRecordsDTO projectRecordsDTO : dto.getProjectList()) {
                SignatureProjectReportRelevanceNumber signatureProjectReportRelevanceNumber = new SignatureProjectReportRelevanceNumber();
                signatureProjectReportRelevanceNumber.setProjectId(projectRecordsDTO.getId());
                signatureProjectReportRelevanceNumber.setSignatureProjectReportId(dto.getId());
                signatureProjectReportRelevanceNumber.setFromProject("1");
                relevanceNumberMapper.insert(signatureProjectReportRelevanceNumber);
            }
        }
        // 修改附件信息列表
        if (CollectionUtils.isNotEmpty(dto.getFiles())) {
            updateFiles(dto.getFiles(), userDTO, dto.getId(),"signatureReport");
        }
        //获取当前节点信息
        String currentTask = flowTaskService.getCurrentTaskName(dto.getProcInsId());
        if (StringUtils.isNotBlank(currentTask)){
            if (currentTask.equals("部门主任审批")){
                //部门主任同意之后生成签章信息
                if (StringUtils.isNotBlank(dto.getStatus())&&dto.getStatus().equals("2")){
                    this.getManualSignatureUrl(dto.getId());
                }
            }
        }

        return signatureProjectReportRelation;
    }

    private SignatureProjectReportRelation add(SignatureProjectReportRelationDTO dto, UserDTO userDTO) throws Exception {
        // 生成id
        String id = UUID.randomUUID().toString().replace("-", "");
        // 生成编号
        String no = SpringUtil.getBean ( IWorkAttachmentApi.class ).genSerialNum(userDTO.getCompanyDTO().getId(), dto.BIZ_CODE, TokenProvider.getCurrentToken());
        //保存信息
        SignatureProjectReportRelation signatureProjectReportRelation = new SignatureProjectReportRelation();
        BeanUtils.copyProperties(dto, signatureProjectReportRelation);
        signatureProjectReportRelation.setId(id);
        signatureProjectReportRelation.setNumber(no);
        signatureProjectReportRelation.setCreateById(userDTO.getId());
        signatureProjectReportRelation.setCreateTime(new Date());
        signatureProjectReportRelation.setUpdateById(userDTO.getId());
        signatureProjectReportRelation.setUpdateTime(new Date());
        signatureProjectReportRelation.setDelFlag(0);
        signatureProjectReportMapper.insert(signatureProjectReportRelation);
        //保存项目信息
        if (CollectionUtils.isNotEmpty(dto.getProjectList())){
            for (CwProjectRecordsDTO projectRecordsDTO : dto.getProjectList()) {
                SignatureProjectReportRelevanceNumber signatureProjectReportRelevanceNumber = new SignatureProjectReportRelevanceNumber();
                signatureProjectReportRelevanceNumber.setProjectId(projectRecordsDTO.getId());
                signatureProjectReportRelevanceNumber.setSignatureProjectReportId(id);
                signatureProjectReportRelevanceNumber.setFromProject("1");
                relevanceNumberMapper.insert(signatureProjectReportRelevanceNumber);
            }
        }
        // 保存附件列表信息
        if (CollectionUtils.isNotEmpty(dto.getFiles())) {
            saveFiles(dto.getFiles(), userDTO, id);
        }

        return signatureProjectReportRelation;
    }

    /**
     * 保存附件信息
     * @param list 待保存的附件列表
     * @param userDTO 当前登录用户
     * @param id 关联id
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveFiles(List<WorkAttachmentInfo> list, UserDTO userDTO, String id) {
        int j = 1;
        for (WorkAttachmentInfo dto : list) {
            WorkAttachmentInfo i = new WorkAttachmentInfo();
            //包含了url、size、name
            i.setId(UUID.randomUUID().toString().replace("-", ""));
//            i.getCreateBy().setId(userDTO.getId());
            i.setCreateTime(new Date());
//            i.getUpdateBy().setId(userDTO.getId());
            i.setUpdateTime(new Date());
            i.setDelFlag(0);
            i.setUrl(dto.getUrl());
            //文件类型处理
            String fileName = dto.getName();
            List<String> strings = Arrays.asList(fileName.split("\\."));
            // 检查文件名是否有后缀
            if (CollectionUtil.isNotEmpty(strings) && strings.size() > 1) {
                // 获取最后一个部分作为文件类型
                i.setType(strings.get(strings.size() - 1));
            } else {
                // 如果没有后缀或文件名无效，设置一个默认类型或空
                i.setType("");
            }
            i.setAttachmentId(id);
            i.setAttachmentName(dto.getName());
            i.setAttachmentFlag("signatureReport");
            i.setFileSize(dto.getSize());
            i.setSort(j);
//            ossServiceMapper.insertWorkAttachment(i, userDTO);
            Map<String,String> map = new HashMap<>();
            String workAttachment = JSON.toJSONString((i));
            String userDTOInfo = JSON.toJSONString((userDTO));
            map.put("workAttachment",workAttachment);
            map.put("userDTO",userDTOInfo);
            SpringUtil.getBean ( IWorkAttachmentApi.class ).insertWorkAttachment(map);
            j++;
        }
    }

    /**
     * 修改附件信息
     * @param list 待修改的附件列表
     * @param userDTO 当前登录用户
     * @param id 关联id
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateFiles(List<WorkAttachmentInfo> list, UserDTO userDTO, String id, String attachmentFlag) {
        int j = 1;
        String names = new String();
        //表中存在，但是传过来不存在，说明已删除，表中数据也要删除
        for (WorkAttachmentInfo dto : list) {
            names = names + "," +dto.getUrl();
        }
        //查询保存的附件信息
        List<WorkAttachmentInfo> infoList = mapper.findListByIdAndAttachmentFlag(id,attachmentFlag);
        if (org.flowable.editor.language.json.converter.util.CollectionUtils.isNotEmpty(infoList)) {
            for (WorkAttachmentInfo i : infoList) {
                if (!names.contains(i.getUrl())) {
//                    ossServiceMapper.deleteById(i.getId());
                    SpringUtil.getBean ( IWorkAttachmentApi.class ).deleteById(i.getId());
                }
            }
        }
        //保存信息
        for (WorkAttachmentInfo dto : list) {
            //判断是否存在
            Integer isExit = mapper.findIsExit(id, dto.getName());
            if (isExit == 0) {
                WorkAttachmentInfo i = new WorkAttachmentInfo();
                //包含了url、size、name
                i.setId(UUID.randomUUID().toString().replace("-", ""));
//                i.getCreateBy().setId(userDTO.getId());
                i.setCreateTime(new Date());
//                i.getUpdateBy().setId(userDTO.getId());
                i.setUpdateTime(new Date());
                i.setDelFlag(0);
                i.setUrl(dto.getUrl());
                //文件类型处理
                String fileName = dto.getName();
                List<String> strings = Arrays.asList(fileName.split("\\."));
                // 检查文件名是否有后缀
                if (CollectionUtil.isNotEmpty(strings) && strings.size() > 1) {
                    // 获取最后一个部分作为文件类型
                    i.setType(strings.get(strings.size() - 1));
                } else {
                    // 如果没有后缀或文件名无效，设置一个默认类型或空
                    i.setType("");
                }
                i.setAttachmentId(id);
                i.setAttachmentName(dto.getName());
                i.setAttachmentFlag(attachmentFlag);
                i.setFileSize(dto.getSize());
                i.setSort(j);
                Map<String,String> map = new HashMap<>();
                String workAttachment = JSON.toJSONString((i));
                String userDTOInfo = JSON.toJSONString((userDTO));
                map.put("workAttachment",workAttachment);
                map.put("userDTO",userDTOInfo);
                SpringUtil.getBean ( IWorkAttachmentApi.class ).insertWorkAttachment(map);
//                ossServiceMapper.insertWorkAttachment(i, userDTO);
                j++;
            }
        }
    }



    public String remove(String id) {
        signatureProjectReportMapper.deleteById(id);
        SpringUtil.getBean ( IWorkAttachmentApi.class ).deleteByAttachmentId(id);
        return "操作成功";
    }

    public void updateStatusById(SignatureProjectReportRelationDTO dto) {
        signatureProjectReportMapper.updateStatusById(dto.getStatus(),dto.getId());
        //如果是撤销或者是驳回,则需要对签章流程进行恢复
        if ("3".equals(dto.getStatus())||"4".equals(dto.getStatus())){
            SignatureProjectReportRelation signatureProjectReportRelation = new SignatureProjectReportRelation();
            signatureProjectReportRelation.setSignatureContractId("");
            signatureProjectReportRelation.setSignatureDocumentId("");
            signatureProjectReportRelation.setSignatureFlag(0);
            signatureProjectReportRelation.setSignatureUrlFlag(0);
            signatureProjectReportRelation.setSignatureUrl("");
            signatureProjectReportRelation.setSignatureFileName("");
            signatureProjectReportRelation.setSignatureUploadDate(null);
            signatureProjectReportRelation.setId(dto.getId());
            signatureProjectReportMapper.updateById(signatureProjectReportRelation);
        }
    }

    /**
     * 创建签章流程
     * @param dailyOfficeWorkId
     * @return
     */
    public HashMap<String, Object> getManualSignatureUrl( String dailyOfficeWorkId) {
        HashMap<String, Object> map = Maps.newHashMap();
        map.put("contractUrl","");
        map.put("success",false);
        //下载文件位置
        String deleteFile = null;
        try {
            //根据项目id查询是否已经提交过了报告签章
            SignatureProjectReportRelationDTO relationDTO = this.findById(dailyOfficeWorkId);
            if(null == relationDTO){
                map.put("str","查询不到该签章申请信息");
                map.put("success",false);
                return map;
            }
            if(null!= relationDTO.getSignatureFlag() && 1 == relationDTO.getSignatureFlag()){
                map.put("str","该盖章申请已完成");
                map.put("success",false);
                return map;
            }

            List<WorkAttachmentInfo> infoList = mapper.findListByIdAndAttachmentFlag(dailyOfficeWorkId,"signatureReport");


            //创建一个用于存放签章文件documentId的集合
            List<String> documentList = Lists.newArrayList();
            if(infoList.size()>0) {
                String aliyunUrl = "http://cdn.gangwaninfo.com";
                String aliDownloadUrl = "http://oss.gangwaninfo.com";
                for (WorkAttachmentInfo workattachment : infoList) {
                    if (StringUtils.isBlank(workattachment.getUrl())) {
                        map.put("str", "签章文件存储路径为空，无法进行签章操作，请驳回后重新上传盖章文件");
                        map.put("success", false);
                    } else {
                        if (StringUtils.isBlank(workattachment.getUrl())) {
                            map.put("str", "签章文件存储路径为空，无法进行签章操作，请驳回后重新上传盖章文件");
                            map.put("success", false);
                        } else {
                            //下载签章申请文件
                            String path = null;
                            if (System.getProperty("os.name").toLowerCase().contains("win")) {
                                path = "D:/attachment-file/";
                            } else {
                                path = "/attachment-file/";
                            }
                            String file = aliyunUrl+workattachment.getUrl();
                            file = file.replace("amp;", "");
                            String fileName = file.substring(file.lastIndexOf("/") + 1, file.length());
                            String cons = "";
                            if (file.contains(aliyunUrl)) {
                                cons = aliyunUrl;
                            } else if (file.contains("http://gangwan-app.oss-cn-hangzhou.aliyuncs.com")) {
                                cons = "http://gangwan-app.oss-cn-hangzhou.aliyuncs.com";
                            } else {
                                cons = aliDownloadUrl;
                            }
                            String ossKey = file.split(cons + "/")[1];
                            SpringUtil.getBean ( IWorkAttachmentApi.class ).downByStreamSaveLocal(ossKey,fileName,path+fileName);
                            //将下载下来的文件转换为file文件
                            File srcFile = new File(path + fileName);
                            deleteFile = path + fileName;

                            //截取文件后缀名
                            String substring = srcFile.getName().substring(srcFile.getName().lastIndexOf(".") + 1, srcFile.getName().length());
                            if (!"doc".equals(substring.toLowerCase()) && !"docx".equals(substring.toLowerCase()) && !"pdf".equals(substring.toLowerCase())) {
                                map.put("str", "请上传doc、docx或者pdf的文件进行签章操作");
                                map.put("success", false);
                            } else {

                                //获取真签单的documentId
                                HashMap hashMap = new SignaturePostUtil().getDocument(srcFile);
                                String code = hashMap.get("code").toString();

                                if ("0".equals(code)) {
                                    String documentId = "";
                                    String result = hashMap.get("result").toString();
                                    HashMap documentIdMap = JSON.parseObject(result, HashMap.class);
                                    documentId = documentIdMap.get("documentId").toString();
                                    if ("".equals(documentId)) {
                                        map.put("str", "签章文件创建失败，签章文件存在问题");
                                        map.put("success", false);
                                    } else {
                                        documentList.add(documentId);
                                    }
                                } else {
                                    String message = hashMap.get("message").toString();
                                    map.put("str", message);
                                    map.put("success", false);
                                }
                            }
                        }
                    }
                }
            }

            //根据项目id 和 documentId生成合同id
            HashMap contractIdHashMap = this.getManualSignatureContractId(documentList,relationDTO);
            String contractIdCode = contractIdHashMap.get("code").toString();
            String contractId = "";
            if("0".equals(contractIdCode)){
                contractId = contractIdHashMap.get("contractId").toString();
                if("".equals(contractId)){
                    map.put("str","签章文件创建失败");
                    map.put("success",false);
                    return map;
                }
            }else{
                map.put("str",contractIdHashMap.get("message").toString());
            }


            String documents = String.join(",", documentList);
            //修改报告信息中对应的签章contractId
            relationDTO.setSignatureDocumentId(documents);
            relationDTO.setSignatureContractId(contractId);
            //修改签章对应信息文件
            signatureProjectReportMapper.updateSignatureInfo(relationDTO);

            map.put("success",true);
            return map;

            //获取contractUrl路径
            /*String contractUrl = this.getSignatureContractUrl(contractId);
            if("".equals(contractUrl)){
                map.put("str","签章文件创建失败");
                map.put("success",false);
                return map;
            }else{

                String documents = String.join(",", documentList);
                //修改报告信息中对应的签章contractId
                dailyOfficeWork.setSignatureDocumentId(documents);
                dailyOfficeWork.setSignatureContractId(contractId);
                //修改签章对应信息文件
                dao.updateSignatureInfo(dailyOfficeWork);

                map.put("contractUrl",contractUrl);
                map.put("success",true);
                return map;
            }*/
        } catch (Exception e) {
            e.getMessage();
        } finally {
            if(StringUtils.isNotBlank(deleteFile)){
                //根据路径创建文件对象
                File file = new File(deleteFile);
                //路径是个文件且不为空时删除文件
                if(file.isFile()&&file.exists()){
                    file.delete();
                }
            }
        }


        return map;
    }

    /**
     * 根据项目id 和 documentId生成合同id（手动签生成签署合同）
     * @param documentList
     * @return
     */
    public HashMap getManualSignatureContractId(List<String> documentList,SignatureProjectReportRelationDTO relationDTO){
        HashMap hashMap = new HashMap();
        //创建签署方信息
        List<Action> actions = Lists.newArrayList();
        Set<String> serialIdSet = new HashSet<>();

        Action companyAction = new Action();
        companyAction.setType("CORPORATE");
        companyAction.setName("公司印章");
        companyAction.setSerialNo("1");
        //公司圆章-竖
        serialIdSet.add(COMPANYROUNDSEALID);
        //添加盖章位置
        List<Location> locations = Lists.newArrayList();
        for (String documentId: documentList) {
            Location location = new Location();
            location.setSealId(COMPANYROUNDSEALID);
            location.setDocumentId(documentId);
            location.setPage("0");
            location.setRectType("SEAL_CORPORATE");
            location.setKeywordIndex(-1);
            location.setOffsetX("0.5264");
            location.setOffsetY("0.6787");
            locations.add(location);
        }

        List<String> serialIdList = new ArrayList<String>(serialIdSet);
        companyAction.setSealIds("[" + String.join(",", serialIdList) + "]");
        companyAction.setAutoSign("false");
        companyAction.setLocations(locations);
        actions.add(companyAction);


        //创建签署方信息表
        List<SignatorieInfo> signatories = Lists.newArrayList();
        SignatorieInfo signatorieInfo1 = new SignatorieInfo();
        signatorieInfo1.setSerialNo("1");
        signatorieInfo1.setTenantName("江苏兴光项目管理有限公司");
        signatorieInfo1.setTenantType("COMPANY");
        signatorieInfo1.setActions(actions);
        signatories.add(signatorieInfo1);
        SignatureContract signatureContract = new SignatureContract();
        signatureContract.setDocuments(documentList);
        //签章申请用印流程id
        signatureContract.setCategoryId(SIGNATUREREPORTCAREGORYID);

        signatureContract.setSend(true);
        signatureContract.setSignatories(signatories);
        signatureContract.setSn("");
        if(null != relationDTO && StringUtils.isNotBlank(relationDTO.getNumber())){
            signatureContract.setSubject(relationDTO.getNumber() + "。" + relationDTO.getSignatureName());//添加项目名称
        }else if(null != relationDTO && StringUtils.isNotBlank(relationDTO.getSignatureName())){
            signatureContract.setSubject(relationDTO.getSignatureName());//添加项目名称
        }
        JSONObject json = JSONObject.fromObject(signatureContract);
        String contractIdMapStr = SignaturePostUtil.sendPostApplicationJson(HTTPTOP + "/contract/createbycategory", json.toString());
        hashMap = JSON.parseObject(contractIdMapStr, HashMap.class);

        return hashMap;
    }

    /**
     * 根据documentId查询签章信息
     * @param documentId
     * @return
     */
    public SignatureProjectReportRelationDTO getByDocumentId(String documentId) {
        SignatureProjectReportRelationDTO relationDTO = signatureProjectReportMapper.getByDocumentId(documentId);
        return relationDTO;
    }
    //根据contractId查询对应的报告信息
    public SignatureProjectReportRelationDTO getByContractId(String contractId) {
        SignatureProjectReportRelationDTO relationDTO = signatureProjectReportMapper.getByContractId(contractId);
        return relationDTO;
    }

    /**
     * 根据报告签章id查询签章审核节点信息
     * @param
     * @return
     */
    public Map<String,Object> getAuditNodeById(String id){
        Map<String,Object> map = new HashMap<>();
        //查询流程id
        SignatureProjectReportRelationDTO relationDTO = signatureProjectReportMapper.findById(id);
        if(StringUtils.isNotBlank(relationDTO.getProcInsId())){
            //根据流程id查询流程当前节点信息
            String currentTask = flowTaskService.getCurrentTaskName(relationDTO.getProcInsId());
            if(StringUtils.isNotEmpty(currentTask)){
                map.put("success", true);
                map.put("message", "获取签章流程成功");
                map.put("signatureType", currentTask);
            }else{
                map.put("success", false);
                map.put("message", "获取签章流程失败");
                map.put("signatureType", "");
            }
        }else{
            map.put("success", false);
            map.put("message", "获取签章流程失败");
            map.put("signatureType", "");
        }

        return map;
    }

    /**
     * 根据签章节点获取签章状态数据信息
     * @param id
     * @return
     */
    public Map<String,Object> getSignatureTypeById(String id){
        Map<String,Object> map = new HashMap<>();
        SignatureProjectReportRelationDTO relationDTO = signatureProjectReportMapper.findById(id);
        if(null != relationDTO){
            map.put("success", true);
            map.put("message", "获取签章完成情况成功");
            map.put("signatureType", relationDTO.getSignatureFlag());
        }else{
            map.put("success", false);
            map.put("message", "获取签章完成情况失败");
            map.put("signatureType", "0");
        }
        return map;
    }
}
