package com.trade.client.trade.sales.service.impl;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.trade.client.enterprise.service.EnterpriseService;
import com.trade.client.trade.purchase.service.PurchaseContractService;
import com.trade.common.utils.ConstantUtil;
import com.trade.common.utils.LoggerUtil;
import com.trade.common.utils.StringUtils;
import com.trade.common.utils.file.ExcelImportUtils;
import com.trade.common.utils.file.FileDownUtils;
import com.trade.common.utils.file.FileUtils;
import com.trade.service.DictConstants;
import com.trade.service.companyrelated.domain.VendorEntity;
import com.trade.service.companyrelated.service.IVendorEntityService;
import com.trade.service.enterprise.dto.EnterpriseDto;
import com.trade.service.filestorage.service.OSSFileService;
import com.trade.service.filestorage.service.TFileStorageService;
import com.trade.service.filestorage.util.oss.OSSUtil;
import com.trade.service.sales.vo.ImportCommodityVo;
import com.trade.service.serialNum.service.SerialNumberGenerator;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.slf4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.trade.client.consumer.domain.CustomerUser;
import com.trade.client.consumer.service.CustomerUserService;
import com.trade.client.trade.sales.dto.SalesContractInfoDto;
import com.trade.client.trade.sales.service.SalesService;
import com.trade.common.constant.HttpStatus;
import com.trade.common.core.page.GridPage;
import com.trade.common.enums.ContractStatus;
import com.trade.common.enums.SubmitStatus;
import com.trade.common.exception.ValidatorException;
import com.trade.common.validate.ValidatorGroup;
import com.trade.common.validate.ValidatorUtil;
import com.trade.service.FileTypeEnum;
import com.trade.service.contract.dto.ContractGenInputItem;
import com.trade.service.contract.dto.ContractGenOutputItem;
import com.trade.service.contract.service.ContractService;
import com.trade.service.filestorage.entity.TFileStorage;
import com.trade.service.filestorage.enums.FileModuleEnum;
import com.trade.service.filestorage.util.MultipartFileUtil;
import com.trade.service.sales.domain.*;
import com.trade.service.sales.dto.ContractSearchDto;
import com.trade.service.sales.dto.ContractTermsDto;
import com.trade.service.sales.dto.SalesCommodityDto;
import com.trade.service.sales.dto.SalesContractDto;
import com.trade.service.sales.service.*;
import com.trade.service.sales.service.impl.SalesDataConverter;
import com.trade.service.sales.vo.SalesContractInfoVo;
import com.trade.service.sales.vo.SalesContractVo;

import cn.hutool.core.collection.CollectionUtil;

/**
 * @description: 销售服务实现类
 * @Author: wanglang
 * @Date: 2024/9/3 19:14
 * @Version: 1.0
 */
@Service
public class SalesServiceImpl implements SalesService {

    private static final Logger log = LoggerUtil.logger(LoggerUtil.LogFileNameEnum.SERVICES_LOG);;
    @Resource
    private CustomerUserService customerUserService;
    @Resource
    private SalesContractService salesContractService;
    @Resource
    private SalesDataConverter salesDataConverter;
    @Resource
    private ContractFileService contractFileService;
    @Resource
    private OSSFileService ossFileService;
    @Resource
    private TFileStorageService tFileStorageService;
    @Resource
    private OSSUtil ossUtil;
    @Resource
    private ContractService contractService;
    @Resource
    private SalesCommodityService salesCommodityService;
    @Resource
    private ContractTermsService contractTermsService;
    @Resource
    private ContractTermsExtendService contractTermsExtendService;
    @Resource
    private IVendorEntityService iVendorEntityService;
    @Resource
    private SerialNumberGenerator serialNumberGenerator;
    @Resource
    private EnterpriseService enterpriseService;
    @Resource
    private PurchaseContractService purchaseContractService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long saveSalesContract(SalesContractInfoDto salesContractInfoDto, HttpServletRequest request) {
        SalesContractDto salesContractDto = salesContractInfoDto.getSalesContract();
        preVerification(salesContractInfoDto);
        CustomerUser customerUser = customerUserService.getCustomerUser();
        MultipartFile transferFile = null;
        if (request instanceof MultipartHttpServletRequest) {
            transferFile = ((MultipartHttpServletRequest) request).getFile("file");
        }
        // 设置为草稿状态
        salesContractDto.setSubmitStatus(SubmitStatus.DRAFT.getCode());
        SalesContract contractNoExist = salesContractService.lambdaQuery()
                .eq(SalesContract::getContractNo, salesContractDto.getContractNo()).eq(SalesContract::getDeleted, 0)
                .one();
        checkSalesContractParameter(salesContractDto, transferFile, contractNoExist);
        boolean isTemplate = false;
        ContractFile contractFile = handleContractFile(salesContractDto, customerUser, transferFile, isTemplate);
        salesContractDto.setContractNo(contractFile.getContractNo());
        salesContractDto.setContractStatus(ContractStatus.DRAFT.getCode());
        SalesContract salesContract = salesDataConverter.convertSalesContractDo(salesContractDto);
        // 更新时 这个字段不能为空
        if (salesContract.getId() != null) {
            salesContract.setUpdateBy(customerUser.getNickname());
            salesContractService.updateById(salesContract);
            if (!salesContractDto.getTemplateType()) {
                ContractFile contractFileExist = contractFileService.lambdaQuery()
                        .eq(ContractFile::getContractNo, contractFile.getContractNo()).eq(ContractFile::getDeleted, 0)
                        .one();
                contractFile.setId(contractFileExist.getId());
                contractFileService.updateById(contractFile);
            }
        } else {
            // 1、保存合同信息
            salesContract.setCreateBy(customerUser.getNickname());
            salesContractService.save(salesContract);
            if (!salesContractDto.getTemplateType()) {
                // 2、保存销售合同文件信息
                contractFileService.save(contractFile);
            }
        }
        // 3、保存商品信息
        List<SalesCommodity> salesCommodities = salesCommodityService.lambdaQuery()
                .eq(SalesCommodity::getSalesContractId, salesContract.getId()).list();
        if (CollectionUtil.isNotEmpty(salesCommodities)) {
            salesCommodityService.removeBatchByIds(salesCommodities);
        }
        List<SalesCommodityDto> salesCommodityDtos = salesContractInfoDto.getSalesCommoditys();
        salesCommodityDtos.forEach(salesCommodityDto -> {
            salesCommodityDto.setSalesContractId(salesContract.getId());
        });
        salesCommodityService.saveBatch(salesDataConverter.convertCommodityDo(salesCommodityDtos));
        return salesContract.getId();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveContractTerms(ContractTermsDto contractTermsDto, HttpServletResponse response) {
        if (SubmitStatus.FORMAL.getCode().equals(contractTermsDto.getSubmitStatus())) {
            ValidatorUtil.validator(ValidatorGroup.ValidatorType.SUBMIT, contractTermsDto);
        }
        if (StringUtils.isBlank(contractTermsDto.getPaymentWay())) {
            throw new ValidatorException(HttpStatus.BAD_REQUEST, "付款币种不能为空！");
        }
        // ContractTerms contractTermsExist = contractTermsService.lambdaQuery()
        // .eq(ContractTerms::getContractNo, contractTermsDto.getContractNo()).eq(ContractTerms::getDeleted, 0)
        // .one();
        ContractTerms contractTermsExist = contractTermsService.getByContractIdAndType(contractTermsDto.getContractId(),
                ConstantUtil.SALES_CONTRACT_NO_PREFIX);
        ContractTerms contractTerms = salesDataConverter.convertContractTermsDo(contractTermsDto);
        if (contractTermsExist != null) {
            contractTerms.setId(contractTermsExist.getId());
            contractTermsService.updateById(contractTerms);
        } else {
            contractTerms.setContractId(contractTermsDto.getContractId());
            contractTerms.setContractType(ConstantUtil.SALES_CONTRACT_NO_PREFIX);
            contractTermsService.save(contractTerms);
        }
        List<ContractTermsExtend> contractTermsExtendsExist = contractTermsExtendService.lambdaQuery()
                .eq(ContractTermsExtend::getContractTermsId, contractTerms.getId()).list();
        if (CollectionUtil.isNotEmpty(contractTermsExtendsExist)) {
            contractTermsExtendService.removeBatchByIds(contractTermsExtendsExist);
        }
        contractTermsExtendService.saveBatch(contractTermsDto.getPaymentInfo());
        contractTermsExtendService.saveBatch(contractTermsDto.getTitleInfo());
        CustomerUser customerUser = customerUserService.getCustomerUser();
        if (SubmitStatus.FORMAL.getCode().equals(contractTermsDto.getSubmitStatus())) {
            SalesContract salesContract = salesContractService.lambdaQuery()
                    .eq(SalesContract::getContractNo, contractTermsDto.getContractNo()).eq(SalesContract::getDeleted, 0)
                    .one();
            salesContract.setContractStatus(ContractStatus.TAKE_EFFECT.getCode());
            salesContract.setSubmitStatus(SubmitStatus.FORMAL.getCode());
            if (salesContract.getTemplateType()) {
                salesContract.setContractStatus(ContractStatus.TO_BE_UPLOADED.getCode());
                List<ContractTermsExtend> contractTermsExtends = contractTermsDto.getPaymentInfo();
                contractTermsExtends.addAll(contractTermsDto.getTitleInfo());
                ContractFile contractFile = handleInkassoContractFile(salesContract, customerUser, contractTerms,
                        contractTermsExtends);
                try {
                    TFileStorage tFileStorage = tFileStorageService
                            .getFileStorageById(contractFile.getUnsignFileStorageId());
                    String objName = tFileStorage.getPath();
                    String fileName = tFileStorage.getOriginalName();
                    InputStream in = ossUtil.downloadFile(objName);
                    OutputStream out = response.getOutputStream();
                    FileUtils.setAttachmentResponseHeader(response, fileName);
                    FileUtils.writeInputStream(in, out);
                } catch (Exception e) {
                    log.error("文件下载失败,合同编号={},客户id={},异常原因={}", salesContract.getContractNo(), customerUser.getId(), e);
                    throw new ValidatorException(HttpStatus.ERROR, "文件下载失败！");
                }
            }
            salesContractService.updateById(salesContract);
            purchaseContractService.createPurchaseContract(salesContract.getId());
        }
        return true;
    }

    @Override
    public SalesContractInfoVo getSalesContractDetails(Long contractId) {
        return salesContractService.getSalesContractDetails(contractId);
    }

    @Override
    public GridPage<SalesContractVo> getSalesContractPage(ContractSearchDto contractSearch) {
        CustomerUser customerUser = customerUserService.getCustomerUser();
        contractSearch.setCustomerUserId(customerUser.getId());
        contractSearch.setPoint(true);
        Page<SalesContractVo> page = PageHelper.startPage(contractSearch.getPage(), contractSearch.getRows());
        List<SalesContractVo> rows = salesContractService.getSalesContractInfo(contractSearch);
        return new GridPage<>(contractSearch.getPage(), contractSearch.getRows(), page.getTotal(), rows);
    }

    @Override
    public Boolean deleteSalesContract(Long contractId) {
        return salesContractService.deleteSalesContract(contractId);
    }

    @Override
    public Boolean uploadContract(Long contractId, HttpServletRequest request) {
        MultipartFile transferFile = null;
        if (request instanceof MultipartHttpServletRequest) {
            transferFile = ((MultipartHttpServletRequest) request).getFile("file");
        }
        if (transferFile == null) {
            throw new ValidatorException(HttpStatus.ERROR, "请您上传合同文件！");
        }
        SalesContract salesContract = salesContractService.getById(contractId);
        ContractFile contractFileExist = contractFileService.lambdaQuery()
                .eq(ContractFile::getContractNo, salesContract.getContractNo()).eq(ContractFile::getDeleted, 0).one();
        if (salesContract.getTemplateType() && contractFileExist == null) {
            throw new ValidatorException(HttpStatus.ERROR, "长银合同还未生成！");
        }
        try {
            if (contractFileExist != null) {
                TFileStorage fileStorage = ossFileService.addStorage(transferFile, FileModuleEnum.SIGNED_CONTRACT);
                contractFileExist.setSignedFileStorageId(fileStorage.getId());
                contractFileService.updateById(contractFileExist);
            } else {
                CustomerUser customerUser = customerUserService.getCustomerUser();
                ContractFile contractFile = new ContractFile();
                contractFile.setSignFileType(FileTypeEnum.SALES_CONTRACT.getCode());
                contractFile.setGenerationTime(LocalDateTime.now());
                contractFile.setOperatorName(customerUser.getNickname());
                TFileStorage fileStorage = ossFileService.addStorage(transferFile, FileModuleEnum.SIGNED_CONTRACT);
                contractFile.setContractNo(salesContract.getContractNo());
                contractFile.setUnsignFileStorageId(fileStorage.getId());
                contractFile.setSignedFileStorageId(fileStorage.getId());
                contractFileService.save(contractFile);
            }
            salesContract.setContractStatus(ContractStatus.TAKE_EFFECT.getCode());
            salesContractService.updateById(salesContract);
        } catch (Exception e) {
            log.error("合同编号={},上传合同文件失败,异常原因={}", salesContract.getContractNo(), e);
            throw new ValidatorException(HttpStatus.ERROR, "上传合同文件失败！");
        }
        return true;
    }

    @Override
    public Boolean downloadContract(Long contractId, HttpServletRequest request, HttpServletResponse response) {
        SalesContract salesContract = salesContractService.getById(contractId);
        ContractFile contractFileExist = contractFileService.lambdaQuery()
                .eq(ContractFile::getContractNo, salesContract.getContractNo()).eq(ContractFile::getDeleted, 0).one();
        Long fileId;
        if (!salesContract.getTemplateType()) {
            fileId = contractFileExist.getSignedFileStorageId();
        } else {
            if (ContractStatus.TAKE_EFFECT.getCode().equals(salesContract.getContractStatus())
                    || ContractStatus.COMPLETED.getCode().equals(salesContract.getContractStatus())) {
                fileId = contractFileExist.getSignedFileStorageId();
            } else {
                fileId = contractFileExist.getUnsignFileStorageId();
            }
        }
        TFileStorage tFileStorage = tFileStorageService.getFileStorageById(fileId);
        InputStream in = ossUtil.downloadFile(tFileStorage.getPath());
        FileDownUtils.downloadFile(response, in, tFileStorage.getOriginalName());
        return true;
    }

    @Override
    public ImportCommodityVo importCommodityFile(MultipartFile file) {
        if (file == null) {
            throw new ValidatorException(HttpStatus.ERROR, "请您上传商品文件！");
        }
        ExcelImportUtils excelImportUtils = new ExcelImportUtils(file);
        Sheet sheet = excelImportUtils.readFile();
        ImportCommodityVo importCommodityVo = new ImportCommodityVo();
        List<SalesCommodityDto> pass = new ArrayList<>();
        List<SalesCommodityDto> error = new ArrayList<>();
        Iterator<Row> rows = sheet.rowIterator();
        EnterpriseDto enterpriseDto = enterpriseService.queryMyEnterprise();
        String exportType = enterpriseDto.getExportType();
        // todo 缺少与小图接口校验部分
        while (rows.hasNext()) {
            Row row = rows.next();
            if (row.getRowNum() == 0) {
                continue;
            }
            Cell cell = row.getCell(0);
            SalesCommodityDto salesCommodityDto = new SalesCommodityDto();
            StringBuffer stringBuffer = new StringBuffer();
            if (DictConstants.EXPORT_TYPE_SELF.equals(exportType)) {
                if (cell != null && StringUtils.isNotBlank(cell.getStringCellValue())) {
                    String entityName = cell.getStringCellValue();
                    VendorEntity vendorEntity = iVendorEntityService.lambdaQuery()
                            .eq(VendorEntity::getEntityName, entityName).eq(VendorEntity::getDeleted, 0).one();
                    if (vendorEntity != null) {
                        salesCommodityDto.setEntityNo(vendorEntity.getEntityNo());
                    } else {
                        stringBuffer.append("供应商名称不存在,");
                    }
                    salesCommodityDto.setEntityName(entityName);
                } else {
                    stringBuffer.append("供应商名称为空,");
                }
            } else {
                salesCommodityDto.setEntityName(cell.getStringCellValue());
            }
            cell = row.getCell(1);
            if (cell != null && StringUtils.isNotBlank(cell.getStringCellValue())) {
                salesCommodityDto.setName(cell.getStringCellValue());
            } else {
                stringBuffer.append("商品名称为空,");
            }
            cell = row.getCell(2);
            if (cell != null && StringUtils.isNotBlank(cell.getStringCellValue())) {
                salesCommodityDto.setHsCode(cell.getStringCellValue());
            } else {
                stringBuffer.append("HS编码为空,");
            }
            cell = row.getCell(2);
            salesCommodityDto.setModel(cell.getStringCellValue());
            cell = row.getCell(3);
            if (cell != null && StringUtils.isNotBlank(cell.getStringCellValue())) {
                salesCommodityDto.setMeasurementUnit(cell.getStringCellValue());
            } else {
                stringBuffer.append("计量单位为空,");
            }
            cell = row.getCell(4);
            if (cell != null && StringUtils.isNotBlank(cell.getStringCellValue())) {
                salesCommodityDto.setPackSpec(cell.getStringCellValue());
            } else {
                stringBuffer.append("包装规格为空,");
            }
            cell = row.getCell(5);
            if (cell != null && StringUtils.isNotBlank(cell.getStringCellValue())) {
                salesCommodityDto.setNumber(Integer.valueOf(cell.getStringCellValue()));
            } else {
                stringBuffer.append("数量为空,");
            }
            cell = row.getCell(6);
            if (cell != null && StringUtils.isNotBlank(cell.getStringCellValue())) {
                salesCommodityDto.setPriceUnit(new BigDecimal(cell.getStringCellValue()));
            } else {
                stringBuffer.append("销售单价为空,");
            }
            // cell = row.getCell(7);
            // if (cell != null && StringUtils.isNotBlank(cell.getStringCellValue())) {
            // salesCommodityDto.setAmount(new BigDecimal(cell.getStringCellValue()));
            // } else {
            // stringBuffer.append("商品金额为空,");
            // }
            if (stringBuffer != null && stringBuffer.length() > 0) {
                salesCommodityDto.setErrors(stringBuffer.deleteCharAt(stringBuffer.length() - 1).toString());
                error.add(salesCommodityDto);
            } else {
                pass.add(salesCommodityDto);
            }
        }
        importCommodityVo.setPass(pass);
        importCommodityVo.setError(error);
        return importCommodityVo;
    }

    /**
     * 校验销售合同参数
     * 
     * @param salesContractDto
     * @param transferFile
     * @param salesContractExist
     */
    private void checkSalesContractParameter(SalesContractDto salesContractDto, MultipartFile transferFile,
            SalesContract salesContractExist) {
        if (!salesContractDto.getTemplateType()) {
            if (salesContractDto.getContractNo() == null || salesContractDto.getSignDate() == null) {
                throw new ValidatorException(HttpStatus.ERROR, "合同编号与签署日期不能为空！");
            }
            if (transferFile == null) {
                throw new ValidatorException(HttpStatus.ERROR, "请您上传合同！");
            }
            // 获取文件名
            String filename = transferFile.getOriginalFilename();
            String suffix;
            int dotIndex = filename.lastIndexOf('.');
            if (dotIndex == -1 || dotIndex == filename.length() - 1) {
                suffix = "";
            } else {
                suffix = filename.substring(dotIndex + 1);
            }
            if ("pdf".equalsIgnoreCase(suffix)) {
                throw new ValidatorException(HttpStatus.ERROR, "合同文件格式必须为pdf格式");
            }
            boolean meetLimit = MultipartFileUtil.checkFileSize(transferFile, 20, "M");
            if (!meetLimit) {
                throw new ValidatorException(HttpStatus.ERROR, "合同文件大小请控制在20M以内");
            }
        }
        if (salesContractExist != null && SubmitStatus.FORMAL.getCode().equals(salesContractExist.getSubmitStatus())) {
            throw new ValidatorException(HttpStatus.ERROR, "该合同编号已存在正式合同，请勿重复提交！");
        }
    }

    /***
     * 处理合同文件
     * 
     * @param salesContractDto
     * @param customerUser
     * @param transferFile
     * @param isTemplate
     * @return 合同文件信息
     */
    private ContractFile handleContractFile(SalesContractDto salesContractDto, CustomerUser customerUser,
            MultipartFile transferFile, boolean isTemplate) {
        try {
            ContractFile contractFile = new ContractFile();
            contractFile.setSignFileType(FileTypeEnum.SALES_CONTRACT.getCode());
            contractFile.setGenerationTime(LocalDateTime.now());
            contractFile.setOperatorName(customerUser.getNickname());
            if (salesContractDto.getTemplateType() && isTemplate) {
                // 生成合同文件
                contractFile.setContractNo(serialNumberGenerator.nextValue(ConstantUtil.SALES_CONTRACT_NO_PREFIX));
                // ContractGenInput input = new ContractGenInput();
                // input.setBizNo(contractFile.getContractNo());
                // input.setUserId(customerUser.getId());
                // input.setBizType(FileTypeEnum.SALES_CONTRACT.getCode());
                ContractGenInputItem contractGenInputItem = new ContractGenInputItem();
                contractGenInputItem.setContractName(salesContractDto.getContractName());
                // todo 缺失合同模板
                ContractGenOutputItem contractGenOutput = contractService.generateSingleContract(contractGenInputItem,
                        customerUser.getId());
                contractFile.setUnsignFileStorageId(contractGenOutput.getFileId());
            } else {
                TFileStorage fileStorage = ossFileService.addStorage(transferFile, FileModuleEnum.SIGNED_CONTRACT);
                contractFile.setContractNo(salesContractDto.getContractNo());
                contractFile.setUnsignFileStorageId(fileStorage.getId());
                contractFile.setSignedFileStorageId(fileStorage.getId());
            }
            return contractFile;
        } catch (IOException e) {
            log.error("上传合同文件失败,合同编号={},客户id={},异常原因={}", salesContractDto.getContractNo(), customerUser.getId(), e);
            throw new ValidatorException(HttpStatus.ERROR, "合同文件处理失败，请稍后再试！");
        }
    }

    /**
     * 处理合同文件
     * 
     * @param salesContract
     * @param customerUser
     * @param contractTerms
     * @param contractTermsExtends
     * @return
     */
    private ContractFile handleInkassoContractFile(SalesContract salesContract, CustomerUser customerUser,
            ContractTerms contractTerms, List<ContractTermsExtend> contractTermsExtends) {
        try {
            List<SalesCommodity> salesCommodities = salesCommodityService.lambdaQuery()
                    .eq(SalesCommodity::getSalesContractId, salesContract.getId()).list();
            ContractFile contractFile = new ContractFile();
            contractFile.setSignFileType(FileTypeEnum.SALES_CONTRACT.getCode());
            contractFile.setGenerationTime(LocalDateTime.now());
            contractFile.setOperatorName(customerUser.getNickname());
            contractFile.setContractNo(serialNumberGenerator.nextValue(ConstantUtil.SALES_CONTRACT_NO_PREFIX));
            // ContractGenInput input = new ContractGenInput();
            // input.setBizNo(contractFile.getContractNo());
            // input.setUserId(customerUser.getId());
            // input.setBizType(FileTypeEnum.SALES_CONTRACT.getCode());
            ContractGenInputItem contractGenInputItem = new ContractGenInputItem();
            contractGenInputItem.setContractName(salesContract.getContractName());
            // todo 缺失合同模板
            Map<String, Object> params = new HashMap<>();
            ContractGenOutputItem contractGenOutput = contractService.generateSingleContract(contractGenInputItem,
                    customerUser.getId());
            contractFile.setUnsignFileStorageId(contractGenOutput.getFileId());
            return contractFile;
        } catch (Exception e) {
            log.error("生成合同文件失败,合同编号={},客户id={},异常原因={}", salesContract.getContractNo(), customerUser.getId(), e);
            throw new ValidatorException(HttpStatus.ERROR, "合同文件处理失败，请稍后再试！");
        }
    }

    private void preVerification(SalesContractInfoDto salesContractDto) {
        if (SubmitStatus.INTERMEDIATE_STATE.getCode().equals(salesContractDto.getSalesContract().getSubmitStatus())) {
            // 校验参数
            EnterpriseDto enterpriseDto = enterpriseService.queryMyEnterprise();
            String exportType = enterpriseDto.getExportType();
            if (DictConstants.EXPORT_TYPE_PROXY.equals(exportType)
                    && StringUtils.isBlank(salesContractDto.getSalesContract().getAgencyCertNo())) {
                throw new ValidatorException(HttpStatus.BAD_REQUEST, "代理公司不能为空！");
            }
            ValidatorUtil.validator(ValidatorGroup.ValidatorType.SUBMIT, salesContractDto.getSalesContract());
            if (CollectionUtil.isEmpty(salesContractDto.getSalesCommoditys())) {
                throw new ValidatorException(HttpStatus.BAD_REQUEST, "需要添加商品信息！");
            }
            for (int i = 0; i < salesContractDto.getSalesCommoditys().size(); i++) {
                ValidatorUtil.validator(ValidatorGroup.ValidatorType.SUBMIT,
                        salesContractDto.getSalesCommoditys().get(i), i + 1);
                if (DictConstants.EXPORT_TYPE_SELF.equals(exportType)
                        && StringUtils.isBlank(salesContractDto.getSalesCommoditys().get(i).getEntityNo())) {
                    throw new ValidatorException(HttpStatus.BAD_REQUEST, "商品信息第" + i + 1 + "行，供应商不能为空！");
                }
            }
        }
    }
}
