package com.sunxung.factoring.service.businessmanagement.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.sunxung.factoring.component.exception.BusinessException;
import com.sunxung.factoring.component.exception.ValidatorException;
import com.sunxung.factoring.component.util.*;
import com.sunxung.factoring.dict.impl.BusinessStageDict;
import com.sunxung.factoring.dict.impl.FileModuleDict;
import com.sunxung.factoring.dict.impl.ProjectInitiationStatusDict;
import com.sunxung.factoring.entity.GridPage;
import com.sunxung.factoring.entity.acceptance.AcceptanceBasicInfo;
import com.sunxung.factoring.entity.businessmanagement.*;
import com.sunxung.factoring.entity.customerinformation.Customer;
import com.sunxung.factoring.entity.invoicemanage.InvoiceBasicInfo;
import com.sunxung.factoring.entity.project.BusinessAssignee;
import com.sunxung.factoring.entity.project.BusinessProcessingLog;
import com.sunxung.factoring.entity.project.vo.BusinessProcessingTaskVo;
import com.sunxung.factoring.entity.purchcontractmanagement.PurchContractBasicInfo;
import com.sunxung.factoring.entity.purchcontractmanagement.PurchContractManagement;
import com.sunxung.factoring.entity.settlement.SettlementBasicInfo;
import com.sunxung.factoring.entity.sys.Dictionary;
import com.sunxung.factoring.entity.sys.FileStorage;
import com.sunxung.factoring.entity.sys.User;
import com.sunxung.factoring.entity.tradingPlatform.Platform;
import com.sunxung.factoring.entity.underlying.UnderlyingBasicInfo;
import com.sunxung.factoring.entity.vo.ConditionVo;
import com.sunxung.factoring.mapper.businessManagement.BusinessBasicInfoMapper;
import com.sunxung.factoring.mapper.customerinformation.CustomerMapper;
import com.sunxung.factoring.mapper.project.BusinessProcessingLogMapper;
import com.sunxung.factoring.service.acceptancesheet.AcceptanceBasicInfoService;
import com.sunxung.factoring.service.acceptancesheet.AcceptanceGoodsInfoService;
import com.sunxung.factoring.service.businessmanagement.*;
import com.sunxung.factoring.service.invoicemanage.InvoiceBasicInfoService;
import com.sunxung.factoring.service.project.BusinessAssigneeService;
import com.sunxung.factoring.service.project.BusinessProcessingLogService;
import com.sunxung.factoring.service.purchcontractmanagement.PurchContractBasicInfoService;
import com.sunxung.factoring.service.purchcontractmanagement.PurchContractService;
import com.sunxung.factoring.service.salescontractmanagement.ISalesContractPersonInfoService;
import com.sunxung.factoring.service.salescontractmanagement.ICSalesContractBasicInfoService;
import com.sunxung.factoring.service.salescontractmanagement.SalesContractService;
import com.sunxung.factoring.service.settlement.SettlementBasicInfoService;
import com.sunxung.factoring.service.sys.*;
import com.sunxung.factoring.service.sys.dto.AttachmentDto;
import com.sunxung.factoring.service.sys.flowable.FlowableService;
import com.sunxung.factoring.service.tradingPlatform.PlatformService;
import com.sunxung.factoring.service.underlying.UnderlyingBasicInfoService;
import org.apache.commons.lang3.StringUtils;
import org.flowable.bpmn.model.BpmnModel;
import org.flowable.bpmn.model.EndEvent;
import org.flowable.bpmn.model.Process;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.engine.runtime.Execution;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author liutao
 */
@Service
public class BusinessManagementServiceImpl implements BusinessManagementService {

    @Autowired
    private BusinessBasicInfoService businessBasicInfoService;

    @Autowired
    private BusinessSupplierInfoService businessSupplierInfoService;

    @Autowired
    private CustomerMapper customerMapper;

    @Autowired
    private SerialNumberGenerator serialNumberGenerator;

    @Autowired
    private SalesContractService salesContractService;

    @Autowired
    private DictionaryService dictService;

    @Autowired
    private BusinessAssigneeService assigneeService;

    @Autowired
    private UserService userService;

    @Autowired
    private FlowableService flowableService;

    @Autowired
    private ISysAttachmentRefService sysAttachmentRefService;

    @Autowired
    private OrgService orgService;

    @Autowired
    private PlatformService platformService;

    @Autowired
    private BusinessBasicInfoMapper businessBasicInfoMapper;

    @Autowired
    private BusinessTransferRecordInfoService businessTransferRecordInfoService;

    @Autowired
    private AcceptanceBasicInfoService acceptanceBasicInfoService;

    @Autowired
    private AcceptanceGoodsInfoService acceptanceGoodsInfoService;

    @Autowired
    private SettlementBasicInfoService settlementBasicInfoService;

    @Autowired
    private BusinessProcessingLogMapper processingLogMapper;

    @Autowired
    private TaskService taskService;

    @Autowired
    private BusinessProcessingLogService businessProcessingLogService;

    @Autowired
    private InvoiceBasicInfoService invoiceBasicInfoService;

    @Autowired
    private UnderlyingBasicInfoService underlyingBasicInfoService;

    @Autowired
    private PurchContractService purchContractService;

    @Autowired
    private BusinessBasicInfoHistoryService businessBasicInfoHistoryService;

    @Autowired
    private BusinessSupplierInfoHistoryService businessSupplierInfoHistoryService;

    @Autowired
    private ICSalesContractBasicInfoService salesContractBasicInfoService;

    @Autowired
    private BusinessProcessingLogService processingLogService;

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    protected RepositoryService repositoryService;

    @Autowired
    private PurchContractBasicInfoService purchContractBasicInfoService;

    @Autowired
    private IBusinessGuaranteeModeService businessGuaranteeModeService;

    @Autowired
    private IBusinessAwardConfirmService businessAwardConfirmService;

    @Autowired
    private IBusinessRefundDepositConfirmationService businessRefundDepositConfirmationService;

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private ISalesContractPersonInfoService salesContractPersonInfoService;

    /**
     * 新建业务
     *
     * @param businessBasicInfo 业务基本信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(BusinessBasicInfo businessBasicInfo) {
        String businessName = businessBasicInfo.getName();
        List<BusinessBasicInfo> list = businessBasicInfoService.lambdaQuery().eq(BusinessBasicInfo::getName, businessName).list();
        if (CollectionUtil.isNotEmpty(list)) {
            throw new ValidatorException(CodeUtil.FAIL, "业务名称重复，请修改业务名称！！！");
        }

        String businessNumber = serialNumberGenerator.nextValue(ConstantUtil.BUSINESS_CODE);
        //新增业务
        //开启业务流程
    }

    private void startBusinessManagementProcess(BusinessBasicInfo businessBasicInfo) {
        Long odlId = businessBasicInfo.getId();
        //2.新增处理人-- 业务经理、法务专员
        BusinessAssignee projectManager = new BusinessAssignee(businessBasicInfo.getId(), ConstantUtil.BUSINESS_MANAGEMENT);
        projectManager.setAssigneeId(ThreadLocalUtil.getUserId());
        projectManager.setAssigneeType(ConstantUtil.ASSIGNEE_PROJECT_MANAGER);
        assigneeService.add(projectManager);

        List<Long> legalSpecialists = userService.findUserIdByRole(ConstantUtil.LEGAL_SPECIALIST);
        if (legalSpecialists == null || legalSpecialists.size() == 0) {
            throw new ValidatorException(CodeUtil.FAIL, ConstantUtil.LEGAL_SPECIALIST + "角色内无任何用户！");
        }

        //模板审核操作岗  法务专员
        BusinessAssignee legalSpecialist = new BusinessAssignee(businessBasicInfo.getId(), ConstantUtil.BUSINESS_MANAGEMENT);
        legalSpecialist.setCandidateId(StringUtils.join(legalSpecialists, ","));
        legalSpecialist.setAssigneeType(ConstantUtil.ASSIGNEE_LEGAL_SPECIALIST);
        assigneeService.add(legalSpecialist);

        //3.开启流程实例
        Map<String, Object> procVariables = new HashMap<>();
        procVariables.put(ConstantUtil.BUSINESS_ADD_ASSIGNEE,
                assigneeService.getIdByBusiness(businessBasicInfo.getId(), ConstantUtil.BUSINESS_MANAGEMENT, ConstantUtil.ASSIGNEE_PROJECT_MANAGER));
        //查询条件： 请输入业务编号/业务名称/核心企业名称/贸易平台/供应商名称
        List<BusinessSupplierInfo> supplierList = businessSupplierInfoService.getSupplierList(businessBasicInfo.getBusinessNumber());
        Customer customer = customerMapper.selectById(businessBasicInfo.getEnterpriseCustomerInfoId());
        Platform platform = platformService.getById(businessBasicInfo.getTradingPlatformId());
        String queryBusiness = businessBasicInfo.getBusinessNumber() + FlowableUtil.splitChar + businessBasicInfo.getName() +
                FlowableUtil.splitChar + customer.getEnterpriseName() + FlowableUtil.splitChar + platform.getPlatformName() +
                FlowableUtil.splitChar + supplierList.stream().map(r -> r.getSupplierName()).collect(Collectors.joining(FlowableUtil.splitChar));
        ProcessInstance processInst = flowableService.startProcessInstance(businessBasicInfo, procVariables,
                FlowableUtil.generateBusinessKey(businessBasicInfo, ConstantUtil.BUSINESS_MANAGEMENT, queryBusiness), null, ConstantUtil.BUSINESS_MANAGEMENT);
        if (processInst == null) {
            throw new BusinessException(CodeUtil.FAIL, "流程启动失败");
        }
        //完成流程第一步提交验收单，开启下一步法务验收
        String processInstId = processInst.getId();
        Map<String, Object> msgVariables = new HashMap<>();
        Task task = flowableService.findRuntimeTaskByProcessInstId(processInstId).get(0);
        procVariables.put(ConstantUtil.TEMPLATE_REVIEW_CANDIDATE,
                assigneeService.getCandidateByBusiness(businessBasicInfo.getId(), ConstantUtil.BUSINESS_MANAGEMENT, ConstantUtil.ASSIGNEE_LEGAL_SPECIALIST));
        msgVariables.put(ConstantUtil.FLOWABLE_MSG_TITLE, "业务编号：" + businessBasicInfo.getBusinessNumber());
        msgVariables.put(ConstantUtil.FLOWABLE_MSG_CONTENT,
                "业务编号为“" + businessBasicInfo.getBusinessNumber() + "”的业务已进入“"
                        + ConstantConversionUtil.flowBusinessKeyNames.get(ConstantUtil.BUSINESS_MANAGEMENT) + "—模板审核阶段，"
                        + ConstantUtil.FLOWABLE_MSG_ASSIGNEE);
        Long historyId = addHistoryBusiness(businessBasicInfo);
        businessBasicInfo.setId(odlId);
        if (businessBasicInfo.getBidding().equals(1)) {
            procVariables.put("result", ConstantUtil.BIDDING);
        } else if (businessBasicInfo.getBidding().equals(0)) {
            procVariables.put("result", ConstantUtil.NOT_BIDDING);
            //不招投标的话直接开启销售合同流程
//            salesContractBasicInfoService.startSalesContractProcess(businessBasicInfo, businessBasicInfo.getBusinessNumber());
        } else {
            throw new ValidatorException(CodeUtil.FAIL, "是否招投标必选！！！！");
        }
        flowableService.completeMyTask(task.getId(), businessBasicInfo, procVariables, null, historyId, msgVariables, ConstantUtil.BUSINESS_MANAGEMENT, legalSpecialists);
    }

    private Long addHistoryBusiness(BusinessBasicInfo businessBasicInfo) {
        Long oldId = businessBasicInfo.getId();
        String businessNumber = businessBasicInfoService.get(oldId).getBusinessNumber();
        Long managerId = businessBasicInfoService.get(oldId).getManagerId();
        //保存基础信息
        BusinessBasicInfoHistory history = new BusinessBasicInfoHistory();
        BeanUtils.copyProperties(businessBasicInfo, history, "id");
        history.setBusinessNumber(businessNumber);
        history.setManagerId(managerId);
        history.setBusinessBasicInfoId(businessBasicInfo.getId());
        businessBasicInfoHistoryService.save(history);
        //保存供应商信息
        List<BusinessSupplierInfo> suppliers =
                businessSupplierInfoService.list(new QueryWrapper<BusinessSupplierInfo>().eq("business_basic_info_id", oldId));
        suppliers.forEach(businessSupplierInfo -> {
            BusinessSupplierInfoHistory businessSupplierInfoHistory = new BusinessSupplierInfoHistory();
            BeanUtils.copyProperties(businessSupplierInfo, businessSupplierInfoHistory, "id", "business_basic_info_id");
            businessSupplierInfoHistory.setBusinessBasicInfoId(history.getId());
            businessSupplierInfoHistoryService.save(businessSupplierInfoHistory);
        });
        //上传附件
//        AttachmentDto attachmentDto = AttachmentDto.builder()
//                .setEntityId(businessBasicInfo.getId())
//                .setChildEnum(FileModuleDict.ChildEnum.BIDDING_FILE)
//                .build();
//        List<FileStorage> files = sysAttachmentRefService.getFiles(attachmentDto);
//        AttachmentDto attachmentDtoHis = AttachmentDto.builder()
//                .setEntityId(history.getId())
//                .setChildEnum(FileModuleDict.ChildEnum.BIDDING_HIS_FILE)
//                .build();
//        sysAttachmentRefService.saveFileAndRefHis(files, attachmentDtoHis);
        return history.getId();
    }


    /**
     * 修改业务
     *
     * @param businessBasicInfo 业务基本信息
     * @throws IOException
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(BusinessBasicInfo businessBasicInfo) {
        businessBasicInfo.setStage(dictService.getByCode(BusinessStageDict.ChildEnum.TEMPLATE_REVIEW.getCode()).getId());
        String businessName = businessBasicInfo.getName();
        List<BusinessBasicInfo> businessBasicInfos = businessBasicInfoService.lambdaQuery().eq(BusinessBasicInfo::getName, businessName).list();
        if (CollectionUtil.isNotEmpty(businessBasicInfos)) {
            if (businessBasicInfos.size() > 1) {
                throw new ValidatorException(CodeUtil.FAIL, "业务名称重复，请修改业务名称！！！");
            } else {
                BusinessBasicInfo exist = businessBasicInfos.get(0);
                if (!exist.getId().equals(businessBasicInfo.getId())) {
                    throw new ValidatorException(CodeUtil.FAIL, "业务名称重复，请修改业务名称！！！");
                }
            }
        }
        businessBasicInfo.setManagerId(ThreadLocalUtil.getUserId());
        //删除原来供应商
        businessSupplierInfoService.remove(new LambdaQueryWrapper<BusinessSupplierInfo>().eq(BusinessSupplierInfo::getBusinessBasicInfoId, businessBasicInfo.getId()));
        //保存新供应商
        if (CollectionUtil.isNotEmpty(businessBasicInfo.getBusinessSupplierInfos())) {
            List<BusinessSupplierInfo> businessSupplierInfos = businessBasicInfo.getBusinessSupplierInfos();
            Set<Long> set = businessSupplierInfos.stream().map(r -> r.getSupplierId()).collect(Collectors.toSet());
            List<Long> list = businessSupplierInfos.stream().map(r -> r.getSupplierId()).collect(Collectors.toList());
            if (list.size() > set.size()) {
                throw new ValidatorException(CodeUtil.FAIL, "不能添加相同的供应商！");
            }
            businessSupplierInfos.forEach(businessSupplierInfo -> {
                Customer customer = customerMapper.selectById(businessSupplierInfo.getSupplierId());
                businessSupplierInfo.setSupplierName(customer.getEnterpriseName());
                businessSupplierInfo.setBusinessBasicInfoId(businessBasicInfo.getId());
                businessSupplierInfoService.save(businessSupplierInfo);
            });
        }
        AttachmentDto attachmentDto = AttachmentDto.builder()
                .setEntityId(businessBasicInfo.getId())
                .setChildEnum(FileModuleDict.ChildEnum.BIDDING_HIS_FILE)
                .build();
        List<FileStorage> files = sysAttachmentRefService.getFiles(attachmentDto);
        List<Long> fileList = businessBasicInfo.getFileStorage().stream().map(r -> r.getId()).collect(Collectors.toList());
        List deleteIds = new ArrayList<>();
        List addIds = new ArrayList<>();
        files.forEach(r -> {
            boolean contains = fileList.contains(r.getId());
            if (!contains) {
                deleteIds.add(r.getId());
            }
        });
        //删除原文件
        sysAttachmentRefService.removeFilestorageAndRef(deleteIds);
        fileList.forEach(r -> {
            boolean anyMatch = files.stream().anyMatch(fileStorage -> fileStorage.getId().equals(r));
            if (!anyMatch) {
                addIds.add(r);
            }
        });
        //新增文件
        sysAttachmentRefService.saveRef(addIds, attachmentDto);
        Long odlId = businessBasicInfo.getId();
        //完成审核流程流转到下一流程或者完成流程
        Map<String, Object> msgVariables = new HashMap<>();
        msgVariables.put(ConstantUtil.FLOWABLE_MSG_TITLE, "业务编号：" + businessBasicInfo.getBusinessNumber());
        msgVariables.put(ConstantUtil.FLOWABLE_MSG_CONTENT,
                "业务编号为“" + businessBasicInfo.getBusinessNumber() + "”的业务已进入“"
                        + ConstantConversionUtil.flowBusinessKeyNames.get(ConstantUtil.BUSINESS_MANAGEMENT) + "—模板审核阶段，"
                        + ConstantUtil.FLOWABLE_MSG_ASSIGNEE);
        Long historyId = addHistoryBusiness(businessBasicInfo);
        businessBasicInfo.setId(odlId);
        Map<String, Object> procVariables = new HashMap<>();
        String result;
        if (businessBasicInfo.getBidding().equals(1)) {
            result = ConstantUtil.BIDDING;
            businessBasicInfo.setStage(dictService.getByCode(BusinessStageDict.ChildEnum.TEMPLATE_REVIEW.getCode()).getId());
            businessBasicInfo.setStatusDic(dictService.getByCode(ProjectInitiationStatusDict.ChildEnum.PROCESSING.getCode()).getId());
            //保存业务管理基本信息
            businessBasicInfoService.updateById(businessBasicInfo);
        } else if (businessBasicInfo.getBidding().equals(0)) {
            result = ConstantUtil.NOT_BIDDING;
            //不招投标的话直接开启销售合同流程
            businessBasicInfo.setStage(dictService.getByCode(BusinessStageDict.ChildEnum.EMPTY.getCode()).getId());
            businessBasicInfo.setStatusDic(dictService.getByCode(ProjectInitiationStatusDict.ChildEnum.COMPLETED.getCode()).getId());
            //保存业务管理基本信息
            businessBasicInfoService.updateById(businessBasicInfo);
//            salesContractBasicInfoService.startSalesContractProcess(businessBasicInfo, businessBasicInfo.getBusinessNumber());
        } else {
            throw new ValidatorException(CodeUtil.FAIL, "是否招投标必选！！！！");
        }
        procVariables.put("result", result);
        List<Long> legalSpecialists = userService.findUserIdByRole(ConstantUtil.LEGAL_SPECIALIST);
        if (legalSpecialists == null || legalSpecialists.size() == 0) {
            throw new ValidatorException(CodeUtil.FAIL, ConstantUtil.LEGAL_SPECIALIST + "角色内无任何用户！");
        }
        flowableService.completeMyTask(businessBasicInfo.getTaskId(), businessBasicInfo, procVariables, null, historyId, msgVariables, ConstantUtil.BUSINESS_MANAGEMENT, legalSpecialists);
    }

    /**
     * 根据业务Id查询详情
     *
     * @param businessBasicInfoId 业务基本信息
     * @return 需要查询的业务信息
     */
    @Override
    public BusinessBasicInfo findDetail(long businessBasicInfoId) {
        //业务基础信息
        BusinessBasicInfo businessBasicInfo = businessBasicInfoService.getById(businessBasicInfoId);
        //保存供应商信息
        List<BusinessSupplierInfo> businessSupplierInfos = businessSupplierInfoService.list(new LambdaQueryWrapper<BusinessSupplierInfo>().eq(BusinessSupplierInfo::getBusinessBasicInfoId, businessBasicInfoId));
        businessBasicInfo.setBusinessSupplierInfos(businessSupplierInfos);
        //上传附件
        AttachmentDto attachmentDto = AttachmentDto.builder()
                .setEntityId(businessBasicInfo.getId())
                .setChildEnum(FileModuleDict.ChildEnum.BIDDING_HIS_FILE)
                .build();
        List<FileStorage> files = sysAttachmentRefService.getFiles(attachmentDto);
        businessBasicInfo.setFileStorage(files);
        businessBasicInfo.setUserName(userService.get(businessBasicInfo.getManagerId()).getName());
        return businessBasicInfo;
    }

    @Override
    public List<BusinessBasicInfo> getLocalUserBusinessList(Long supplierId, Long customerId, String businessName) {
        Long userId = ThreadLocalUtil.getUserId();
        User user = ThreadLocalUtil.getUser();
        List<Long> orgIdList = user.getOrgIdList();
        List<BusinessBasicInfo> list = new ArrayList<>();
        list.add(new BusinessBasicInfo("请选择业务编号"));
        //供应商登录  只有自己一个选项
        if (orgIdList.contains(orgService.getByCode(ConstantUtil.SUPPLIER).getId())) {
            list.addAll(businessBasicInfoMapper.getLocalSupplierBusinessList(customerId, supplierId));
        } else {
            list.addAll(businessBasicInfoMapper.getLocalUserBusinessList(supplierId, customerId, userId, businessName));
        }
        return list;
    }

    @Override
    public List<BusinessBasicInfo> getLocalUserBusinessNameList(Long supplierId, Long customerId, String name) {
        Long userId = ThreadLocalUtil.getUserId();
        User user = ThreadLocalUtil.getUser();
        List<Long> orgIdList = user.getOrgIdList();
        List<BusinessBasicInfo> list = new ArrayList<>();
        //供应商登录  只有自己一个选项
        if (orgIdList.contains(orgService.getByCode(ConstantUtil.SUPPLIER).getId())) {
            list.addAll(businessBasicInfoMapper.getLocalSupplierBusinessList(customerId, supplierId));
        } else {
            list.addAll(businessBasicInfoMapper.getLocalUserBusinessList(supplierId, customerId, userId ,name));
        }
//        if (list != null && list.size() > 0) {
//            BusinessSupplierInfo businessSupplierInfo = new BusinessSupplierInfo();
//            for (BusinessBasicInfo basicInfo : list) {
//                businessSupplierInfo.setBusinessBasicInfoId(basicInfo.getId());
//                businessSupplierInfo.setSupplierId(supplierId);
//                List<PurchContractBuyerSeller> purchContractBuyerSellers = purchContractService.findByBusinessInfo(businessSupplierInfo);
//                if (CollectionUtil.isNotEmpty(purchContractBuyerSellers)) {
//                    String buyerSeller = purchContractBuyerSellers.stream().map(PurchContractBuyerSeller::getName).collect(Collectors.joining(","));
//                    basicInfo.setSellerName(buyerSeller);
//                }
//                SalesContractBasicInfo salesContractBasicInfo = salesContractService.findByBusinessNumber(basicInfo.getBusinessNumber());
//                if (salesContractBasicInfo != null) {
//                    basicInfo.setCheckOperator(salesContractBasicInfo.getCheckOperator());
//                    List<SalesContractPersonInfo> contractPersonInfos = salesContractPersonInfoService.lambdaQuery().eq(SalesContractPersonInfo::getSalesContractBasicInfoId, salesContractBasicInfo.getId()).eq(SalesContractPersonInfo::getType, "结算经办人").list();
//                    String names = contractPersonInfos.stream().map(r -> r.getName()).collect(Collectors.joining(","));
//                    basicInfo.setSettlementOperator(names);
//                }
//                Platform plateform = platformService.getPlateformByBusiness(basicInfo.getBusinessNumber());
//                basicInfo.setTradingPlatformName(plateform.getPlatformName());
//            }
//        }
        BusinessBasicInfo basicInfo = new BusinessBasicInfo();
        basicInfo.setBusinessName("请选择业务名称");
        list.add(0, basicInfo);

        return list;
    }

    @Override
    public List<BusinessBasicInfo> getBusinessListByCustomer(Long customerId) {
        Long userId = ThreadLocalUtil.getUserId();
        List<BusinessBasicInfo> list = new ArrayList<>();
        list.add(new BusinessBasicInfo("请选择业务"));
        List<BusinessBasicInfo> businessList = businessBasicInfoService.getBusinessListByCustomer(userId, customerId);
        list.addAll(businessList);
        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void transferAssignee(Long businessBasicInfoId, Long userId) {
        //业务的移交 移交记录的保存
        BusinessBasicInfo businessBasicInfo = businessBasicInfoService.getById(businessBasicInfoId);
        BusinessTransferRecordInfo businessTransferRecordInfo = new BusinessTransferRecordInfo();
        businessTransferRecordInfo.setTransferId(businessBasicInfo.getManagerId());
        businessTransferRecordInfo.setReceiverId(userId);
        businessTransferRecordInfo.setBussinessBasicInfoId(businessBasicInfo.getId());
        businessBasicInfo.setManagerId(userId);
        businessBasicInfoMapper.updateById(businessBasicInfo);
        businessTransferRecordInfoService.save(businessTransferRecordInfo);
        //业务的移交
        businessBasicInfoTransfer(businessBasicInfo, userId);
        //移交该业务下所有未完成的销售合同
//        salesContractTransfer(businessBasicInfo.getBusinessNumber(), userId);
        //移交该业务下所有未完成的采购合同
        purchContractTransfer(businessBasicInfo.getBusinessNumber(), userId);
        //移交该业务下所有未完成的验收单
        acceptanceTransfer(businessBasicInfo.getBusinessNumber(), userId);
        //移交该业务下所有未完成的结算单
        settlementTransfer(businessBasicInfo.getBusinessNumber(), userId);
        //移交该业务下所有未完成的底层
        underlyingTransfer(businessBasicInfo.getBusinessNumber(), userId);
        //移交该业务下所有未完成的发票
        invoiceTransfer(businessBasicInfo.getBusinessNumber(), userId);
    }

    private void businessBasicInfoTransfer(BusinessBasicInfo businessBasicInfo, Long userId) {


        List<BusinessProcessingLog> businessProcessingLogs = businessProcessingLogService.listForNullValueOfEndTime(businessBasicInfo.getId(), ConstantUtil.BUSINESS_MANAGEMENT);
        if (CollectionUtil.isNotEmpty(businessProcessingLogs)) {
            for (BusinessProcessingLog businessProcessingLog : businessProcessingLogs) {
                taskService.setVariable(businessProcessingLog.getHistoricTaskId(), ConstantUtil.BUSINESS_ADD_ASSIGNEE, String.valueOf(userId));
                taskService.setVariable(businessProcessingLog.getHistoricTaskId(), ConstantUtil.GUARANTEE_METHOD_CONFIRM_ASSIGNEE, String.valueOf(userId));
                taskService.setVariable(businessProcessingLog.getHistoricTaskId(), ConstantUtil.AWARD_CONFIRM_ASSIGNEE, String.valueOf(userId));
                taskService.setVariable(businessProcessingLog.getHistoricTaskId(), ConstantUtil.REFUND_DEPOSIT_CONFIRM_ASSIGNEE, String.valueOf(userId));
                //修改business_assignee
                BusinessAssignee businessAssignee = assigneeService.getByBusiness(businessBasicInfo.getId(), ConstantUtil.BUSINESS_MANAGEMENT, ConstantUtil.ASSIGNEE_PROJECT_MANAGER);
                businessAssignee.setAssigneeId(userId);
                assigneeService.update(businessAssignee);
                if (businessProcessingLog.getTaskDefKey().equals(ConstantUtil.GUARANTEE_METHOD_CONFIRM_ASSIGNEE.replace(ConstantUtil.ASSIGNEE, ""))
                        || businessProcessingLog.getTaskDefKey().equals(ConstantUtil.BUSINESS_ADD_ASSIGNEE.replace(ConstantUtil.ASSIGNEE, ""))
                        || businessProcessingLog.getTaskDefKey().equals(ConstantUtil.AWARD_CONFIRM_ASSIGNEE.replace(ConstantUtil.ASSIGNEE, ""))
                        || businessProcessingLog.getTaskDefKey().equals(ConstantUtil.REFUND_DEPOSIT_CONFIRM_ASSIGNEE.replace(ConstantUtil.ASSIGNEE, ""))) {
                    taskService.setAssignee(businessProcessingLog.getHistoricTaskId(), String.valueOf(userId));
                    taskService.setOwner(businessProcessingLog.getHistoricTaskId(), String.valueOf(userId));
                    businessProcessingLog.setAssignee(userService.get(userId));
                    processingLogMapper.updateAssigneeId(businessProcessingLog);
                }
            }
        }
        //历史记录修改业务经理
        List<BusinessBasicInfoHistory> list = businessBasicInfoHistoryService.lambdaQuery().eq(BusinessBasicInfoHistory::getBusinessNumber, businessBasicInfo.getBusinessNumber()).list();
        list.forEach(r -> {
            r.setManagerId(userId);
            businessBasicInfoHistoryService.updateById(r);
        });
    }

    @Override
    public List<BusinessBasicInfo> getLocalUserBusinessListByAcceptance(Long supplierId, Long customerId, String businessName) {
        Long userId = ThreadLocalUtil.getUserId();
        User user = ThreadLocalUtil.getUser();
        List<Long> orgIdList = user.getOrgIdList();
        List<BusinessBasicInfo> list = new ArrayList<>();
        //供应商登录  只有自己一个选项
        if (orgIdList.contains(orgService.getByCode(ConstantUtil.SUPPLIER).getId())) {
            list.addAll(businessBasicInfoMapper.getLocalSupplierBusinessListByAcceptance(customerId, supplierId));
        } else {
            list.addAll(businessBasicInfoMapper.getLocalUserBusinessListByAcceptance(supplierId, customerId, userId,businessName));
        }
        list.stream().forEach(b -> {
            PurchContractBasicInfo purchContractBasicInfo = purchContractBasicInfoService.findByBusinessNumberAndSupplierId(b.getBusinessNumber(), supplierId);
            b.setPurchContractBasicInfo(purchContractBasicInfo);
        });
        BusinessBasicInfo businessBasicInfo = new BusinessBasicInfo();
        businessBasicInfo.setBusinessName("请选择业务名称");
        list.add(0, businessBasicInfo);
        return list;
    }

    @Override
    public List<BusinessBasicInfo> getBusinessListByCustomerInvoice(Long customerId) {
        Long userId = ThreadLocalUtil.getUserId();
        List<BusinessBasicInfo> list = new ArrayList<>();
        BusinessBasicInfo business = new BusinessBasicInfo("请选择业务");
        business.setBusinessName("请选择业务名称");
        list.add(business);
        List<BusinessBasicInfo> businessList = businessBasicInfoService.getBusinessListByCustomerInvoice(userId, customerId);
        list.addAll(businessList);
        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long businessBasicInfoId) {
        BusinessBasicInfo businessBasicInfo = businessBasicInfoService.get(businessBasicInfoId);
        Dictionary stage = dictService.get(businessBasicInfo.getStage());
        Dictionary status = dictService.get(businessBasicInfo.getStatusDic());
        if (stage.getCode().equals(BusinessStageDict.ChildEnum.CREATE.getCode())) {
            //终止在途业务流程
            stopProcess(businessBasicInfoId, ConstantUtil.BUSINESS_MANAGEMENT);
        } else if (status.getCode().equals(ProjectInitiationStatusDict.ChildEnum.COMPLETED.getCode()) &&
                stage.getCode().equals(BusinessStageDict.ChildEnum.EMPTY.getCode())) {
//            SalesContractManagement salesContractManagement = salesContractService.getByBusinessNumber(businessBasicInfo.getBusinessNumber());
//            Dictionary contractStatus = dictService.get(salesContractManagement.getContractStatus());
//            if (contractStatus.getCode().equals(SalesContractStatusDict.ChildEnum.CREATE.getCode()) || contractStatus.getCode().equals(SalesContractStatusDict.ChildEnum.OVERRULE.getCode())) {
//                //终止在途销售合同流程
//                stopProcess(salesContractManagement.getId(), ConstantUtil.SALES_CONTRACT);
//                //删除销售合同
//                salesContractService.removeById(salesContractManagement.getId());
//            } else {
//                throw new ValidatorException(CodeUtil.FAIL, "该业务存在流程中销售合同，无法删除");
//            }
        } else {
            throw new ValidatorException(CodeUtil.FAIL, "该业务无法删除");
        }
        //删除业务
        businessBasicInfoService.removeById(businessBasicInfoId);
    }

    private void stopProcess(Long businessKey, String businessType) {
        //查询日志信息
        List<BusinessProcessingLog> businessProcessingLogs = processingLogService.listForNullValueOfEndTime(businessKey, businessType);
        if (businessProcessingLogs != null && businessProcessingLogs.size() > 0) {
            Set<String> historyTaskId = businessProcessingLogs.stream().map(r -> r.getHistoricTaskId()).collect(Collectors.toSet());
            historyTaskId.forEach(taskId -> {
                String existTaskId = null;
                for (BusinessProcessingLog businessProcessingLog : businessProcessingLogs) {
                    if (taskId.equals(businessProcessingLog.getHistoricTaskId()) && (existTaskId == null || !existTaskId.equals(businessProcessingLog.getHistoricTaskId()))) {
                        existTaskId = businessProcessingLog.getHistoricTaskId();
                        //是否存在task
                        Boolean flag = flowableService.existTask(businessProcessingLog.getHistoricTaskId());
                        if (flag) {
                            String procInstId = taskService.createTaskQuery().taskId(businessProcessingLog.getHistoricTaskId()).singleResult().getProcessInstanceId();
                            ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(procInstId).singleResult();
                            if (processInstance != null) {
                                List<EndEvent> endNodes;
                                BpmnModel bpmnModel = repositoryService.getBpmnModel(processInstance.getProcessDefinitionId());
                                if (bpmnModel != null) {
                                    Process mainProcess = bpmnModel.getMainProcess();
                                    endNodes = mainProcess.findFlowElementsOfType(EndEvent.class);
                                } else {
                                    throw new BusinessException(CodeUtil.FAIL, "终止失败");
                                }
                                String endId = endNodes.get(0).getId();
                                String processInstanceId = processInstance.getProcessInstanceId();
                                //执行终止
                                List<Execution> executions = runtimeService.createExecutionQuery().parentId(processInstanceId).list();
                                List<String> executionIds = new ArrayList<>();
                                executions.forEach(execution -> executionIds.add(execution.getId()));
                                runtimeService.createChangeActivityStateBuilder().moveExecutionsToSingleActivityId(executionIds, endId).changeState();
                            }
                        }
                    }
                }
            });
        }
    }

    private void purchContractTransfer(String businessNumber, Long userId) {
        List<PurchContractManagement> purchContractManagements = purchContractService.lambdaQuery().eq(PurchContractManagement::getBusinessNumber, businessNumber).list();
        if (CollectionUtil.isNotEmpty(purchContractManagements)) {
            for (PurchContractManagement purchContractManagement : purchContractManagements) {
                List<BusinessProcessingLog> businessProcessingLogs = businessProcessingLogService.listForNullValueOfEndTime(purchContractManagement.getId(), ConstantUtil.PURCH_CONTRACT);
                List<BusinessProcessingLog> changeLogs = businessProcessingLogService.listForNullValueOfEndTime(purchContractManagement.getId(), ConstantUtil.PURCH_CONTRACT_CHANGE_PROCESS);
                if (CollectionUtil.isNotEmpty(businessProcessingLogs)) {
                    for (BusinessProcessingLog businessProcessingLog : businessProcessingLogs) {
                        taskService.setVariable(businessProcessingLog.getHistoricTaskId(), ConstantUtil.PURCH_CONTRACT_CREATE + ConstantUtil.ASSIGNEE, String.valueOf(userId));
                        taskService.setVariable(businessProcessingLog.getHistoricTaskId(), ConstantUtil.PURCH_CONTRACT_UNDERLINE_CONFIRM + ConstantUtil.ASSIGNEE, String.valueOf(userId));
                        //修改business_assignee
                        BusinessAssignee businessAssignee = assigneeService.getByBusiness(purchContractManagement.getId(), ConstantUtil.PURCH_CONTRACT, ConstantUtil.ASSIGNEE_PROJECT_MANAGER);
                        businessAssignee.setAssigneeId(userId);
                        assigneeService.update(businessAssignee);
                        if (businessProcessingLog.getTaskDefKey().equals(ConstantUtil.PURCH_CONTRACT_CREATE) || businessProcessingLog.getTaskDefKey().equals(ConstantUtil.PURCH_CONTRACT_UNDERLINE_CONFIRM)) {
                            taskService.setAssignee(businessProcessingLog.getHistoricTaskId(), String.valueOf(userId));
                            taskService.setOwner(businessProcessingLog.getHistoricTaskId(), String.valueOf(userId));
                            businessProcessingLog.setAssignee(userService.get(userId));
                            processingLogMapper.updateAssigneeId(businessProcessingLog);
                        }
                    }
                }
                if (CollectionUtil.isNotEmpty(changeLogs)) {
                    for (BusinessProcessingLog businessProcessingLog : changeLogs) {
                        taskService.setVariable(businessProcessingLog.getHistoricTaskId(), ConstantUtil.PURCH_CONTRACT_CHANGE + ConstantUtil.ASSIGNEE, String.valueOf(userId));
                        taskService.setVariable(businessProcessingLog.getHistoricTaskId(), ConstantUtil.PURCH_CONTRACT_CHANGE_SIGN_CONFIRM_UNDERLINE + ConstantUtil.ASSIGNEE, String.valueOf(userId));
                        //修改business_assignee
                        BusinessAssignee businessAssignee = assigneeService.getByBusiness(purchContractManagement.getId(), ConstantUtil.PURCH_CONTRACT_CHANGE_PROCESS, ConstantUtil.ASSIGNEE_PROJECT_MANAGER);
                        businessAssignee.setAssigneeId(userId);
                        assigneeService.update(businessAssignee);
                        if (businessProcessingLog.getTaskDefKey().equals(ConstantUtil.PURCH_CONTRACT_CHANGE) || businessProcessingLog.getTaskDefKey().equals(ConstantUtil.PURCH_CONTRACT_CHANGE_SIGN_CONFIRM_UNDERLINE)) {
                            taskService.setAssignee(businessProcessingLog.getHistoricTaskId(), String.valueOf(userId));
                            taskService.setOwner(businessProcessingLog.getHistoricTaskId(), String.valueOf(userId));
                            businessProcessingLog.setAssignee(userService.get(userId));
                            processingLogMapper.updateAssigneeId(businessProcessingLog);
                        }
                    }
                }
            }
        }
    }

//    private void salesContractTransfer(String businessNumber, Long userId) {
//        SalesContractManagement salesContractManagement = salesContractService.getByBusinessNumber(businessNumber);
//        if (salesContractManagement != null) {
//            List<BusinessProcessingLog> businessProcessingLogs = businessProcessingLogService.listForNullValueOfEndTime(salesContractManagement.getId(), ConstantUtil.SALES_CONTRACT);
//            List<BusinessProcessingLog> changeLogs = businessProcessingLogService.listForNullValueOfEndTime(salesContractManagement.getId(), ConstantUtil.SALES_CONTRACT_CHANGE_PROCESS);
//            if (CollectionUtil.isNotEmpty(businessProcessingLogs)) {
//                for (BusinessProcessingLog businessProcessingLog : businessProcessingLogs) {
//                    taskService.setVariable(businessProcessingLog.getHistoricTaskId(), ConstantUtil.SALES_CONTRACT_CREATE + ConstantUtil.ASSIGNEE, String.valueOf(userId));
//                    //修改business_assignee
//                    BusinessAssignee businessAssignee = assigneeService.getByBusiness(salesContractManagement.getId(), ConstantUtil.SALES_CONTRACT, ConstantUtil.ASSIGNEE_PROJECT_MANAGER);
//                    businessAssignee.setAssigneeId(userId);
//                    assigneeService.update(businessAssignee);
//                    if (businessProcessingLog.getTaskDefKey().equals(ConstantUtil.SALES_CONTRACT_CREATE)) {
//                        taskService.setAssignee(businessProcessingLog.getHistoricTaskId(), String.valueOf(userId));
//                        taskService.setOwner(businessProcessingLog.getHistoricTaskId(), String.valueOf(userId));
//                        businessProcessingLog.setAssignee(userService.get(userId));
//                        processingLogMapper.updateAssigneeId(businessProcessingLog);
//                    }
//                }
//            }
//            if (CollectionUtil.isNotEmpty(changeLogs)) {
//                for (BusinessProcessingLog businessProcessingLog : changeLogs) {
//                    taskService.setVariable(businessProcessingLog.getHistoricTaskId(), ConstantUtil.SALES_CONTRACT_CHANGE + ConstantUtil.ASSIGNEE, String.valueOf(userId));
//                    //修改business_assignee
//                    BusinessAssignee businessAssignee = assigneeService.getByBusiness(salesContractManagement.getId(), ConstantUtil.SALES_CONTRACT_CHANGE_PROCESS, ConstantUtil.ASSIGNEE_PROJECT_MANAGER);
//                    businessAssignee.setAssigneeId(userId);
//                    assigneeService.update(businessAssignee);
//                    if (businessProcessingLog.getTaskDefKey().equals(ConstantUtil.SALES_CONTRACT_CHANGE)) {
//                        taskService.setAssignee(businessProcessingLog.getHistoricTaskId(), String.valueOf(userId));
//                        taskService.setOwner(businessProcessingLog.getHistoricTaskId(), String.valueOf(userId));
//                        businessProcessingLog.setAssignee(userService.get(userId));
//                        processingLogMapper.updateAssigneeId(businessProcessingLog);
//                    }
//                }
//            }
//        }
//    }

    private void underlyingTransfer(String businessNumber, Long userId) {
        List<UnderlyingBasicInfo> underlyingAudiList = underlyingBasicInfoService.lambdaQuery().eq(UnderlyingBasicInfo::getBusinessNumber, businessNumber).list();
        if (CollectionUtil.isNotEmpty(underlyingAudiList)) {
            for (UnderlyingBasicInfo underlyingBasicInfo : underlyingAudiList) {
                List<BusinessProcessingLog> businessProcessingLogs = businessProcessingLogService.listForNullValueOfEndTime(underlyingBasicInfo.getId(), "UnderlyingManage");
                if (CollectionUtil.isNotEmpty(businessProcessingLogs)) {
                    for (BusinessProcessingLog businessProcessingLog : businessProcessingLogs) {
                        taskService.setVariable(businessProcessingLog.getHistoricTaskId(), ConstantUtil.UNDERLYING_CREATE_ASSIGNEE, String.valueOf(userId));
                        //修改business_assignee
                        BusinessAssignee businessAssignee = assigneeService.getByBusiness(underlyingBasicInfo.getId(), ConstantUtil.UNDERLYING_MANAGE, ConstantUtil.ASSIGNEE_PROJECT_MANAGER);
                        businessAssignee.setAssigneeId(userId);
                        assigneeService.update(businessAssignee);
                        if (businessProcessingLog.getTaskDefKey().equals(ConstantUtil.UNDERLYING_CREATE_ASSIGNEE.replace(ConstantUtil.ASSIGNEE, ""))) {
                            taskService.setAssignee(businessProcessingLog.getHistoricTaskId(), String.valueOf(userId));
                            taskService.setOwner(businessProcessingLog.getHistoricTaskId(), String.valueOf(userId));
                            businessProcessingLog.setAssignee(userService.get(userId));
                            processingLogMapper.updateAssigneeId(businessProcessingLog);
                        }
                    }
                }
            }
        }
    }

    private void invoiceTransfer(String businessNumber, Long userId) {
        List<InvoiceBasicInfo> invoiceAudiList = invoiceBasicInfoService.lambdaQuery().eq(InvoiceBasicInfo::getBusinessNumber, businessNumber).list();
        if (CollectionUtil.isNotEmpty(invoiceAudiList)) {
            for (InvoiceBasicInfo invoiceBasicInfo : invoiceAudiList) {
                List<BusinessProcessingLog> businessProcessingLogs = businessProcessingLogService.listForNullValueOfEndTime(invoiceBasicInfo.getId(), "invoiceManager");
                if (CollectionUtil.isNotEmpty(businessProcessingLogs)) {
                    for (BusinessProcessingLog businessProcessingLog : businessProcessingLogs) {
                        taskService.setVariable(businessProcessingLog.getHistoricTaskId(), ConstantUtil.SALE_INVOICE_CREATE + ConstantUtil.ASSIGNEE, String.valueOf(userId));
                        //修改business_assignee
                        BusinessAssignee businessAssignee = assigneeService.getByBusiness(invoiceBasicInfo.getId(), ConstantUtil.INVOICE, ConstantUtil.ASSIGNEE_PROJECT_MANAGER);
                        businessAssignee.setAssigneeId(userId);
                        assigneeService.update(businessAssignee);
                        if (businessProcessingLog.getTaskDefKey().equals(ConstantUtil.SALE_INVOICE_CREATE)) {
                            taskService.setAssignee(businessProcessingLog.getHistoricTaskId(), String.valueOf(userId));
                            taskService.setOwner(businessProcessingLog.getHistoricTaskId(), String.valueOf(userId));
                            businessProcessingLog.setAssignee(userService.get(userId));
                            processingLogMapper.updateAssigneeId(businessProcessingLog);
                        }
                    }
                }
            }
        }
    }

    private void settlementTransfer(String businessNumber, Long userId) {
        List<SettlementBasicInfo> settlementBasicInfos = settlementBasicInfoService.lambdaQuery().eq(SettlementBasicInfo::getBusinessNumber, businessNumber).list();
        if (CollectionUtil.isNotEmpty(settlementBasicInfos)) {
            for (SettlementBasicInfo settlementBasicInfo : settlementBasicInfos) {
                List<BusinessProcessingLog> businessProcessingLogs = businessProcessingLogService.listForNullValueOfEndTime(settlementBasicInfo.getId(), ConstantUtil.BILL_BASIC_INFORMATION);
                if (CollectionUtil.isNotEmpty(businessProcessingLogs)) {
                    for (BusinessProcessingLog businessProcessingLog : businessProcessingLogs) {
                        taskService.setVariable(businessProcessingLog.getHistoricTaskId(), ConstantUtil.BILL_ASSIGNEE, String.valueOf(userId));
                        //修改business_assignee
                        BusinessAssignee businessAssignee = assigneeService.getByBusiness(settlementBasicInfo.getId(), ConstantUtil.BILL_BASIC_INFORMATION, ConstantUtil.ASSIGNEE_PROJECT_MANAGER);
                        businessAssignee.setAssigneeId(userId);
                        assigneeService.update(businessAssignee);
                        if (businessProcessingLog.getTaskDefKey().equals("bill_create")) {
                            taskService.setAssignee(businessProcessingLog.getHistoricTaskId(), String.valueOf(userId));
                            taskService.setOwner(businessProcessingLog.getHistoricTaskId(), String.valueOf(userId));
                            businessProcessingLog.setAssignee(userService.get(userId));
                            processingLogMapper.updateAssigneeId(businessProcessingLog);
                        }
                    }
                }
            }
        }
    }

    private void acceptanceTransfer(String businessNumber, Long userId) {
        List<AcceptanceBasicInfo> acceptanceBasicInfos = acceptanceBasicInfoService.lambdaQuery().eq(AcceptanceBasicInfo::getBusinessNumber, businessNumber).list();
        if (CollectionUtil.isNotEmpty(acceptanceBasicInfos)) {
            for (AcceptanceBasicInfo acceptanceBasicInfo : acceptanceBasicInfos) {
                List<BusinessProcessingLog> businessProcessingLogs = businessProcessingLogService.listForNullValueOfEndTime(acceptanceBasicInfo.getId(), ConstantUtil.ACCEPTANCE_SHEET);
                if (CollectionUtil.isNotEmpty(businessProcessingLogs)) {
                    for (BusinessProcessingLog businessProcessingLog : businessProcessingLogs) {
                        taskService.setVariable(businessProcessingLog.getHistoricTaskId(), ConstantUtil.ACCEPTANCE_SHEET_ASSIGNEE, String.valueOf(userId));
                        //修改business_assignee
                        BusinessAssignee businessAssignee = assigneeService.getByBusiness(acceptanceBasicInfo.getId(), ConstantUtil.ACCEPTANCE_SHEET, ConstantUtil.ASSIGNEE_PROJECT_MANAGER);
                        businessAssignee.setAssigneeId(userId);
                        assigneeService.update(businessAssignee);
                        if (businessProcessingLog.getTaskDefKey().equals(ConstantUtil.ACCEPTANCE_SHEET_ASSIGNEE.replace(ConstantUtil.ASSIGNEE, ""))) {
                            taskService.setAssignee(businessProcessingLog.getHistoricTaskId(), String.valueOf(userId));
                            taskService.setOwner(businessProcessingLog.getHistoricTaskId(), String.valueOf(userId));
                            businessProcessingLog.setAssignee(userService.get(userId));
                            processingLogMapper.updateAssigneeId(businessProcessingLog);
                        }
                    }
                }
            }
        }
    }

    @Override
    public GridPage findOldByCondition(ConditionVo conditionVo) {
        Dictionary completed = dictService.getByCode(ProjectInitiationStatusDict.ChildEnum.COMPLETED.getCode());

        Page<BusinessBasicInfo> businessList = businessBasicInfoService.getBusinessList(conditionVo);
        long total = businessList.getTotal();
        List<BusinessProcessingTaskVo> oldRows = businessList.stream().map(r -> {
            BusinessProcessingTaskVo businessProcessingTaskVo = new BusinessProcessingTaskVo();
            businessProcessingTaskVo.setId(r.getId());
            businessProcessingTaskVo.setBusinessNumber(r.getBusinessNumber());
            businessProcessingTaskVo.setBusinessName(r.getBusinessName());
            Customer customer = customerMapper.selectById(r.getEnterpriseCustomerInfoId());
            businessProcessingTaskVo.setCustomerName(customer.getEnterpriseName());
            Platform platform = platformService.getById(r.getTradingPlatformId());
            businessProcessingTaskVo.setPlatformName(platform.getPlatformName());
            List<BusinessSupplierInfo> businessSupplierInfos = businessSupplierInfoService.lambdaQuery().eq(BusinessSupplierInfo::getBusinessBasicInfoId, r.getId()).list();
            String supplierName = businessSupplierInfos.stream().map(businessSupplierInfo -> businessSupplierInfo.getSupplierName()).collect(Collectors.joining(","));
            businessProcessingTaskVo.setSupplierName(supplierName);
            businessProcessingTaskVo.setMode("");
            businessProcessingTaskVo.setStatus(dictService.getByCode(BusinessStageDict.ChildEnum.EMPTY.getCode()));
            businessProcessingTaskVo.setStatus(completed);
            businessProcessingTaskVo.setUserName(userService.get(r.getManagerId()).getName());
            return businessProcessingTaskVo;
        }).collect(Collectors.toList());

        return new GridPage(conditionVo.getRows(), conditionVo.getPage(), total, oldRows);
    }

//    @Override
//    public void downloadAllBusinessFile(Long id, HttpServletResponse response) {
//        List<FileStorage> allBusinessFile = new ArrayList<>();
//
//        //招投标文件
//        List<FileStorage> biddingFiles = sysAttachmentRefService.getFiles(AttachmentDto.builder()
//                .setEntityId(id)
//                .setChildEnum(FileModuleDict.ChildEnum.BIDDING_FILE)
//                .build());
//        allBusinessFile.addAll(biddingFiles);
//
//        //保函文件和中标通知书
//        BusinessGuaranteeMode businessGuaranteeMode = businessGuaranteeModeService.getOne(new QueryWrapper<BusinessGuaranteeMode>()
//                .eq("business_basic_info_id", id));
//        if (businessGuaranteeMode != null) {
//            List<FileStorage> guaranteeFiles = sysAttachmentRefService.getFiles(AttachmentDto.builder()
//                    .setEntityId(businessGuaranteeMode.getId())
//                    .setChildEnum(FileModuleDict.ChildEnum.GUARANTEE_FILE)
//                    .build());
//            allBusinessFile.addAll(guaranteeFiles);
//            List<FileStorage> bidWinningNoticeFiles = sysAttachmentRefService.getFiles(AttachmentDto.builder()
//                    .setEntityId(businessGuaranteeMode.getId())
//                    .setChildEnum(FileModuleDict.ChildEnum.BID_WINNING_NOTICE)
//                    .build());
//            allBusinessFile.addAll(bidWinningNoticeFiles);
//        }
//
//        //支付凭证、投标凭证、中标通知书
//        BusinessAwardConfirm awardConfirm = businessAwardConfirmService.getOne(new QueryWrapper<BusinessAwardConfirm>()
//                .eq("business_basic_info_id", id));
//        if (awardConfirm != null) {
//            List<FileStorage> awardConfirmFiles = sysAttachmentRefService.getFiles(AttachmentDto.builder()
//                    .setEntityId(awardConfirm.getId())
//                    .setChildEnum(FileModuleDict.ChildEnum.BIDDING_BID_WINNING_NOTICE)
//                    .build());
//            List<FileStorage> tenderDocumentsFiles = sysAttachmentRefService.getFiles(AttachmentDto.builder()
//                    .setEntityId(awardConfirm.getId())
//                    .setChildEnum(FileModuleDict.ChildEnum.TENDER_DOCUMENTS)
//                    .build());
//            List<FileStorage> paymentVoucherFiles = sysAttachmentRefService.getFiles(AttachmentDto.builder()
//            .setEntityId(awardConfirm.getId())
//            .setChildEnum(FileModuleDict.ChildEnum.PAYMENT_VOUCHER)
//            .build());
//            allBusinessFile.addAll(paymentVoucherFiles);
//            allBusinessFile.addAll(tenderDocumentsFiles);
//            allBusinessFile.addAll(awardConfirmFiles);
//        }
//
//        //保证金退款确认
//        BusinessRefundDepositConfirmation depositConfirmation = businessRefundDepositConfirmationService
//                .getOne(new QueryWrapper<BusinessRefundDepositConfirmation>().eq("business_basic_info_id", id));
//        if (depositConfirmation != null) {
//            List<FileStorage> returnVoucherFiles = sysAttachmentRefService.getFiles(AttachmentDto.builder()
//                    .setEntityId(depositConfirmation.getId())
//                    .setChildEnum(FileModuleDict.ChildEnum.RETURN_VOUCHER)
//                    .build());
//            allBusinessFile.addAll(returnVoucherFiles);
//        }
//
//        //去重文件 文件打包下载
//        fileStorageService.renameFileStorageList(allBusinessFile);
//        fileStorageService.downloadZipFile(allBusinessFile, FileModuleDict.ChildEnum.BUSINESS_ZIP_FILE.getCname(), FileModuleDict.ChildEnum.BUSINESS_ZIP_FILE, response);
//    }
}
