package com.jeeplus.finance.contractRegistration.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.druid.sql.visitor.functions.If;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.jeeplus.common.TokenProvider;
import com.jeeplus.core.domain.BaseEntity;
import com.jeeplus.finance.contractRegistration.domain.ContractFile;
import com.jeeplus.finance.contractRegistration.domain.ContractFilePaper;
import com.jeeplus.finance.contractRegistration.domain.ContractInfo;
import com.jeeplus.finance.contractRegistration.domain.ContractParticipant;
import com.jeeplus.finance.contractRegistration.mapper.ContractFileMapper;
import com.jeeplus.finance.contractRegistration.mapper.ContractFilePaperMapper;
import com.jeeplus.finance.contractRegistration.mapper.ContractInfoMapper;
import com.jeeplus.finance.contractRegistration.mapper.ContractParticipantMapper;
import com.jeeplus.finance.workClientInfo.domain.CwWorkClientBase;
import com.jeeplus.finance.workClientInfo.service.CwWorkClientService;
import com.jeeplus.finance.workClientInfo.service.dto.CwWorkClientBaseDTO;
//import com.jeeplus.pubmodules.oss.mapper.OssServiceMapper;
//import com.jeeplus.pubmodules.oss.service.OssService;
//import com.jeeplus.pubmodules.serialNumTpl.service.SerialnumTplService;
import com.jeeplus.sys.domain.WorkAttachmentInfo;
import com.jeeplus.sys.feign.IRoleApi;
import com.jeeplus.sys.feign.IUserApi;
import com.jeeplus.sys.feign.IWorkAttachmentApi;
import com.jeeplus.sys.service.dto.RoleDTO;
import com.jeeplus.sys.service.dto.UserDTO;
//import com.jeeplus.sys.utils.UserUtils;
import org.apache.commons.lang3.StringUtils;
import org.flowable.editor.language.json.converter.util.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author: 王强
 * @create: 2022-11-08 10:50
 **/
@Service
public class ContractInfoService {

    @Resource
    private ContractInfoMapper mapper;

//    @Resource
//    private SerialnumTplService serialnumTplService;

//    @Resource
//    private OssServiceMapper ossServiceMapper;

    @Resource
    private ContractFileMapper fileMapper;

    @Resource
    private ContractFilePaperMapper paperMapper;

    @Resource
    private ContractParticipantMapper participantMapper;

    @Resource
    private CwWorkClientService cwWorkClientService;

//    @Resource
//    private OssService ossService;

    /**
     * 根据id修改status
     */
    public void updateStatusById(ContractInfo info) {
        mapper.updateStatusById(info.getId(), info.getStatus());
    }
    /**
     * 根据id修改合同实际金额
     */
    public void updateInfo(ContractInfo info) {
        mapper.updateInfo(info.getId(), info.getActualContractAmount(),info.getContractApprovalType(),info.getFiledType());
    }

    /**
     * 根据id修改合同实际金额
     */
    public void updatePaperInfo(ContractInfo info) {
        mapper.updatePaperInfo(info.getId(), info.getActualContractAmount(),info.getContractApprovalType(), info.getFiledPaperType());
        List<WorkAttachmentInfo> list = info.getContractInfoList();
        UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken());
        if (CollectionUtils.isNotEmpty(list)) {
            updateFiles(list, userDTO, info.getId());
        }
    }

    public IPage<ContractInfo> list(Page<ContractInfo> page, ContractInfo info, QueryWrapper<ContractInfo> wrapper) {
//        LambdaQueryWrapper<ContractInfo> wrapper = new LambdaQueryWrapper<>();

        //条件查询list
        //1、合同编号
        if (StringUtils.isNotBlank(info.getContractNo())) {
            wrapper.like("a.contract_no", info.getContractNo());
        }
        //案卷号
        if (StringUtils.isNotBlank(info.getFiledNo())) {
            wrapper.like("h.filed_no", info.getFiledNo());
        }
        //2、合同名称
        if (StringUtils.isNotBlank(info.getContractName())) {
            wrapper.like("a.contract_name", info.getContractName());
        }
        //3、合同金额（区间）
        String[] contractAmounts = info.getContractAmounts();
        if (contractAmounts != null) {
            if (StringUtils.isNotBlank(contractAmounts[0])) {
                wrapper.ge("a.contract_amount",contractAmounts[0]);
            }
            if (contractAmounts.length>1 && StringUtils.isNotBlank(contractAmounts[1])) {
                wrapper.le("a.contract_amount", contractAmounts[1]);
            }
        }
        //4、签约时间（区间）
        String[] contractDates = info.getContractDates();
        if (contractDates != null) {

            wrapper.between("a.signing_date", contractDates[0], contractDates[1]);
        }
        //5、创建人
        if (StringUtils.isNotBlank(info.getCreateById())) {
            wrapper.like("c.`id`", info.getCreateById());
        }
        //6、所属部门
        if (StringUtils.isNotBlank(info.getDepartment())) {
            //先根据id查出是否是父节点，是父节点则查出所有的子节点信息
            List<String> childIds = mapper.findChildIds(info.getDepartment());
            if ( null != childIds & childIds.size()>0){
                childIds.add(info.getDepartment());
                wrapper.in("a.department",childIds);
            }else {
                wrapper.eq("a.department", info.getDepartment());
            }
        }
        //7、状态
        //判断 状态是否包含 逗号
        if(StringUtils.isNotBlank(info.getStatus())){
            if (info.getStatus().contains(",")) {
                List<String> statusList = Lists.newLinkedList();
                statusList = Arrays.asList(info.getStatus().split(","));
                wrapper.in("a.status", statusList);
            }else{
                wrapper.like("a.status", info.getStatus());
            }
        }
        //8、归档状态
        if (StringUtils.isNotBlank(info.getFiledType())) {
            wrapper.like("a.filed_type", info.getFiledType());
        }
        //纸质归档
        if (StringUtils.isNotBlank(info.getFiledPaperType())) {
            wrapper.like("a.filed_paper_type", info.getFiledPaperType());
        }
        //委托方名称
        if (StringUtils.isNotBlank(info.getClientContactsName())) {
            wrapper.like("cw_wcb.name", info.getClientContactsName());
        }
        wrapper.eq("a.del_flag","0");


        StringBuilder officeIds = new StringBuilder();
       /* List<String> manageOfficeIdList= Lists.newArrayList();
        UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken());*/
        //判定是否为会计所长
        /*if(CommonUtils.haveRoleKjsz()){
            //获取当前人管理的部门id
            if(StringUtils.isNotBlank(userDTO.getManageOfficeIds())){
                manageOfficeIdList = Arrays.asList(userDTO.getManageOfficeIds().split(","));
            }else{
                manageOfficeIdList.add(userDTO.getOfficeDTO().getId());
            }
            for (int i = 0; i <manageOfficeIdList.size(); i++){
                officeIds.append("'").append(manageOfficeIdList.get(i)).append("'");
                if(i < manageOfficeIdList.size()-1){
                    officeIds.append(",");
                }
            }
        }*/

        /*//获取当前登录人所属角色
        //若是评估部门主任，则仅展示部门主任信息
        //若是评估员工，则仅展示自己的数据信息
        List<RoleDTO> roleDTOList = userDTO.getRoleDTOList();
        for (RoleDTO roleDTO : roleDTOList) {
            //根据角色id查询角色信息
            RoleDTO roleDTOById = SpringUtil.getBean(IRoleApi.class).getRoleDTOById(roleDTO.getId());
            if("cwyg".equals(roleDTOById.getEnName()) && "兴光会计员工".equals(roleDTOById.getName())){
                wrapper.eq("a.create_by_id", userDTO.getId());
                break;
            }else if("cw_bmzr".equals(roleDTOById.getEnName()) && "兴光会计部门主任".equals(roleDTOById.getName())){
                wrapper.eq("c.office_id", userDTO.getOfficeDTO().getId());
                break;
            }
        }*/

        IPage<ContractInfo> pageList = mapper.findPageList(page, officeIds.toString(), wrapper);

        return pageList;
    }

    /**
     * 合同登记查询
     */
    public ContractInfo findByContractId(String id) {

        //根据id判断是file表的id，还是info表的id
//        ContractFile byId = mapper.getById(id);
//        ContractInfo dto = null;
//        if (byId != null){
//            dto = mapper.findByContractId(id);
//        }else {
//            dto = mapper.findById(id);
//        }
        ContractInfo dto = mapper.findById(id);
        if (dto != null){
            dto.setContractStatus("新创建");
            // 查询附件信息
            List<WorkAttachmentInfo> dtos = mapper.findDtos(id);
            if (CollectionUtils.isNotEmpty(dtos)) {
                for (WorkAttachmentInfo i : dtos) {
                    i.setCreateBy(SpringUtil.getBean ( IUserApi.class ).getById(i.getBy()));
                }
            }
            dto.setContractProperList(dtos);
        }

        return dto;
    }

    /**
     * 合同登记查询
     */
    public ContractInfo findById(String id) {

        ContractInfo dto = mapper.findById(id);
        List<WorkAttachmentInfo> fileList = Lists.newArrayList();

        if (dto != null){
            List<ContractParticipant> participant = participantMapper.findByInfoId(dto.getId());
            dto.setContractStatus("新创建");
            // 查询附件信息
            List<WorkAttachmentInfo> dtos = mapper.findDtos(id);
            if (CollectionUtils.isNotEmpty(dtos)) {
                for (WorkAttachmentInfo i : dtos) {
                    i.setCreateBy(SpringUtil.getBean ( IUserApi.class ).getById(i.getBy()));
                }
            }
            fileList.addAll(dtos);
            List<CwWorkClientBaseDTO> list = new ArrayList<>();
            if (participant.size()>0){
                participant.forEach(cw->{
                    CwWorkClientBaseDTO baseDTO = new CwWorkClientBaseDTO();
                    baseDTO.setName(cw.getCustomerName());
                    baseDTO.setNo(cw.getCustomerNo());
                    list.add(baseDTO);
                });

            }
            //根据合同id去归档表查归档附件信息
//            ContractFile file = fileMapper.getInfoByConId(dto.getId());
//            if (null != file){
//                //查归档附件信息
//                List<WorkAttachmentInfo> fileDtos = mapper.findDtos(file.getId());
//                if (CollectionUtils.isNotEmpty(fileDtos)) {
//                    for (WorkAttachmentInfo i : fileDtos) {
//                        i.setCreateBy(UserUtils.get(i.getBy()));
//                    }
//                    dto.setContractInfoList(fileDtos);
//                }
//            }
            //根据合同id去纸质归档表查附件信息
            ContractFilePaper filePaper = paperMapper.selectFilePaperByContractInfoId(id);
            if (null != filePaper){
                //查归档附件信息
                List<WorkAttachmentInfo> fileDtos = mapper.findDtos(filePaper.getId());
                if (CollectionUtils.isNotEmpty(fileDtos)) {
                    for (WorkAttachmentInfo i : fileDtos) {
                        i.setCreateBy(SpringUtil.getBean ( IUserApi.class ).getById(i.getBy()));
                    }
                    fileList.addAll(fileDtos);
                    //dto.setContractInfoList(fileDtos);
                }
            }

            dto.setCwWorkClientContactDTOList(list);
            dto.setContractProperList(fileList);
        } else {
            //穿来的是归档的id
            ContractFile infoByConId = fileMapper.getById(id);
            if ( null != infoByConId) {
                dto = mapper.findById(infoByConId.getContractInfoId());
                if (null != dto) {
                    List<ContractParticipant> participant = participantMapper.findByInfoId(dto.getId());
                    dto.setContractStatus("新创建");
                    // 查询附件信息
                    List<WorkAttachmentInfo> dtos = mapper.findDtos(dto.getId());
                    if (CollectionUtils.isNotEmpty(dtos)) {
                        for (WorkAttachmentInfo i : dtos) {
                            i.setCreateBy(SpringUtil.getBean ( IUserApi.class ).getById(i.getBy()));
                        }
                    }
                    fileList.addAll(dtos);
                    List<CwWorkClientBaseDTO> list = new ArrayList<>();
                    if (participant.size()>0){
                        participant.forEach(cw->{
                            CwWorkClientBaseDTO baseDTO = new CwWorkClientBaseDTO();
                            baseDTO.setName(cw.getCustomerName());
                            baseDTO.setNo(cw.getCustomerNo());
                            list.add(baseDTO);
                        });

                    }
                    if (null != infoByConId){
                        //查归档附件信息
                        List<WorkAttachmentInfo> fileDtos = mapper.findDtos(id);
                        if (CollectionUtils.isNotEmpty(fileDtos)) {
                            for (WorkAttachmentInfo i : fileDtos) {
                                i.setCreateBy(SpringUtil.getBean ( IUserApi.class ).getById(i.getBy()));
                            }
                            fileList.addAll(fileDtos);
                            //dto.setContractInfoList(fileDtos);
                        }
                    }

                    dto.setCwWorkClientContactDTOList(list);
                    dto.setContractProperList(fileList);
                }
            } else {
                //传过来的是纸质归档的id
                ContractFilePaper filePaper = paperMapper.getById(id);
                if ( null != filePaper ) {
                    dto = mapper.findById(filePaper.getContractInfoId());
                    if (null != dto) {
                        //参与签约方信息
                        List<ContractParticipant> participant = participantMapper.findByInfoId(dto.getId());
                        dto.setContractStatus("新创建");
                        // 查询合同登记附件信息
                        List<WorkAttachmentInfo> dtos = mapper.findDtos(dto.getId());
                        if (CollectionUtils.isNotEmpty(dtos)) {
                            for (WorkAttachmentInfo i : dtos) {
                                i.setCreateBy(SpringUtil.getBean ( IUserApi.class ).getById(i.getBy()));
                            }
                        }
                        fileList.addAll(dtos);
                        List<CwWorkClientBaseDTO> list = new ArrayList<>();
                        if (participant.size()>0){
                            participant.forEach(cw->{
                                CwWorkClientBaseDTO baseDTO = new CwWorkClientBaseDTO();
                                baseDTO.setName(cw.getCustomerName());
                                baseDTO.setNo(cw.getCustomerNo());
                                list.add(baseDTO);
                            });

                        }
                        //查归档附件信息
                        List<WorkAttachmentInfo> fileDtos = mapper.findDtos(filePaper.getId());
                        if (CollectionUtils.isNotEmpty(fileDtos)) {
                            for (WorkAttachmentInfo i : fileDtos) {
                                i.setCreateBy(SpringUtil.getBean ( IUserApi.class ).getById(i.getBy()));
                            }
                            fileList.addAll(fileDtos);
                            //dto.setContractInfoList(fileDtos);
                        }
//                        //估计合同登记id查出归档信息
//                        ContractFile contractFile = fileMapper.getInfoByConId(dto.getId());
//                        if (null != contractFile){
//                            //查归档附件信息
//                            List<WorkAttachmentInfo> fileDtos = mapper.findDtos(contractFile.getId());
//                            if (CollectionUtils.isNotEmpty(fileDtos)) {
//                                for (WorkAttachmentInfo i : fileDtos) {
//                                    i.setCreateBy(UserUtils.get(i.getBy()));
//                                }
//                                dto.setContractInfoList(fileDtos);
//                            }
//                        }

                        dto.setCwWorkClientContactDTOList(list);
                        dto.setContractProperList(fileList);
                    }
                }
            }
        }

        return dto;
    }

    /**
     * 合同登记查询附件信息
     */
    public ContractInfo findFileInfoById(String id) {

        ContractInfo dto = mapper.findFileInfoById(id);

        if (dto != null){
            List<ContractParticipant> participant = participantMapper.findByInfoId(dto.getId());
            dto.setContractStatus("新创建");
            // 查询附件信息
            List<WorkAttachmentInfo> dtos = mapper.findDtos(id);
            if (CollectionUtils.isNotEmpty(dtos)) {
                for (WorkAttachmentInfo i : dtos) {
                    i.setCreateBy(SpringUtil.getBean ( IUserApi.class ).getById(i.getBy()));
                }
            }
            List<CwWorkClientBaseDTO> list = new ArrayList<>();
            if (participant.size()>0){
                participant.forEach(cw->{
                    CwWorkClientBaseDTO baseDTO = new CwWorkClientBaseDTO();
                    baseDTO.setName(cw.getCustomerName());
                    baseDTO.setNo(cw.getCustomerNo());
                    list.add(baseDTO);
                });

            }
            //根据合同id去归档表查归档附件信息
            ContractFile file = fileMapper.getInfoByConId(dto.getId());
            if (null != file){
                //查归档附件信息
                List<WorkAttachmentInfo> fileDtos = mapper.findDtos(file.getId());
                if (CollectionUtils.isNotEmpty(fileDtos)) {
                    for (WorkAttachmentInfo i : fileDtos) {
                        i.setCreateBy(SpringUtil.getBean ( IUserApi.class ).getById(i.getBy()));
                    }
                    dto.setContractInfoList(fileDtos);
                }
            }

            dto.setCwWorkClientContactDTOList(list);
            dto.setContractProperList(dtos);
        }

        return dto;
    }

    public String saveInfo(ContractInfo info) throws Exception {
        info.setClientContacts(info.getCustomerId());
        if (StringUtils.isNotEmpty(info.getId())) {
            //对参与签约方进行处理  将参与签约方的客户编号 和 客户名称进行持久化
            ContractInfo contractInfo = mapper.selectById(info.getId());
            if (contractInfo != null) {
                info.setCreateById(info.getCreateId());
                return update(info);
            }
        }
        return add(info);
    }

    /**
     * 合同登记删除
     */
    public ResponseEntity removeById(String id) {
        // 查询合同是否被引用 （项目、报销、发票）
        // 查询合同是否被引用（项目）
        String useByProject = mapper.isUseByProject(id);
        String aa = mapper.isUseByReim(id);
        String bb = mapper.isUseByInvoice(id);
        if (StringUtils.isNotBlank(useByProject)) {
            return ResponseEntity.ok ("合同: "+useByProject+" 被引用，不可删除");
        }
        // 查询合同是否被引用（报销）
        String useByReim = mapper.isUseByReim(id);
        if (StringUtils.isNotBlank(useByReim)) {
            return ResponseEntity.ok ("合同: "+useByReim+" 被引用，不可删除");
        }
        // 查询合同是否被引用（发票）
        String useByInvoice = mapper.isUseByInvoice(id);
        if (StringUtils.isNotBlank(useByInvoice)) {
            return ResponseEntity.ok ("合同: "+useByInvoice+" 被引用，不可删除");
        }
        mapper.deleteById(id);
        return ResponseEntity.ok ("删除成功");
    }

    /**
     * 合同登记修改
     */
    @Transactional(rollbackFor = Exception.class)
    public String update(ContractInfo info) throws Exception{
        //获取当前登录人信息
        UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken());

        ContractInfo contractInfo = new ContractInfo();
        BeanUtils.copyProperties(info, contractInfo);
        contractInfo.setUpdateById(userDTO.getId());
        contractInfo.setUpdateTime(new Date());

        //合同编号生成
        String serialNum = "";
        String currentToken = TokenProvider.getCurrentToken();
        if (StringUtils.isNotBlank(contractInfo.getContractType()) && StringUtils.isBlank(contractInfo.getContractNo())){
            if (contractInfo.getContractType().equals("1")){
                serialNum = SpringUtil.getBean ( IWorkAttachmentApi.class ).genSerialNum(userDTO.getCompanyDTO().getId(), ContractInfo.SERIAL_NUMBER1,currentToken);
            } else if (contractInfo.getContractType().equals("2")) {
                serialNum = SpringUtil.getBean ( IWorkAttachmentApi.class ).genSerialNum(userDTO.getCompanyDTO().getId(), ContractInfo.SERIAL_NUMBER2,currentToken);
            } else if (contractInfo.getContractType().equals("3")) {
                serialNum = SpringUtil.getBean ( IWorkAttachmentApi.class ).genSerialNum(userDTO.getCompanyDTO().getId(), ContractInfo.SERIAL_NUMBER3,currentToken);
            } else if (contractInfo.getContractType().equals("4")) {
                serialNum = SpringUtil.getBean ( IWorkAttachmentApi.class ).genSerialNum(userDTO.getCompanyDTO().getId(), ContractInfo.SERIAL_NUMBER4,currentToken);
            } else if (contractInfo.getContractType().equals("5")) {
                serialNum = SpringUtil.getBean ( IWorkAttachmentApi.class ).genSerialNum(userDTO.getCompanyDTO().getId(), ContractInfo.SERIAL_NUMBER5,currentToken);
            } else if (contractInfo.getContractType().equals("6")) {
                serialNum = SpringUtil.getBean ( IWorkAttachmentApi.class ).genSerialNum(userDTO.getCompanyDTO().getId(), ContractInfo.SERIAL_NUMBER6,currentToken);
            }
            contractInfo.setContractNo(serialNum);
        }

        if (StringUtils.isNotEmpty(contractInfo.getStatus()) &&!contractInfo.getStatus().equals("5")){
            int num = Integer.parseInt(contractInfo.getChangeNum()) + 1;
            contractInfo.setChangeNum(num + "");
        }else {
            contractInfo.setChangeNum(contractInfo.getChangeNum());
        }
        //对管理员上传归档文件进行相关操作  归档修改
        if (StringUtils.isNotEmpty(contractInfo.getFiledType()) && contractInfo.getFiledType().equals("5")){
            //根据id找到归档表id
            ContractFile contractFile = fileMapper.getInfoByConId(info.getId());
            if ( null != contractFile) {
                contractFile.setContractInfoList(info.getContractInfoList());
                if (CollectionUtils.isNotEmpty(contractFile.getContractInfoList())){
                    updateFiles(contractFile.getContractInfoList(), userDTO, contractFile.getId());
                }
            }
        }

        //纸质归档修改
        ContractFilePaper filePaper = paperMapper.selectFilePaperByContractInfoId(info.getId());
        if (null != filePaper) {
            filePaper.setFiledNo(info.getFiledNo());
            filePaper.setConfirmFiledNo(info.getConfirmFiledNo());
            paperMapper.updateById(filePaper);
        }

        mapper.updateById(contractInfo);
        ContractParticipant participant = new ContractParticipant();
        //对参与签约方进行操作
        participantMapper.deleteFromParticipant(info.getId());
        //在操作前，清空之前的信息
        if (info.getCwWorkClientContactDTOList() != null){
            if (info.getCwWorkClientContactDTOList().size()>0){
                info.getCwWorkClientContactDTOList().forEach(cw->{

                    String parId = UUID.randomUUID().toString().replace("-", "");
                    participant.setId(parId);
                    participant.setContractInfoId(info.getId());
                    participant.setCustomerName(cw.getName());
                    participant.setCustomerNo(cw.getNo());
                    participant.setCreateById(userDTO.getId());
                    participant.setCreateTime(info.getCreateTime());
                    participant.setUpdateById(userDTO.getId());
                    participant.setUpdateTime(new Date());
                    participantMapper.insert(participant);
                });
            }
        }

        List<WorkAttachmentInfo> list = info.getContractProperList();
        if (CollectionUtils.isNotEmpty(list)) {
            updateFiles(list, userDTO, info.getId());
        }

        return info.getId();
    }

    /**
     * 合同登记新增
     */
    @Transactional(rollbackFor = Exception.class)
    public String add(ContractInfo contractInfo) throws Exception{
        //获取当前登录人信息
        UserDTO userDTO = SpringUtil.getBean ( IUserApi.class ).getByToken(TokenProvider.getCurrentToken());
        String currentToken = TokenProvider.getCurrentToken();
        //合同流水号生成
        String serialNumber = SpringUtil.getBean ( IWorkAttachmentApi.class ).genSerialNum(userDTO.getCompanyDTO().getId(), ContractInfo.BIZ_CODE,currentToken);
        //合同编号生成
        String serialNum = "";
        if (StringUtils.isNotEmpty(contractInfo.getContractType())){
            if (contractInfo.getContractType().equals("1")){
                serialNum = SpringUtil.getBean ( IWorkAttachmentApi.class ).genSerialNum(userDTO.getCompanyDTO().getId(), ContractInfo.SERIAL_NUMBER1,currentToken);
            } else if (contractInfo.getContractType().equals("2")) {
                serialNum = SpringUtil.getBean ( IWorkAttachmentApi.class ).genSerialNum(userDTO.getCompanyDTO().getId(), ContractInfo.SERIAL_NUMBER2,currentToken);
            } else if (contractInfo.getContractType().equals("3")) {
                serialNum = SpringUtil.getBean ( IWorkAttachmentApi.class ).genSerialNum(userDTO.getCompanyDTO().getId(), ContractInfo.SERIAL_NUMBER3,currentToken);
            } else if (contractInfo.getContractType().equals("4")) {
                serialNum = SpringUtil.getBean ( IWorkAttachmentApi.class ).genSerialNum(userDTO.getCompanyDTO().getId(), ContractInfo.SERIAL_NUMBER4,currentToken);
            } else if (contractInfo.getContractType().equals("5")) {
                serialNum = SpringUtil.getBean ( IWorkAttachmentApi.class ).genSerialNum(userDTO.getCompanyDTO().getId(), ContractInfo.SERIAL_NUMBER5,currentToken);
            } else if (contractInfo.getContractType().equals("6")) {
                serialNum = SpringUtil.getBean ( IWorkAttachmentApi.class ).genSerialNum(userDTO.getCompanyDTO().getId(), ContractInfo.SERIAL_NUMBER6,currentToken);
            }
            contractInfo.setContractSerialNumber(serialNumber);
        }
        String id = UUID.randomUUID().toString().replace("-", "");
        ContractInfo info = new ContractInfo();
        BeanUtils.copyProperties(contractInfo, info);
        info.setId(id);
//        info.setNo(serialNum);
        info.setContractNo(serialNum);
        info.setCreateById(userDTO.getId());
        info.setCreateTime(contractInfo.getCreateTime());
        info.setUpdateById(userDTO.getId());
        info.setUpdateTime(new Date());
        mapper.insert(info);
        //对参与签约方进行持久化
        //对参与签约方进行操作
        participantMapper.deleteFromParticipant(info.getId());
        ContractParticipant participant = new ContractParticipant();
        if (info.getCwWorkClientContactDTOList() != null){
            if (info.getCwWorkClientContactDTOList().size()>0){
                info.getCwWorkClientContactDTOList().forEach(cw->{
                    String parId = UUID.randomUUID().toString().replace("-", "");
                    participant.setId(parId);
                    participant.setContractInfoId(id);
                    participant.setCustomerName(cw.getName());
                    participant.setCustomerNo(cw.getNo());
                    participant.setCreateById(userDTO.getId());
                    participant.setCreateTime(contractInfo.getCreateTime());
                    participant.setUpdateById(userDTO.getId());
                    participant.setUpdateTime(new Date());
                    participantMapper.insert(participant);
                });
            }
        }
        List<WorkAttachmentInfo> list = contractInfo.getContractProperList();
//        if (CollectionUtils.isNotEmpty(list)) {
//            saveFiles(list, userDTO, id);
//        }
        saveFiles(list, userDTO, id);

        return id;
    }

    /**
     * 保存附件信息
     * @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());
            //文件类型处理
            List<String> strings = Arrays.asList(dto.getName().split("\\."));
            if (CollectionUtils.isNotEmpty(strings)) {
                i.setType(strings.get(1));
            }
            i.setAttachmentId(id);
            i.setAttachmentName(dto.getName());
            i.setAttachmentFlag("cwWorkContract");
            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) {
        int j = 1;
        String names = new String();
        //表中存在，但是传过来不存在，说明已删除，表中数据也要删除
        for (WorkAttachmentInfo dto : list) {
            names = names + "," +dto.getUrl();
        }
        //查询保存的附件信息
        List<WorkAttachmentInfo> infoList = mapper.findList(id);
        if (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());
                //文件类型处理
                List<String> strings = Arrays.asList(dto.getName().split("\\."));
                if (CollectionUtils.isNotEmpty(strings)) {
                    i.setType(strings.get(1));
                }
                i.setAttachmentId(id);
                i.setAttachmentName(dto.getName());
                i.setAttachmentFlag("cwWorkContract");
                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 List<ContractInfo> getByClientId(String contractId, ContractInfo contractInfo){
        if (StringUtils.isNotBlank(contractId)) {
            CwWorkClientBase cwWorkClientBase = cwWorkClientService.getById(contractId);
            if (ObjectUtil.isNotEmpty(cwWorkClientBase)) {
                if (StringUtils.isNotBlank(cwWorkClientBase.getNo())) {
                    List<String> ids = mapper.getClientListByClientNo(cwWorkClientBase.getNo());
                    if (CollectionUtil.isNotEmpty(ids)){
                        QueryWrapper<ContractInfo> queryWrapper = new QueryWrapper<>();
                        queryWrapper.in("cw_wci.id",ids);
                        queryWrapper.eq("cw_wci.del_flag","0");
//                        queryWrapper.eq("cw_wci.status","5");  //  取消查询审核通过(status=5)的合同数据，只要求数据有效(del_flag=0)就可以
                        queryWrapper.orderByDesc("cw_wci.create_time");
                        if(ObjectUtil.isNotEmpty(contractInfo)){
                            if(StringUtils.isNotBlank(contractInfo.getContractName())){
                                queryWrapper.like("cw_wci.contract_name",contractInfo.getContractName());
                            }
                            if(StringUtils.isNotBlank(contractInfo.getContractNo())){
                                queryWrapper.like("cw_wci.contract_no",contractInfo.getContractNo());
                            }
                        }
                        return mapper.getByClientId(queryWrapper);
                    }
                }
            }
            return new ArrayList<>();
        }
        return new ArrayList<>();
    }
}
