package com.yh.saas.plugin.yiliangyiyun.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.alipay.sofa.runtime.api.annotation.SofaService;
import com.winsea.svc.base.base.util.DateUtils;
import com.winsea.svc.base.workflow.entity.Workflow;
import com.winsea.svc.notice.entity.base.BaseNotice;
import com.winsea.svc.notice.service.INoticeService;
import com.yh.saas.common.support.util.IdGenerator;
import com.yh.saas.plugin.base.service.ICommonBillOperateHisService;
import com.yh.saas.plugin.yiliangyiyun.constant.NumberConstant;
import com.yh.saas.plugin.yiliangyiyun.constant.StatusEnum;
import com.yh.saas.plugin.yiliangyiyun.entity.*;
import com.yh.saas.plugin.yiliangyiyun.exception.YException;
import com.yh.saas.plugin.yiliangyiyun.exception.YExceptionEnum;
import com.yh.saas.plugin.yiliangyiyun.mapper.ContractManagementInfoMapper;
import com.yh.saas.plugin.yiliangyiyun.service.*;
import com.google.common.collect.Lists;
import com.winsea.svc.base.security.util.AuthSecurityUtils;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.yh.saas.plugin.yiliangyiyun.util.Const;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.httpclient.util.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.beans.factory.annotation.Autowired;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;


import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;
import java.io.*;
import java.net.URLDecoder;

/**
 * <p>
 * 合同管理 服务实现类
 * </p>
 *
 * @author Gongdc
 * @since 2021-05-17
 */
@SofaService
@Slf4j
public class ContractManagementInfoServiceImpl extends ServiceImpl<ContractManagementInfoMapper, ContractManagementInfo> implements IContractManagementInfoService {
    @Autowired
    private IContractGoodsInfoService contractGoodsInfoService;
    @Autowired
    private IContractManagementInfoService contractManagementInfoService;
    @Autowired
    private ICommonBillOperateHisService billOperateHisService;
    @Autowired
    private IContractProcessInfoService contractProcessInfoService;
    @Autowired
    private IWarehouseBaseInfoService warehouseBaseInfoService;
    @Autowired
    private IWarehouseInOutInfoService warehouseInOutInfoService;
    @Autowired
    private IInOutWarehouseTaskService inOutWarehouseTaskService;
    @Autowired
    private IStockSaleReceiptReportService stockSaleReceiptReportService;
    @Autowired
    private IStockPurchaseReceiptReportService stockPurchaseReceiptReportService;
    @Autowired
    private ITranTaskInfoService tranTaskInfoService;
    @Autowired
    private ITranCarInfoService tranCarInfoService;
    @Autowired
    private ITranProcessInfoService tranProcessInfoService;
    @Autowired
    private ITranSettlementReportService tranSettlementReportService;
    @Autowired
    private INewWorkflowService workflowService;
    @Autowired
    private INoticeService noticeService;
    @Autowired
    private IPriceConfirmationSheetService priceConfirmationSheetService;
    @Autowired
    private IContractInventoryDistributionService contractInventoryDistributionService;
    @Autowired
    private IWarehousingOrderService warehousingOrderService;
    @Autowired
    private ICollectionWarehousingRecordService collectionWarehousingRecordService;
    @Value("${file-root-path}")
    private String localPath;

    @Autowired
    private CacheComponent cacheComponent;
    /**
     * 新增合同信息
     *
     * @param contractManagementInfo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String addInfo(ContractManagementInfo contractManagementInfo) {
        // 主表信息新增
        // 新增主键id
        contractManagementInfo.setId(IdGenerator.generateUUID());
        // 期货插入状态
//        if("2".equals(contractManagementInfo.getGoodsType())){
        contractManagementInfo.setStatusFlag(StatusEnum.CONTRACT_WAIT.getFlag());
        contractManagementInfo.setStatus(StatusEnum.CONTRACT_WAIT.getName());
//        }
        if (contractManagementInfo.getAgreementNo()!=null){
            //判断补充协议编号是否唯一
            List<ContractManagementInfo> contractManagementInfoList =
                    contractManagementInfoService.selectList(new EntityWrapper<ContractManagementInfo>()
                            .eq(ContractManagementInfo.QueryFiles.COMP_ID, AuthSecurityUtils.getCurrentUserInfo().getCompId())
                            .eq(ContractManagementInfo.QueryFiles.CONTRACT_NO, contractManagementInfo.getContractNo())
                            .eq(ContractManagementInfo.QueryFiles.DELETE_FLAG, NumberConstant.CONSTANT0));
            if (contractManagementInfoList.size() > 0) {
                throw new YException(YExceptionEnum.AGREEMENT_NO_ERROR);
            }
        }
        else{
            //判断合同编号是否唯一
            List<ContractManagementInfo> contractManagementInfos =
                    contractManagementInfoService.selectList(new EntityWrapper<ContractManagementInfo>()
                            .eq(ContractManagementInfo.QueryFiles.COMP_ID,contractManagementInfo.getCompId())
                            .eq(ContractManagementInfo.QueryFiles.CONTRACT_NO, contractManagementInfo.getContractNo())
                            .eq(ContractManagementInfo.QueryFiles.DELETE_FLAG, NumberConstant.CONSTANT0));
            if (contractManagementInfos.size() > 0) {
                throw new YException(YExceptionEnum.CONTRACT_NO_ERROR);
            }
        }
        //现货自运采购合同添加临时仓库
        if (NumberConstant.CONSTANT1.equals(contractManagementInfo.getGoodsType())&&NumberConstant.CONSTANT2.equals(contractManagementInfo.getContractType()) && (NumberConstant.CONSTANT1.equals(contractManagementInfo.getDeliverType())||NumberConstant.CONSTANT3.equals(contractManagementInfo.getDeliverType()))) {
            WarehouseBaseInfo warehouseBaseInfo = new WarehouseBaseInfo();
            warehouseBaseInfo.setId(IdGenerator.generateUUID());
            Map<String, Object> pageView = new HashMap<>();
            pageView.put("compId", contractManagementInfo.getCompId());
            // 查询本公司临时仓库包括已删除的
            Integer dataCount = warehouseBaseInfoService.getTemWareHouseCountByCondition(pageView);
            //插入仓库编号
            Integer warehouseNum = dataCount + 1;
            //一位数
            if (warehouseNum < 10) {
                warehouseBaseInfo.setCommonWarehouseNo("000" + warehouseNum);
            }
            //两位数
            else if (warehouseNum < 100) {
                warehouseBaseInfo.setCommonWarehouseNo("00" + warehouseNum);
            }
            //三位数
            else if (warehouseNum < 1000) {
                warehouseBaseInfo.setCommonWarehouseNo("0" + warehouseNum);
            }
            //四位数
            else if (warehouseNum < 10000) {
                warehouseBaseInfo.setCommonWarehouseNo(String.valueOf(warehouseNum));
            }
            warehouseBaseInfo.setWarehouseName(contractManagementInfo.getContractNo());
//            warehouseBaseInfo.setPersonChargeKey(contractManagementInfo.getPersonChargeKey());
            warehouseBaseInfo.setOtherPersonCharge(contractManagementInfo.getPersonCharge());
            warehouseBaseInfo.setOtherPersonPhone(contractManagementInfo.getPersonPhone());
            warehouseBaseInfo.setCreateType("1");
            warehouseBaseInfo.setCompId(contractManagementInfo.getCompId());
            warehouseBaseInfo.setWarehousePrivate(contractManagementInfo.getSourceProvince());
            warehouseBaseInfo.setWarehouseCity(contractManagementInfo.getSourceCity());
            warehouseBaseInfo.setWarehouseArea(contractManagementInfo.getSourceArea());
            warehouseBaseInfo.setDetailedAddress(contractManagementInfo.getSourceGoods());
            warehouseBaseInfo.setWarehousePositioning(contractManagementInfo.getSourceLocation());
            warehouseBaseInfoService.addTemporaryWarehouse(warehouseBaseInfo);
            //临时仓库流转页面
            WarehouseInOutInfo warehouseInOutInfo = new WarehouseInOutInfo();
            warehouseInOutInfo.setId(IdGenerator.generateUUID());
            warehouseInOutInfo.setBaseId(warehouseBaseInfo.getId());
            warehouseInOutInfo.setStatus(StatusEnum.SUBMITTED.getName());
            warehouseInOutInfo.setWarehouseName(contractManagementInfo.getContractNo());
            warehouseInOutInfo.setStatusFlag("3");
            warehouseInOutInfo.setInOutFlag(NumberConstant.CONSTANT2);
            warehouseInOutInfo.setContractNo(contractManagementInfo.getContractNo());
            warehouseInOutInfo.setNetWeight(Double.valueOf(contractManagementInfo.getFinalTradingVolume()));
            warehouseInOutInfo.setGoodsName(contractManagementInfo.getContractGoodsInfo().getGoodsName());
            warehouseInOutInfo.setGoodsNameKey(contractManagementInfo.getContractGoodsInfo().getGoodsNameKey());
            warehouseInOutInfo.setGrade(contractManagementInfo.getContractGoodsInfo().getGrade());
            warehouseInOutInfo.setGradeKey(contractManagementInfo.getContractGoodsInfo().getGradeKey());
            warehouseInOutInfo.setInOutType(NumberConstant.PURCHASE_WAREHOUSING);
            warehouseInOutInfo.setInOutTypeKey(NumberConstant.CONSTANT1);
            warehouseInOutInfo.setBackOfficeId(AuthSecurityUtils.getCurrentUserId());
            warehouseInOutInfo.setAgentKey(AuthSecurityUtils.getCurrentUserId());
            warehouseInOutInfo.setAgent(AuthSecurityUtils.getStaffById(AuthSecurityUtils.getCurrentUserId()).getStaffName());
            warehouseInOutInfo.setBackOffice(AuthSecurityUtils.getStaffById(AuthSecurityUtils.getCurrentUserId()).getStaffName());
            warehouseInOutInfo.setInOutDate(contractManagementInfo.getSigningDate());
            warehouseInOutInfoService.insert(warehouseInOutInfo);
            //采购自运合同自动生成入库单
            WarehousingOrder warehousingOrder = new WarehousingOrder();
            warehousingOrder.setId(IdGenerator.generateUUID());
            warehousingOrder.setBaseId(warehouseBaseInfo.getId());
            warehousingOrder.setWarehouseName(contractManagementInfo.getContractNo());
            warehousingOrder.setGoodsSource(contractManagementInfo.getContractNo());
            warehousingOrder.setInType("采购入库");
            warehousingOrder.setCustomer(contractManagementInfo.getSeller());
            warehousingOrder.setAvgCost(contractManagementInfo.getUnitContractPrice());
            warehousingOrder.setCompId(contractManagementInfo.getCompId());
            warehousingOrder.setDeliveryWarehouse(contractManagementInfo.getContractNo());
            warehousingOrder.setGoodsName(contractManagementInfo.getContractGoodsInfo().getGoodsName());
            warehousingOrder.setContractNo(contractManagementInfo.getContractNo());
            warehousingOrder.setInWarehouseWeight(contractManagementInfo.getFinalTradingVolume());
            warehousingOrder.setAmountNotPayable(contractManagementInfo.getTotalContractPrice());
            warehousingOrder.setAmountEdPayable(0d);
            warehousingOrder.setSurplusWeight(contractManagementInfo.getFinalTradingVolume());
            warehousingOrder.setIssuingTime(new Date());
            warehousingOrder.setGrainFund(contractManagementInfo.getTotalContractPrice());
            warehousingOrderService.insert(warehousingOrder);
            //采购自运合同自动生成库存
            ContractInventoryDistribution contractInventoryDistribution=new ContractInventoryDistribution();
            contractInventoryDistribution.setId(IdGenerator.generateUUID());
            contractInventoryDistribution.setCompId(contractManagementInfo.getCompId());
            contractInventoryDistribution.setInStorage(Double.valueOf(String.valueOf(contractManagementInfo.getFinalTradingVolume())));
            contractInventoryDistribution.setWarehouse(contractManagementInfo.getContractNo());
            contractInventoryDistribution.setContractNo(contractManagementInfo.getContractNo());
            contractInventoryDistribution.setGoodsName(contractManagementInfo.getGoodsName());
            contractInventoryDistribution.setInventoryType("1");
            contractInventoryDistributionService.insert(contractInventoryDistribution);
        }
        // 货物信息新增
        ContractGoodsInfo contractGoodsInfo = contractManagementInfo.getContractGoodsInfo();
        contractGoodsInfo.setId(IdGenerator.generateUUID());
        contractGoodsInfo.setContractId(contractManagementInfo.getId());
        //流程新增
        ContractProcessInfo contractProcessInfo = contractManagementInfo.getContractProcessInfo();
        contractProcessInfo.setId(IdGenerator.generateUUID());
        contractProcessInfo.setContractId(contractManagementInfo.getId());
        boolean one = this.insert(contractManagementInfo);
        // 根据类型进入审核
        if("1".equals(contractManagementInfo.getGoodsType())) {
            //销售合同
            if ("1".equals(contractManagementInfo.getContractType())&&!"代储合同".equals(contractManagementInfo.getAgreementType())) {
                boolean isStartWorkflow = StringUtils.isBlank(contractManagementInfo.getWorkflowId());
                // 不是退回的单子
                if (isStartWorkflow) {
                    Workflow workflow = workflowService
                            .findLatestWorkflowByBusinessCodeByApp(contractManagementInfo.getCompId(), "SALE-CONTRACT-APPROVE");
                    // 没配置审核流程，直接结束并处理信息
                    if (workflow == null) {
                        throw new YException(YExceptionEnum.PURCHASE_ORDER_ERROR);
                    }
                    // 开启审核流
                    else {

                        // 设置状态 已提交审核
                        contractManagementInfo.setWorkflowId(workflow.getId());
                        this.updateById(contractManagementInfo);
                        workflowService.startInstance(workflow.getId(), contractManagementInfo.getId());
                    }
                }
                // 退回的单子 再启用
                else {

                    this.updateById(contractManagementInfo);
                    workflowService.activateInstance(contractManagementInfo.getWorkflowId(), contractManagementInfo.getId());
                }
            }
            //代储合同
            else if ("1".equals(contractManagementInfo.getContractType())&&"代储合同".equals(contractManagementInfo.getAgreementType())) {
                boolean isStartWorkflow = StringUtils.isBlank(contractManagementInfo.getWorkflowId());
                // 不是退回的单子
                if (isStartWorkflow) {
                    Workflow workflow = workflowService
                            .findLatestWorkflowByBusinessCodeByApp(contractManagementInfo.getCompId(), "DAICHU-CONTRACT-APPROVE ");
                    // 没配置审核流程，直接结束并处理信息
                    if (workflow == null) {
                        throw new YException(YExceptionEnum.PURCHASE_ORDER_ERROR);
                    }
                    // 开启审核流
                    else {

                        // 设置状态 已提交审核
                        contractManagementInfo.setWorkflowId(workflow.getId());
                        this.updateById(contractManagementInfo);
                        workflowService.startInstance(workflow.getId(), contractManagementInfo.getId());
                    }
                }
                // 退回的单子 再启用
                else {

                    this.updateById(contractManagementInfo);
                    workflowService.activateInstance(contractManagementInfo.getWorkflowId(), contractManagementInfo.getId());
                }
            }
            //采购合同
            else if("2".equals(contractManagementInfo.getContractType())){
                boolean isStartWorkflow = StringUtils.isBlank(contractManagementInfo.getWorkflowId());
                // 不是退回的单子
                if (isStartWorkflow) {
                    Workflow workflow = workflowService
                            .findLatestWorkflowByBusinessCodeByApp(contractManagementInfo.getCompId(), "BUY-CONTRACT-APPROVE");
                    // 没配置审核流程，直接结束并处理信息
                    if (workflow == null) {
                        throw new YException(YExceptionEnum.PURCHASE_ORDER_ERROR);
                    }
                    // 开启审核流
                    else {

                        // 设置状态 已提交审核
                        contractManagementInfo.setWorkflowId(workflow.getId());
                        this.updateById(contractManagementInfo);
                        workflowService.startInstance(workflow.getId(), contractManagementInfo.getId());
                    }
                }
                // 退回的单子 再启用
                else {

                    this.updateById(contractManagementInfo);
                    workflowService.activateInstance(contractManagementInfo.getWorkflowId(), contractManagementInfo.getId());
                }

            }
            //收购合同
            else if("3".equals(contractManagementInfo.getContractType())){
                boolean isStartWorkflow = StringUtils.isBlank(contractManagementInfo.getWorkflowId());
                // 不是退回的单子
                if (isStartWorkflow) {
                    Workflow workflow = workflowService
                            .findLatestWorkflowByBusinessCodeByApp(contractManagementInfo.getCompId(), "SHOU-CONTRACT-APPROVE");
                    // 没配置审核流程，直接结束并处理信息
                    if (workflow == null) {
                        throw new YException(YExceptionEnum.PURCHASE_ORDER_ERROR);
                    }
                    // 开启审核流
                    else {

                        // 设置状态 已提交审核
                        contractManagementInfo.setWorkflowId(workflow.getId());
                        this.updateById(contractManagementInfo);
                        workflowService.startInstance(workflow.getId(), contractManagementInfo.getId());
                    }
                }
                // 退回的单子 再启用
                else {

                    this.updateById(contractManagementInfo);
                    workflowService.activateInstance(contractManagementInfo.getWorkflowId(), contractManagementInfo.getId());
                }

            }
            //代收合同
            else {
                boolean isStartWorkflow = StringUtils.isBlank(contractManagementInfo.getWorkflowId());
                // 不是退回的单子
                if (isStartWorkflow) {
                    Workflow workflow = workflowService
                            .findLatestWorkflowByBusinessCodeByApp(contractManagementInfo.getCompId(), "DAISHOU-CONTRACT-APPROVE");
                    // 没配置审核流程，直接结束并处理信息
                    if (workflow == null) {
                        throw new YException(YExceptionEnum.PURCHASE_ORDER_ERROR);
                    }
                    // 开启审核流
                    else {

                        // 设置状态 已提交审核
                        contractManagementInfo.setWorkflowId(workflow.getId());
                        this.updateById(contractManagementInfo);
                        workflowService.startInstance(workflow.getId(), contractManagementInfo.getId());
                    }
                }
                // 退回的单子 再启用
                else {

                    this.updateById(contractManagementInfo);
                    workflowService.activateInstance(contractManagementInfo.getWorkflowId(), contractManagementInfo.getId());
                }

            }
        }

        boolean two = contractGoodsInfoService.insert(contractGoodsInfo);
        boolean three = contractProcessInfoService.insert(contractProcessInfo);
        cacheComponent.delPrefixKey(Const.ADMIN_CONTRACTINFO);
        // 假如 都成功返回ok
        if (one && two && three) {
            // 插入操作历史
            String staffName = this.billOperateHisService.getStaffAndName();
            // 插入操作历史
            this.billOperateHisService.saveBillOperateHis(contractManagementInfo.getId(), NumberConstant.CONSTANT_CONTRACT, staffName, null,
                    StatusEnum.CONTRACT_WAIT.getName(), StatusEnum.CONTRACT_WAIT.getName(), "");
            return "OK";
        } else {
            return "NG";
        }
    }

    /**
     * 编辑合同信息
     *
     * @param contractManagementInfo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String editInfo(ContractManagementInfo contractManagementInfo) {
        // 主表信息编辑
        boolean one = this.updateById(contractManagementInfo);
        //上传附件flag 1
        if(contractManagementInfo.getFlag()==null) {
            // 更新仓库名
            WarehouseBaseInfo warehouseBaseInfo = warehouseBaseInfoService.selectOne(new EntityWrapper<WarehouseBaseInfo>()
                    .eq(WarehouseBaseInfo.QueryFiles.COMP_ID, AuthSecurityUtils.getCurrentUserInfo().getCompId())
                    .eq(WarehouseBaseInfo.QueryFiles.WAREHOUSE_NAME, contractManagementInfo.getContractNo())
                    .eq(WarehouseBaseInfo.QueryFiles.DELETE_FLAG, NumberConstant.CONSTANT0));
            if (warehouseBaseInfo != null) {
                warehouseBaseInfo.setOtherPersonCharge(contractManagementInfo.getPersonCharge());
                warehouseBaseInfo.setOtherPersonPhone(contractManagementInfo.getPersonPhone());
                warehouseBaseInfoService.updateById(warehouseBaseInfo);
            }
            //收购任务重量随合同重量变化
            if("3".equals(contractManagementInfo.getContractType())){
                //一个收购合同只能选一次
                InOutWarehouseTask inOutWarehouseTask=inOutWarehouseTaskService.selectOne(new EntityWrapper<InOutWarehouseTask>()
                        .eq("comp_id", contractManagementInfo.getCompId())
                        .eq("contract_no", contractManagementInfo.getContractNo())
                        .eq("delete_flag", "0")
                        .orderBy("update_date", false));
                if (inOutWarehouseTask!=null){
                    inOutWarehouseTask.setWeight(contractManagementInfo.getWeight());
                    inOutWarehouseTaskService.updateById(inOutWarehouseTask);
                }
            }
            // 根据类型进入审核
//            if ("1".equals(contractManagementInfo.getGoodsType())) {
//                if ("1".equals(contractManagementInfo.getContractType())) {
//                    boolean isStartWorkflow = StringUtils.isBlank(contractManagementInfo.getWorkflowId());
//                    // 不是退回的单子
//                    if (isStartWorkflow) {
//                        Workflow workflow = workflowService
//                                .findLatestWorkflowByBusinessCodeByApp(contractManagementInfo.getCompId(), "SALE-CONTRACT-APPROVE");
//                        // 没配置审核流程，直接结束并处理信息
//                        if (workflow == null) {
//                            throw new YException(YExceptionEnum.PURCHASE_ORDER_ERROR);
//                        }
//                        // 开启审核流
//                        else {
//
//                            // 设置状态 已提交审核
//                            //状态清空
//                            contractManagementInfo.setStatusFlag("");
//                            contractManagementInfo.setStatus("");
//                            contractManagementInfo.setWorkflowId(workflow.getId());
//                            this.updateById(contractManagementInfo);
//                            workflowService.startInstance(workflow.getId(), contractManagementInfo.getId());
//                        }
//                    }
//                    // 退回的单子 再启用
//                    else {
//                        //状态清空
//                        contractManagementInfo.setStatusFlag("");
//                        contractManagementInfo.setStatus("");
//                        this.updateById(contractManagementInfo);
//                        workflowService.activateInstance(contractManagementInfo.getWorkflowId(), contractManagementInfo.getId());
//                    }
//                } else {
//
//                    boolean isStartWorkflow = StringUtils.isBlank(contractManagementInfo.getWorkflowId());
//                    // 不是退回的单子
//                    if (isStartWorkflow) {
//                        Workflow workflow = workflowService
//                                .findLatestWorkflowByBusinessCodeByApp(contractManagementInfo.getCompId(), "BUY-CONTRACT-APPROVE");
//                        // 没配置审核流程，直接结束并处理信息
//                        if (workflow == null) {
//                            throw new YException(YExceptionEnum.PURCHASE_ORDER_ERROR);
//                        }
//                        // 开启审核流
//                        else {
//                            //状态清空
//                            contractManagementInfo.setStatusFlag("");
//                            contractManagementInfo.setStatus("");
//                            // 设置状态 已提交审核
//                            contractManagementInfo.setWorkflowId(workflow.getId());
//                            this.updateById(contractManagementInfo);
//                            workflowService.startInstance(workflow.getId(), contractManagementInfo.getId());
//                        }
//                    }
//                    // 退回的单子 再启用
//                    else {
//                        //状态清空
//                        contractManagementInfo.setStatusFlag("");
//                        contractManagementInfo.setStatus("");
//                        this.updateById(contractManagementInfo);
//                        workflowService.activateInstance(contractManagementInfo.getWorkflowId(), contractManagementInfo.getId());
//                    }
//
//                }
//            }
            // 货物信息编辑
            contractGoodsInfoService.updateById(contractManagementInfo.getContractGoodsInfo());
            //流程编辑
            contractProcessInfoService.updateById(contractManagementInfo.getContractProcessInfo());
        }
        // 假如 都成功返回ok
        if (one) {
            return "OK";
        } else {
            return "NG";
        }
    }

    /**
     * 查看合同信息
     *
     * @param id
     * @return
     */
    @Override
    public ContractManagementInfo getInfo(String id) {
        // 主表信息
        ContractManagementInfo contractManagementInfo = this.selectById(id);
        //现货自运采购合同
        if ("1".equals(contractManagementInfo.getGoodsType()) && "1".equals(contractManagementInfo.getDeliverType()) && "2".equals(contractManagementInfo.getContractType())) {
            //定义出库量
            Double outWeight = 0.0d;
            //查询同名临时库出库量
            List<WarehouseInOutInfo> warehouseInOutInfoList = warehouseInOutInfoService.selectList(new EntityWrapper<WarehouseInOutInfo>()
                    .eq("warehouse_name", contractManagementInfo.getContractNo())
                    .eq("in_out_flag", "1")
                    .eq("status_flag", "3")
                    .eq("delete_flag", "0"));
            if (!CollectionUtils.isEmpty(warehouseInOutInfoList)) {
                for (WarehouseInOutInfo warehouseInOutInfo : warehouseInOutInfoList) {
                    outWeight = outWeight + Float.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight()));
                }
            }
            //定义退库量
            Double returnWeight = 0.0d;
            //查询同名临时库出库量
            List<WarehouseInOutInfo> warehouseInOutInfoList1 = warehouseInOutInfoService.selectList(new EntityWrapper<WarehouseInOutInfo>()
                    .eq("warehouse_name", contractManagementInfo.getContractNo())
                    .eq("in_out_type", "退库")
                    .eq("status_flag", "3")
                    .eq("delete_flag", "0"));
            if (!CollectionUtils.isEmpty(warehouseInOutInfoList1)) {
                for (WarehouseInOutInfo warehouseInOutInfo : warehouseInOutInfoList1) {
                    returnWeight = returnWeight +Float.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight()));
                }
            }
            contractManagementInfo.setCompletedQuantity(outWeight - returnWeight);
        }
        //现货他运采购合同
        else if ("1".equals(contractManagementInfo.getGoodsType()) && "2".equals(contractManagementInfo.getDeliverType()) && "2".equals(contractManagementInfo.getContractType())) {
            //定义出库量
            Double inWeight = 0.0d;
            //查询同合同编号入库量
            List<WarehouseInOutInfo> warehouseInOutInfoList = warehouseInOutInfoService.selectList(new EntityWrapper<WarehouseInOutInfo>()
                    .eq("contract_no", contractManagementInfo.getContractNo())
                    .eq("in_out_flag", "2")
                    .eq("status_flag", "3")
                    .eq("delete_flag", "0"));
            if (!CollectionUtils.isEmpty(warehouseInOutInfoList)) {
                for (WarehouseInOutInfo warehouseInOutInfo : warehouseInOutInfoList) {
                    inWeight = Double.valueOf(inWeight) +Float.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight()));
                }
            }
            contractManagementInfo.setCompletedQuantity(inWeight);
        }
        //代收合同
        else if ("3".equals(contractManagementInfo.getContractType())) {
            List<CollectionWarehousingRecord> collectionWarehousingRecordList=collectionWarehousingRecordService.selectList(new EntityWrapper<CollectionWarehousingRecord>()
                    .eq("contract_no",contractManagementInfo.getContractNo())
                    .eq("comp_id",contractManagementInfo.getCompId()));
            if (CollectionUtils.isNotEmpty(collectionWarehousingRecordList)){
                contractManagementInfo.setCollectionWarehousingRecordList(collectionWarehousingRecordList);
            }
        }
        //销售合同
        else {
            //定义出库量
            Double outWeight = 0.0d;
            //查询同合同编号出库量
            List<WarehouseInOutInfo> warehouseInOutInfoList = warehouseInOutInfoService.selectList(new EntityWrapper<WarehouseInOutInfo>()
                    .eq("contract_no", contractManagementInfo.getContractNo())
                    .eq("in_out_flag", "1")
                    .eq("status_flag", "3")
                    .eq("delete_flag", "0"));
            if (!CollectionUtils.isEmpty(warehouseInOutInfoList)) {
                for (WarehouseInOutInfo warehouseInOutInfo : warehouseInOutInfoList) {
                    outWeight = outWeight + Float.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight()));
                }
            }
            //定义运输损耗
            Double loss = 0.0d;
            //查询同合同编号的运输任务
            TranTaskInfo tranTaskInfo = tranTaskInfoService.selectOne(new EntityWrapper<TranTaskInfo>()
                    .eq("contract_no", contractManagementInfo.getContractNo())
                    .eq("delete_flag", "0"));
            if (tranTaskInfo != null) {
                //定义装车净重
                Double loadNetWeight = 0.0d;
                //定义卸车净重
                Double unloadNetWeight = 0.0d;
                //查询运输车辆
                List<TranCarInfo> tranCarInfoList = tranCarInfoService.selectList(new EntityWrapper<TranCarInfo>()
                        .eq("info_id", tranTaskInfo.getId())
                        .eq("status_flag", "1")
                        .eq("delete_flag", "0"));
                if (!CollectionUtils.isEmpty(tranCarInfoList)) {
                    for (TranCarInfo tranCarInfo : tranCarInfoList) {
                        loadNetWeight = loadNetWeight + tranCarInfo.getLoadNetWeight();
                        unloadNetWeight = unloadNetWeight + tranCarInfo.getUnloadNetWeight();
                    }
                    loss = loadNetWeight - unloadNetWeight;
                }
            }
            //定义退库量
            Double returnWeight = 0.0d;
            //查询同合同编号出库量
            List<WarehouseInOutInfo> warehouseInOutInfoList1 = warehouseInOutInfoService.selectList(new EntityWrapper<WarehouseInOutInfo>()
                    .eq("contract_no", contractManagementInfo.getContractNo())
                    .eq("in_out_type", "退库")
                    .eq("status_flag", "3")
                    .eq("delete_flag", "0"));
            if (!CollectionUtils.isEmpty(warehouseInOutInfoList1)) {
                for (WarehouseInOutInfo warehouseInOutInfo : warehouseInOutInfoList1) {
                    returnWeight = returnWeight +Float.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight()));
                }
            }
            contractManagementInfo.setCompletedQuantity(outWeight - loss - returnWeight);
        }
        //货物信息
        ContractGoodsInfo contractGoodsInfo = contractGoodsInfoService.selectOne(new EntityWrapper<ContractGoodsInfo>().eq(ContractGoodsInfo.QueryFiles.CONTRACT_ID, id));
        //流程信息
        ContractProcessInfo contractProcessInfo = contractProcessInfoService.selectOne(new EntityWrapper<ContractProcessInfo>().eq(ContractGoodsInfo.QueryFiles.CONTRACT_ID, id));
        contractManagementInfo.setContractGoodsInfo(contractGoodsInfo);
        contractManagementInfo.setContractProcessInfo(contractProcessInfo);
        String taskId = "";
        // 只有待审核状态才有taskId
        if (StringUtils.isNotBlank(contractManagementInfo.getWorkflowId())) {
            JSONObject jsonObject = workflowService.getActiveTask(Lists.newArrayList(contractManagementInfo.getWorkflowId()), contractManagementInfo.getId());
            taskId = jsonObject.getString("taskId");
            contractManagementInfo.setTaskId(taskId);
        }
        return contractManagementInfo;
    }

    /**
     * 信息分页列表查询
     *
     * @param contractManagementInfo
     * @return
     */
    @Override
    public Page<ContractManagementInfo> selectInfo(ContractManagementInfo contractManagementInfo) {
        Map<String, Object> pageView = new HashMap<>();
        // 状态类型（1未完成2已完成3待回款）
        pageView.put("startRecord", (contractManagementInfo.getCurrentPage() - 1)
                * contractManagementInfo.getPageSize());
        //  公司ID
        pageView.put("compId", AuthSecurityUtils.getCurrentUserInfo().getCompId());
        pageView.put("searchKeyWord", contractManagementInfo.getSearchKeyWord());
        pageView.put("goodsType", contractManagementInfo.getGoodsType());
        pageView.put("startDate", contractManagementInfo.getStartDate());
        pageView.put("endDate", contractManagementInfo.getEndDate());
        pageView.put("searchType", contractManagementInfo.getSearchType());
        pageView.put("agreementType", contractManagementInfo.getAgreementType());
        pageView.put("contractType", contractManagementInfo.getContractType());
        pageView.put("pageSize", contractManagementInfo.getPageSize());
        pageView.put("currentPage", contractManagementInfo.getCurrentPage());
        // 查询服务商总数
        Integer dataCount = baseMapper.getCountByCondition(pageView);
        List<ContractManagementInfo> dataList = baseMapper.getListByCondition(pageView);
        if (!CollectionUtils.isEmpty(dataList)) {
            for (ContractManagementInfo contractManagementInfo1 : dataList) {
                //现货自运采购合同
                if ("1".equals(contractManagementInfo1.getGoodsType()) && "1".equals(contractManagementInfo1.getDeliverType()) && "2".equals(contractManagementInfo1.getContractType())) {
                    //定义出库量
                    Double outWeight = 0.0d;
                    //查询同名临时库出库量
                    List<StockPurchaseReceiptReport> stockPurchaseReceiptReportList = stockPurchaseReceiptReportService.selectList(new EntityWrapper<StockPurchaseReceiptReport>()
                            .eq("warehouse_name", contractManagementInfo1.getContractNo())
                            .ge("status_flag", "1")
                            .eq("delete_flag", "0"));
                    if (!CollectionUtils.isEmpty(stockPurchaseReceiptReportList)) {
                        for (StockPurchaseReceiptReport stockPurchaseReceiptReport : stockPurchaseReceiptReportList) {
                            outWeight = outWeight + stockPurchaseReceiptReport.getSettlementWeight();
                        }
                    }
                    //定义退库量
                    Double returnWeight = 0.0d;
                    //查询同名临时库出库量
                    List<WarehouseInOutInfo> warehouseInOutInfoList1 = warehouseInOutInfoService.selectList(new EntityWrapper<WarehouseInOutInfo>()
                            .eq("warehouse_name", contractManagementInfo1.getContractNo())
                            .eq("in_out_type", "退库")
                            .eq("status_flag", "3")
                            .eq("delete_flag", "0"));
                    if (!CollectionUtils.isEmpty(warehouseInOutInfoList1)) {
                        for (WarehouseInOutInfo warehouseInOutInfo : warehouseInOutInfoList1) {
                            returnWeight = returnWeight + Float.valueOf(String.valueOf(warehouseInOutInfo.getNetWeight()));
                        }
                    }
                    contractManagementInfo1.setCompletedQuantity(outWeight - returnWeight);
                }
                //现货他运采购合同
                else if ("1".equals(contractManagementInfo1.getGoodsType()) && "2".equals(contractManagementInfo1.getDeliverType()) && "2".equals(contractManagementInfo1.getContractType())) {
                    //定义出库量
                    Double inWeight = 0.0d;
                    //查询同合同编号入库量
                    List<StockPurchaseReceiptReport> stockPurchaseReceiptReportList = stockPurchaseReceiptReportService.selectList(new EntityWrapper<StockPurchaseReceiptReport>()
                            .eq("contract_no", contractManagementInfo1.getContractNo())
                            .ge("status_flag", "1")
                            .eq("delete_flag", "0"));
                    if (!CollectionUtils.isEmpty(stockPurchaseReceiptReportList)) {
                        for (StockPurchaseReceiptReport stockPurchaseReceiptReport : stockPurchaseReceiptReportList) {
                            inWeight = Double.valueOf(inWeight) + stockPurchaseReceiptReport.getSettlementWeight();
                        }
                    }
                    contractManagementInfo1.setCompletedQuantity(inWeight);
                }
                //期货查确认单数量
                else if ("2".equals(contractManagementInfo1.getGoodsType())) {
                    Integer count = priceConfirmationSheetService.selectCount(new EntityWrapper<PriceConfirmationSheet>()
                            .eq("contract_no", contractManagementInfo1.getContractNo())
                            .eq("delete_flag", "0"));
                    contractManagementInfo1.setConfirmCount(count);
                }
                //销售合同
                else {
                    //定义出库量
                    Double outWeight = 0.0d;
                    //查询同合同编号出库量
                    List<StockSaleReceiptReport> stockSaleReceiptReportList = stockSaleReceiptReportService.selectList(new EntityWrapper<StockSaleReceiptReport>()
                            .eq("contract_no", contractManagementInfo1.getContractNo())
                            .eq("delete_flag", "0"));
                    if (!CollectionUtils.isEmpty(stockSaleReceiptReportList)) {
                        for (StockSaleReceiptReport stockSaleReceiptReport : stockSaleReceiptReportList) {
                            outWeight = outWeight + (stockSaleReceiptReport.getSettlementWeight()!=null?stockSaleReceiptReport.getSettlementWeight():0);
                        }
                    }
                    //定义运输损耗
//                    Double loss = 0.0d;
//                    //查询同合同编号的运输任务
//                    TranTaskInfo tranTaskInfo = tranTaskInfoService.selectOne(new EntityWrapper<TranTaskInfo>()
//                            .eq("contract_no", contractManagementInfo1.getContractNo())
//                            .eq("delete_flag", "0"));
//                    if (tranTaskInfo != null) {
//                        //定义装车净重
//                        Double loadNetWeight = 0.0d;
//                        //定义卸车净重
//                        Double unloadNetWeight = 0.0d;
//                        //查询运输车辆
//                        List<TranCarInfo> tranCarInfoList = tranCarInfoService.selectList(new EntityWrapper<TranCarInfo>()
//                                .eq("info_id", tranTaskInfo.getId())
//                                .eq("status_flag", "1")
//                                .eq("delete_flag", "0"));
//                        if (!CollectionUtils.isEmpty(tranCarInfoList)) {
//                            for (TranCarInfo tranCarInfo : tranCarInfoList) {
//                                loadNetWeight = loadNetWeight + tranCarInfo.getLoadNetWeight();
//                                unloadNetWeight = unloadNetWeight + tranCarInfo.getUnloadNetWeight();
//                            }
//                            loss = loadNetWeight - unloadNetWeight;
//                        }
//                    }
                    //定义退库量
                    Double returnWeight = 0.0d;
                    //查询同合同编号出库量
                    List<StockSaleReceiptReport> stockSaleReceiptReportList1 = stockSaleReceiptReportService.selectList(new EntityWrapper<StockSaleReceiptReport>()
                            .eq("contract_no", contractManagementInfo1.getContractNo())
                            .eq("return_flag", "1")
                            .ge("status_flag", "8")
                            .eq("delete_flag", "0"));
                    if (!CollectionUtils.isEmpty(stockSaleReceiptReportList1)) {
                        for (StockSaleReceiptReport stockSaleReceiptReport : stockSaleReceiptReportList1) {
                            returnWeight = returnWeight + stockSaleReceiptReport.getSettlementWeight();
                        }
                    }
                    //自运的销售合同
//                    if ("1".equals(contractManagementInfo1.getDeliverType())){
//                        //已完货的粮款结算阶段
////                        TranProcessInfo tranProcessInfo=tranProcessInfoService.selectOne(new EntityWrapper<TranProcessInfo>()
////                                .eq("end_flag","1")
////                                .eq("contract_no",contractManagementInfo1.getContractNo())
////                                .eq("receiving_status_flag","1"));
//                        StockSaleReceiptReport stockSaleReceiptReport =stockSaleReceiptReportService.selectOne(new EntityWrapper<StockSaleReceiptReport>()
//                        .eq("contract_no",contractManagementInfo1.getContractNo()));
//                        if (stockSaleReceiptReport!=null){
//                            //完成量等于完货净重
//                            contractManagementInfo1.setCompletedQuantity(Double.valueOf(stockSaleReceiptReport.getNetWeight()));
//                        }
//                    }
//                    else {
//                        contractManagementInfo1.setCompletedQuantity(outWeight - returnWeight);
//                    }
                    contractManagementInfo1.setCompletedQuantity(outWeight - returnWeight);
                    contractManagementInfo1.setCompletedQuantity((double)(Math.round((contractManagementInfo1.getCompletedQuantity()!=null?contractManagementInfo1.getCompletedQuantity():0f)*1000))/1000);
                }
            }
        }
        Page<ContractManagementInfo> page = new Page<>();
        page.setRecords(dataList == null ? Lists.newArrayList() : dataList);
        page.setTotal(dataCount == null ? 0 : dataCount);
        page.setCurrent(contractManagementInfo.getCurrentPage());
        page.setSize(contractManagementInfo.getPageSize());

        return page;
    }


    /**
     * 更改状态
     *
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String editStatus(String id,String endFlag) {
        // 查询合同信息
        ContractManagementInfo contractManagementInfo = this.selectById(id);
        if (contractManagementInfo != null) {
            if (StatusEnum.CONTRACT_DO.getFlag().equals(contractManagementInfo.getStatusFlag())) {
                //发运结束
                if ("1".equals(endFlag)){
                    contractManagementInfo.setStatusFlag(StatusEnum.END_OF_SHIPMENT.getFlag());
                    contractManagementInfo.setStatus(StatusEnum.END_OF_SHIPMENT.getName());
                }else{
                    contractManagementInfo.setStatusFlag(StatusEnum.CONTRACT_COMPLETED.getFlag());
                    contractManagementInfo.setStatus(StatusEnum.CONTRACT_COMPLETED.getName());
                }
                List<InOutWarehouseTask> inOutWarehouseTaskList = inOutWarehouseTaskService.selectList(new EntityWrapper<InOutWarehouseTask>()
                        .eq("comp_id", contractManagementInfo.getCompId())
                        .eq("contract_no", contractManagementInfo.getContractNo()));
                if (CollectionUtils.isNotEmpty(inOutWarehouseTaskList)){
                    for (InOutWarehouseTask inOutWarehouseTask:inOutWarehouseTaskList){
                        inOutWarehouseTask.setTaskStatusKey(StatusEnum.TASK_COMPLETED.getFlag());
                        inOutWarehouseTask.setTaskStatus(StatusEnum.TASK_COMPLETED.getName());
                        inOutWarehouseTaskService.updateById(inOutWarehouseTask);
                    }
                }
            } else if(StatusEnum.END_OF_SHIPMENT.getFlag().equals(contractManagementInfo.getStatusFlag())){
                contractManagementInfo.setStatusFlag(StatusEnum.CONTRACT_COMPLETED.getFlag());
                contractManagementInfo.setStatus(StatusEnum.CONTRACT_COMPLETED.getName());
            }
            else {
                contractManagementInfo.setStatusFlag(StatusEnum.CONTRACT_DO.getFlag());
                contractManagementInfo.setStatus(StatusEnum.CONTRACT_DO.getName());
                //货物信息
                ContractGoodsInfo contractGoodsInfo = contractGoodsInfoService.selectOne(new EntityWrapper<ContractGoodsInfo>().eq(ContractGoodsInfo.QueryFiles.CONTRACT_ID, contractManagementInfo.getId()));
                //查询这个合同是否有运输任务，如果没有运输任务，创建反馈
                TranTaskInfo tranTaskInfo1 = tranTaskInfoService.selectOne(new EntityWrapper<TranTaskInfo>()
                    .eq("contract_no",contractManagementInfo.getContractNo()));
                if(tranTaskInfo1 == null){
                    //如果是他运现货采购合同，生成发货反馈
                    if("1".equals(contractManagementInfo.getGoodsType()) && "2".equals(contractManagementInfo.getDeliverType()) && "2".equals(contractManagementInfo.getContractType())
                            && contractManagementInfo.getFeedbackLeader() != null
                    ){
                        TranTaskInfo tranTaskInfo = new TranTaskInfo();
                        tranTaskInfo.setId(IdGenerator.generateUUID());
                        tranTaskInfo.setCompId(AuthSecurityUtils.getCurrentUserInfo().getCompId());
                        tranTaskInfo.setContractNo(contractManagementInfo.getContractNo());
                        tranTaskInfo.setWeight(contractManagementInfo.getWeight());
                        tranTaskInfo.setGoodsName(contractGoodsInfo.getGoodsName());
                        tranTaskInfo.setGoodsNameKey(contractGoodsInfo.getGoodsNameKey());
                        tranTaskInfo.setStartPrivate(contractManagementInfo.getSourceProvince());
                        tranTaskInfo.setStartCity(contractManagementInfo.getSourceCity());
                        tranTaskInfo.setStartArea(contractManagementInfo.getSourceArea());
                        tranTaskInfo.setStartDetailedAddress(contractManagementInfo.getSourceGoods());
                        tranTaskInfo.setEndPrivate(contractManagementInfo.getDeliveryProvince());
                        tranTaskInfo.setEndCity(contractManagementInfo.getDeliveryCity());
                        tranTaskInfo.setEndArea(contractManagementInfo.getDeliveryArea());
                        tranTaskInfo.setEndDetailedAddress(contractManagementInfo.getPlaceDelivery());
                        tranTaskInfo.setStatus(StatusEnum.TRAN_DO.getName());
                        tranTaskInfo.setStatusFlag(StatusEnum.TRAN_DO.getFlag());
                        tranTaskInfoService.insert(tranTaskInfo);
                        TranProcessInfo tranProcessInfo = new TranProcessInfo();
                        tranProcessInfo.setId(IdGenerator.generateUUID());
                        tranProcessInfo.setInfoId(tranTaskInfo.getId());
                        tranProcessInfo.setGoodsName(contractGoodsInfo.getGoodsName());
                        tranProcessInfo.setGoodsNameKey(contractGoodsInfo.getGoodsNameKey());
                        tranProcessInfo.setWeight(tranTaskInfo.getWeight());
                        tranProcessInfo.setContractNo(tranTaskInfo.getContractNo());
                        tranProcessInfo.setReceivingDate(tranTaskInfo.getCreateDate());
                        tranProcessInfo.setSendPrivate(contractManagementInfo.getSourceProvince());
                        tranProcessInfo.setSendCity(contractManagementInfo.getSourceCity());
                        tranProcessInfo.setSendArea(contractManagementInfo.getSourceArea());
                        tranProcessInfo.setSendDetailedAddress(contractManagementInfo.getSourceGoods());
                        tranProcessInfo.setReceivePrivate(contractManagementInfo.getDeliveryProvince());
                        tranProcessInfo.setReceiveCity(contractManagementInfo.getDeliveryCity());
                        tranProcessInfo.setReceiveArea(contractManagementInfo.getDeliveryArea());
                        tranProcessInfo.setReceiveDetailedAddress(contractManagementInfo.getPlaceDelivery());
                        tranProcessInfo.setProcessStatusFlag(StatusEnum.PROCESS_DO.getFlag());
                        tranProcessInfo.setProcessStatus(StatusEnum.PROCESS_DO.getName());
                        tranProcessInfo.setFeedbackStatusFlag(StatusEnum.FEEDBACK_DO.getFlag());
                        tranProcessInfo.setFeedbackStatus(StatusEnum.FEEDBACK_DO.getName());
                        tranProcessInfo.setTranType("他运");
                        tranProcessInfo.setTranTypeKey("4");
                        tranProcessInfo.setSender(contractManagementInfo.getFeedbackLeader());
                        tranProcessInfo.setSenderPhone(contractManagementInfo.getFeedbackLeaderPhone());
                        tranProcessInfoService.insert(tranProcessInfo);
                    }
                    //如果是他运现货销售合同，生成收货反馈
                    else if("1".equals(contractManagementInfo.getGoodsType()) && "2".equals(contractManagementInfo.getDeliverType()) && "1".equals(contractManagementInfo.getContractType())){
                        TranTaskInfo tranTaskInfo = new TranTaskInfo();
                        tranTaskInfo.setId(IdGenerator.generateUUID());
                        tranTaskInfo.setCompId(AuthSecurityUtils.getCurrentUserInfo().getCompId());
                        tranTaskInfo.setContractNo(contractManagementInfo.getContractNo());
                        tranTaskInfo.setWeight(contractManagementInfo.getWeight());
                        tranTaskInfo.setGoodsName(contractGoodsInfo.getGoodsName());
                        tranTaskInfo.setGoodsNameKey(contractGoodsInfo.getGoodsNameKey());
                        tranTaskInfo.setStartPrivate(contractManagementInfo.getSourceProvince());
                        tranTaskInfo.setStartCity(contractManagementInfo.getSourceCity());
                        tranTaskInfo.setStartArea(contractManagementInfo.getSourceArea());
                        tranTaskInfo.setStartDetailedAddress(contractManagementInfo.getSourceGoods());
                        tranTaskInfo.setEndPrivate(contractManagementInfo.getDeliveryProvince());
                        tranTaskInfo.setEndCity(contractManagementInfo.getDeliveryCity());
                        tranTaskInfo.setEndArea(contractManagementInfo.getDeliveryArea());
                        tranTaskInfo.setEndDetailedAddress(contractManagementInfo.getPlaceDelivery());
                        tranTaskInfo.setStatus(StatusEnum.TRAN_DO.getName());
                        tranTaskInfo.setStatusFlag(StatusEnum.TRAN_DO.getFlag());
                        tranTaskInfoService.insert(tranTaskInfo);
                        TranProcessInfo tranProcessInfo = new TranProcessInfo();
                        tranProcessInfo.setId(IdGenerator.generateUUID());
                        tranProcessInfo.setInfoId(tranTaskInfo.getId());
                        tranProcessInfo.setGoodsName(contractGoodsInfo.getGoodsName());
                        tranProcessInfo.setGoodsNameKey(contractGoodsInfo.getGoodsNameKey());
                        tranProcessInfo.setWeight(tranTaskInfo.getWeight());
                        tranProcessInfo.setContractNo(tranTaskInfo.getContractNo());
                        tranProcessInfo.setReceivingDate(tranTaskInfo.getCreateDate());
                        tranProcessInfo.setSendPrivate(contractManagementInfo.getSourceProvince());
                        tranProcessInfo.setSendCity(contractManagementInfo.getSourceCity());
                        tranProcessInfo.setSendArea(contractManagementInfo.getSourceArea());
                        tranProcessInfo.setSendDetailedAddress(contractManagementInfo.getSourceGoods());
                        tranProcessInfo.setReceivePrivate(contractManagementInfo.getDeliveryProvince());
                        tranProcessInfo.setReceiveCity(contractManagementInfo.getDeliveryCity());
                        tranProcessInfo.setReceiveArea(contractManagementInfo.getDeliveryArea());
                        tranProcessInfo.setReceiveDetailedAddress(contractManagementInfo.getPlaceDelivery());
                        tranProcessInfo.setProcessStatusFlag(StatusEnum.PROCESS_DO.getFlag());
                        tranProcessInfo.setProcessStatus(StatusEnum.PROCESS_DO.getName());
                        tranProcessInfo.setReceivingStatusFlag(StatusEnum.FEEDBACK_DO.getFlag());
                        tranProcessInfo.setReceivingStatus(StatusEnum.FEEDBACK_DO.getName());
                        tranProcessInfo.setTranType("他运");
                        tranProcessInfo.setTranTypeKey("4");
                        tranProcessInfo.setReceiver(contractManagementInfo.getFeedbackLeader());
                        tranProcessInfo.setReceiverPhone(contractManagementInfo.getFeedbackLeaderPhone());
                        tranProcessInfoService.insert(tranProcessInfo);
                    }
                }
            }
            this.updateById(contractManagementInfo);
            // 插入操作历史
            String staffName = this.billOperateHisService.getStaffAndName();
            // 插入操作历史
            this.billOperateHisService.saveBillOperateHis(contractManagementInfo.getId(), NumberConstant.CONSTANT_CONTRACT, staffName, null,
                    contractManagementInfo.getStatus(), null, "");
            return "OK";
        }
        cacheComponent.delPrefixKey(Const.ADMIN_CONTRACTINFO);
        return "NG";
    }

    /**
     * 查对应的合同
     * @param contractManagementInfo
     * @return
     */
    @Override
    public List<ContractManagementInfo> selectContract(ContractManagementInfo contractManagementInfo) {
        List<ContractManagementInfo> contractManagementInfoList=this.selectList(new EntityWrapper<ContractManagementInfo>()
        .eq("agreement_type",contractManagementInfo.getAgreementType())
        .eq("goods_type",contractManagementInfo.getGoodsType())
        .eq("comp_id", AuthSecurityUtils.getCurrentUserInfo().getCompId())
        .orderBy("update_date",false));
        if (CollectionUtils.isNotEmpty(contractManagementInfoList)) {
            for (ContractManagementInfo contractManagementInfo1 : contractManagementInfoList) {
                //货物信息
                ContractGoodsInfo contractGoodsInfo = contractGoodsInfoService.selectOne(new EntityWrapper<ContractGoodsInfo>().eq(ContractGoodsInfo.QueryFiles.CONTRACT_ID, contractManagementInfo1.getId()));
                //流程信息
                ContractProcessInfo contractProcessInfo = contractProcessInfoService.selectOne(new EntityWrapper<ContractProcessInfo>().eq(ContractGoodsInfo.QueryFiles.CONTRACT_ID, contractManagementInfo1.getId()));
                contractManagementInfo1.setContractGoodsInfo(contractGoodsInfo);
                contractManagementInfo1.setContractProcessInfo(contractProcessInfo);
            }
        }
        return contractManagementInfoList;
    }

    @Override
    public void exportCollection(ContractManagementInfo example, HttpServletResponse response) throws Exception {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        // 查询在船船员
        Page<ContractManagementInfo> contractManagementInfoPage = this.selectInfo(example);
        List<ContractManagementInfo> contractManagementInfos = contractManagementInfoPage.getRecords();


        // 1.Excel的头部信息
        String headerTitle = "";

        // 2.创建一个webbook 对应一个Excel文件
        HSSFWorkbook wb = new HSSFWorkbook();

        // 3.在webbook中添加一个sheet，对应Excel文件中的sheet
        HSSFSheet sheet;

        sheet = wb.createSheet("代收合同信息");
        headerTitle = "代收合同信息";

        // 4.设置打印参数
        sheet.setMargin(HSSFSheet.TopMargin, (short) 1);// 页边距（上）
        sheet.setMargin(HSSFSheet.BottomMargin, (short) 1);// 页边距（下）
        sheet.setMargin(HSSFSheet.LeftMargin, (short) 1);// 页边距（左）
        sheet.setMargin(HSSFSheet.RightMargin, (short) 1);// 页边距（右）

        // 不显示网格
        sheet.setDisplayGridlines(false);
        // 设置水平居中
        sheet.setHorizontallyCenter(true);

        /**************** 数据行样式 start ****************/
        HSSFFont fontTitle = wb.createFont();
        fontTitle.setFontName("宋体");
        fontTitle.setFontHeightInPoints((short) 14);
        // 设置字体加粗
        fontTitle.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);

        HSSFFont fontComp = wb.createFont();
        fontComp.setFontName("宋体");
        fontComp.setFontHeightInPoints((short) 16);
        // 设置字体加粗
        fontComp.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);

        HSSFFont fontDetail = wb.createFont();
        fontDetail.setFontName("宋体");
        fontDetail.setFontHeightInPoints((short) 12);

        // title
        HSSFCellStyle styleTitle = wb.createCellStyle();
        // 指定单元格居中对齐
        styleTitle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        // 指定单元格垂直居中对齐
        styleTitle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        // 指定单元格自动换行
        styleTitle.setWrapText(true);
        // 设置单元格字体
        styleTitle.setFont(fontTitle);
        // 右边框
        styleTitle.setBorderRight(HSSFCellStyle.BORDER_NONE);
        // 左边框
        styleTitle.setBorderLeft(HSSFCellStyle.BORDER_NONE);
        // 上边框
        styleTitle.setBorderTop(HSSFCellStyle.BORDER_NONE);
        // 下边框
        styleTitle.setBorderBottom(HSSFCellStyle.BORDER_NONE);

        // title
        HSSFCellStyle styleComp = wb.createCellStyle();
        // 指定单元格居中对齐
        styleComp.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        // 指定单元格垂直居中对齐
        styleComp.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        // 指定单元格自动换行
        styleComp.setWrapText(true);
        // 设置单元格字体
        styleComp.setFont(fontComp);
        // 右边框
        styleComp.setBorderRight(HSSFCellStyle.BORDER_NONE);
        // 左边框
        styleComp.setBorderLeft(HSSFCellStyle.BORDER_NONE);
        // 上边框
        styleComp.setBorderTop(HSSFCellStyle.BORDER_NONE);
        // 下边框
        styleComp.setBorderBottom(HSSFCellStyle.BORDER_NONE);

        HSSFCellStyle styleInfo = wb.createCellStyle();
        // 指定单元格居中对齐
        styleInfo.setAlignment(HSSFCellStyle.ALIGN_LEFT);
        // 指定单元格垂直居中对齐
        styleInfo.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        // 指定单元格自动换行
        styleInfo.setWrapText(true);
        // 设置单元格字体
        styleInfo.setFont(fontDetail);
        // 右边框
        styleInfo.setBorderRight(HSSFCellStyle.BORDER_NONE);
        // 左边框
        styleInfo.setBorderLeft(HSSFCellStyle.BORDER_NONE);
        // 上边框
        styleInfo.setBorderTop(HSSFCellStyle.BORDER_NONE);
        // 下边框
        styleInfo.setBorderBottom(HSSFCellStyle.BORDER_NONE);

        HSSFCellStyle styleDetail = wb.createCellStyle();
        // 指定单元格居中对齐
        styleDetail.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        // 指定单元格垂直居中对齐
        styleDetail.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        // 指定单元格自动换行
        styleDetail.setWrapText(true);
        // 设置单元格字体
        styleDetail.setFont(fontDetail);
        // 右边框
        styleDetail.setBorderRight(HSSFCellStyle.BORDER_THIN);
        // 左边框
        styleDetail.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        // 上边框
        styleDetail.setBorderTop(HSSFCellStyle.BORDER_THIN);
        // 下styleDetailTitle
        styleDetail.setBorderBottom(HSSFCellStyle.BORDER_THIN);

        HSSFCellStyle contextstyle = wb.createCellStyle();
        // 指定单元格居中对齐
        contextstyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        // 指定单元格垂直居中对齐
        contextstyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        // 指定单元格自动换行
        contextstyle.setWrapText(true);
        // 设置单元格字体
        contextstyle.setFont(fontDetail);
        // 右边框
        contextstyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
        // 左边框
        contextstyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        // 上边框
        contextstyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
        // 下styleDetailTitle
        contextstyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);

        HSSFCellStyle styleDetailYellow = wb.createCellStyle();
        // 指定单元格居中对齐
        styleDetailYellow.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        // 指定单元格垂直居中对齐
        styleDetailYellow.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        // 指定单元格自动换行
        styleDetailYellow.setWrapText(true);
        // 设置单元格字体
        styleDetailYellow.setFont(fontDetail);
        // 右边框
        styleDetailYellow.setBorderRight(HSSFCellStyle.BORDER_THIN);
        // 左边框
        styleDetailYellow.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        // 上边框
        styleDetailYellow.setBorderTop(HSSFCellStyle.BORDER_THIN);
        // 下styleDetailTitle
        styleDetailYellow.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        styleDetailYellow.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
        styleDetailYellow.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);


        HSSFCellStyle styleDetailLeft = wb.createCellStyle();
        // 指定单元格居中对齐
        styleDetailLeft.setAlignment(HSSFCellStyle.ALIGN_LEFT);
        // 指定单元格垂直居中对齐
        styleDetailLeft.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        // 指定单元格自动换行
        styleDetailLeft.setWrapText(true);
        // 设置单元格字体
        styleDetailLeft.setFont(fontDetail);
        // 右边框
        styleDetailLeft.setBorderRight(HSSFCellStyle.BORDER_THIN);
        // 左边框
        styleDetailLeft.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        // 上边框
        styleDetailLeft.setBorderTop(HSSFCellStyle.BORDER_THIN);
        // 下styleDetailTitle
        styleDetailLeft.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        /**************** 数据行样式 end ****************/

        // 设置列宽
        sheet.setColumnWidth(0, 1 * 256 + 184);
        sheet.setColumnWidth(1, 6 * 256 + 184);
        sheet.setColumnWidth(2, 12 * 256 + 184);
        sheet.setColumnWidth(3, 12 * 256 + 184);
        sheet.setColumnWidth(4, 12 * 256 + 184);
        sheet.setColumnWidth(5, 12 * 256 + 184);
        sheet.setColumnWidth(6, 12 * 256 + 184);
        sheet.setColumnWidth(7, 12 * 256 + 184);
        sheet.setColumnWidth(8, 12 * 256 + 184);
        sheet.setColumnWidth(9, 12 * 256 + 184);
        sheet.setColumnWidth(10, 12 * 256 + 184);
        sheet.setColumnWidth(11, 12 * 256 + 184);
        sheet.setColumnWidth(12, 12 * 256 + 184);
        sheet.setColumnWidth(13, 12 * 256 + 184);
        sheet.setColumnWidth(14, 12 * 256 + 184);
        sheet.setColumnWidth(15, 1 * 256 + 184);

        // 创建单元格对象
        HSSFCell cell = null;

        // 创建打印设置对象
        HSSFPrintSetup ps = sheet.getPrintSetup();
        // 打印方向，true：横向，false：纵向(默认)
        ps.setLandscape(false);
        // // 打印质量
        // ps.setVResolution((short) 700)
        // 设置缩放比例
        ps.setScale((short) 80);
        // 纸张类型
        ps.setPaperSize(HSSFPrintSetup.A4_PAPERSIZE);


        int rownum = 1;
        HSSFRow row0 = sheet.createRow((int) rownum);
        row0.setHeightInPoints(25);
        cell = row0.createCell(1);
        cell.setCellStyle(styleTitle);
        cell.setCellValue("代收合同信息");
        sheet.addMergedRegion(new CellRangeAddress(rownum, rownum, (short) 1, (short) 13));
        cell = row0.createCell(2);
        cell.setCellStyle(styleTitle);
        cell = row0.createCell(3);
        cell.setCellStyle(styleTitle);
        cell = row0.createCell(4);
        cell.setCellStyle(styleTitle);
        cell = row0.createCell(5);
        cell.setCellStyle(styleTitle);
        cell = row0.createCell(6);
        cell.setCellStyle(styleTitle);
        cell = row0.createCell(7);
        cell.setCellStyle(styleTitle);
        cell = row0.createCell(8);
        cell.setCellStyle(styleTitle);
        cell = row0.createCell(9);
        cell.setCellStyle(styleTitle);
        cell = row0.createCell(10);
        cell.setCellStyle(styleTitle);
        cell = row0.createCell(11);
        cell.setCellStyle(styleTitle);
        cell = row0.createCell(12);
        cell.setCellStyle(styleTitle);
        cell = row0.createCell(13);
        cell.setCellStyle(styleTitle);
        cell = row0.createCell(14);
        cell.setCellStyle(styleTitle);
        rownum++;

        HSSFRow row1 = sheet.createRow((int) rownum);
        row1.setHeightInPoints(30);
        cell = row1.createCell(1);
        cell.setCellValue("序号");
        cell.setCellStyle(styleDetail);
        cell = row1.createCell(2);
        cell.setCellValue("合同编号");
        cell.setCellStyle(styleDetail);
        cell = row1.createCell(3);
        cell.setCellValue("货名");
        cell.setCellStyle(styleDetail);
        cell = row1.createCell(4);
        cell.setCellValue("买方");
        cell.setCellStyle(styleDetail);
        cell = row1.createCell(5);
        cell.setCellValue("卖方");
        cell.setCellStyle(styleDetail);
        cell = row1.createCell(6);
        cell.setCellValue("重量（吨）");
        cell.setCellStyle(styleDetail);
        cell = row1.createCell(7);
        cell.setCellValue("已完成（吨）");
        cell.setCellStyle(styleDetail);
        cell = row1.createCell(8);
        cell.setCellValue("应付（元）");
        cell.setCellStyle(styleDetail);
        cell = row1.createCell(9);
        cell.setCellValue("已付（元）");
        cell.setCellStyle(styleDetail);
        cell = row1.createCell(10);
        cell.setCellValue("应收（元）");
        cell.setCellStyle(styleDetail);
        cell = row1.createCell(11);
        cell.setCellValue("已收（元）");
        cell.setCellStyle(styleDetail);
        cell = row1.createCell(12);
        cell.setCellValue("已开销发票（元）");
        cell.setCellStyle(styleDetail);
        cell = row1.createCell(13);
        cell.setCellValue("状态");
        cell.setCellStyle(styleDetail);
        cell = row1.createCell(14);
        cell.setCellValue("签订日期");
        cell.setCellStyle(styleDetail);


        rownum++;

        // 详情信息
        if (CollectionUtils.isNotEmpty(contractManagementInfos)) {
            for (int i = 0; i < contractManagementInfos.size(); i++) {
                ContractManagementInfo contractManagementInfo = contractManagementInfos.get(i);
                HSSFRow rowx = sheet.createRow((int) rownum);
                rowx.setHeightInPoints(20);
                cell = rowx.createCell(1);
                cell.setCellValue(i + 1);
                cell.setCellStyle(styleDetail);
                cell = rowx.createCell(2);
                cell.setCellValue(editString(contractManagementInfo.getContractNo()));
                cell.setCellStyle(styleDetail);
                cell = rowx.createCell(3);
                cell.setCellValue(editString(contractManagementInfo.getGoodsName()));
                cell.setCellStyle(styleDetail);
                cell = rowx.createCell(4);
                cell.setCellValue(editString(contractManagementInfo.getBuyer()));
                cell.setCellStyle(styleDetail);
                cell = rowx.createCell(5);
                cell.setCellValue(editString(contractManagementInfo.getSeller()));
                cell.setCellStyle(styleDetail);
                cell = rowx.createCell(6);
                cell.setCellValue(editFloat(contractManagementInfo.getWeight()));
                cell.setCellStyle(contextstyle);
                HSSFDataFormat format1 = wb.createDataFormat(); // 此处设置数据格式
                contextstyle.setDataFormat(format1.getFormat("0.00"));
                cell = rowx.createCell(7);
                cell.setCellValue(editDouble(contractManagementInfo.getCompleted()));
                cell.setCellStyle(contextstyle);
                cell = rowx.createCell(8);
                cell.setCellValue(editDouble(contractManagementInfo.getAmountIngPayable()));
                cell.setCellStyle(contextstyle);
                cell = rowx.createCell(9);
                cell.setCellValue(editDouble(contractManagementInfo.getAmountEdPayableNew()));
                cell.setCellStyle(contextstyle);
                cell = rowx.createCell(10);
                cell.setCellValue(editDouble(contractManagementInfo.getAmountNotCollectable()));
                cell.setCellStyle(contextstyle);
                cell = rowx.createCell(11);
                cell.setCellValue(editDouble(contractManagementInfo.getAmountEdCollectionable()));
                cell.setCellStyle(contextstyle);
                cell = rowx.createCell(12);
                cell.setCellValue(editDouble(contractManagementInfo.getInvoiced()));
                cell.setCellStyle(styleDetail);
                cell = rowx.createCell(13);
                cell.setCellValue(editString(contractManagementInfo.getStatus()!=null?contractManagementInfo.getStatus():contractManagementInfo.getApproveStatus()));
                cell.setCellStyle(styleDetail);
                cell = rowx.createCell(14);
                cell.setCellValue(DateUtil.formatDate(contractManagementInfo.getSigningDate() != null ? addDateOneDay(contractManagementInfo.getSigningDate()) : addDateOneDay(new Date()), DateUtils.DATE_FMT_YYYY_MM_DD));
                cell.setCellStyle(styleDetail);
                rownum++;
            }

        }


        String path = null;
        String tempPath = null;
        String excelPath = null;

        try {

            // 取得绝对路径
            tempPath = URLDecoder.decode((localPath), "utf-8");

            // EXCEL路径
            excelPath = "/web/temp/repair/" + DateUtil.formatDate(new Date(), DateUtils.DATE_FMT_YYYYMMDD_NS) + '/'
                    + UUID.randomUUID().toString().replaceAll("-", "");

            path = tempPath + excelPath + '/' + "代收合同信息"
                    + ".xls";

        } catch (Exception e) {
            log.debug(e.getMessage());
        }
        // 下载
        download(path, response, wb);
    }

    @Override
    public void exportStorageFee(ContractManagementInfo example, HttpServletResponse response) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        // 查询在船船员
        Page<ContractManagementInfo> contractManagementInfoPage = this.selectInfo(example);
        List<ContractManagementInfo> contractManagementInfos = contractManagementInfoPage.getRecords();


        // 1.Excel的头部信息
        String headerTitle = "";

        // 2.创建一个webbook 对应一个Excel文件
        HSSFWorkbook wb = new HSSFWorkbook();

        // 3.在webbook中添加一个sheet，对应Excel文件中的sheet
        HSSFSheet sheet;

        sheet = wb.createSheet("代储合同信息");
        headerTitle = "代储合同信息";

        // 4.设置打印参数
        sheet.setMargin(HSSFSheet.TopMargin, (short) 1);// 页边距（上）
        sheet.setMargin(HSSFSheet.BottomMargin, (short) 1);// 页边距（下）
        sheet.setMargin(HSSFSheet.LeftMargin, (short) 1);// 页边距（左）
        sheet.setMargin(HSSFSheet.RightMargin, (short) 1);// 页边距（右）

        // 不显示网格
        sheet.setDisplayGridlines(false);
        // 设置水平居中
        sheet.setHorizontallyCenter(true);

        /**************** 数据行样式 start ****************/
        HSSFFont fontTitle = wb.createFont();
        fontTitle.setFontName("宋体");
        fontTitle.setFontHeightInPoints((short) 14);
        // 设置字体加粗
        fontTitle.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);

        HSSFFont fontComp = wb.createFont();
        fontComp.setFontName("宋体");
        fontComp.setFontHeightInPoints((short) 16);
        // 设置字体加粗
        fontComp.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);

        HSSFFont fontDetail = wb.createFont();
        fontDetail.setFontName("宋体");
        fontDetail.setFontHeightInPoints((short) 12);

        // title
        HSSFCellStyle styleTitle = wb.createCellStyle();
        // 指定单元格居中对齐
        styleTitle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        // 指定单元格垂直居中对齐
        styleTitle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        // 指定单元格自动换行
        styleTitle.setWrapText(true);
        // 设置单元格字体
        styleTitle.setFont(fontTitle);
        // 右边框
        styleTitle.setBorderRight(HSSFCellStyle.BORDER_NONE);
        // 左边框
        styleTitle.setBorderLeft(HSSFCellStyle.BORDER_NONE);
        // 上边框
        styleTitle.setBorderTop(HSSFCellStyle.BORDER_NONE);
        // 下边框
        styleTitle.setBorderBottom(HSSFCellStyle.BORDER_NONE);

        // title
        HSSFCellStyle styleComp = wb.createCellStyle();
        // 指定单元格居中对齐
        styleComp.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        // 指定单元格垂直居中对齐
        styleComp.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        // 指定单元格自动换行
        styleComp.setWrapText(true);
        // 设置单元格字体
        styleComp.setFont(fontComp);
        // 右边框
        styleComp.setBorderRight(HSSFCellStyle.BORDER_NONE);
        // 左边框
        styleComp.setBorderLeft(HSSFCellStyle.BORDER_NONE);
        // 上边框
        styleComp.setBorderTop(HSSFCellStyle.BORDER_NONE);
        // 下边框
        styleComp.setBorderBottom(HSSFCellStyle.BORDER_NONE);

        HSSFCellStyle styleInfo = wb.createCellStyle();
        // 指定单元格居中对齐
        styleInfo.setAlignment(HSSFCellStyle.ALIGN_LEFT);
        // 指定单元格垂直居中对齐
        styleInfo.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        // 指定单元格自动换行
        styleInfo.setWrapText(true);
        // 设置单元格字体
        styleInfo.setFont(fontDetail);
        // 右边框
        styleInfo.setBorderRight(HSSFCellStyle.BORDER_NONE);
        // 左边框
        styleInfo.setBorderLeft(HSSFCellStyle.BORDER_NONE);
        // 上边框
        styleInfo.setBorderTop(HSSFCellStyle.BORDER_NONE);
        // 下边框
        styleInfo.setBorderBottom(HSSFCellStyle.BORDER_NONE);

        HSSFCellStyle styleDetail = wb.createCellStyle();
        // 指定单元格居中对齐
        styleDetail.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        // 指定单元格垂直居中对齐
        styleDetail.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        // 指定单元格自动换行
        styleDetail.setWrapText(true);
        // 设置单元格字体
        styleDetail.setFont(fontDetail);
        // 右边框
        styleDetail.setBorderRight(HSSFCellStyle.BORDER_THIN);
        // 左边框
        styleDetail.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        // 上边框
        styleDetail.setBorderTop(HSSFCellStyle.BORDER_THIN);
        // 下styleDetailTitle
        styleDetail.setBorderBottom(HSSFCellStyle.BORDER_THIN);

        HSSFCellStyle contextstyle = wb.createCellStyle();
        // 指定单元格居中对齐
        contextstyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        // 指定单元格垂直居中对齐
        contextstyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        // 指定单元格自动换行
        contextstyle.setWrapText(true);
        // 设置单元格字体
        contextstyle.setFont(fontDetail);
        // 右边框
        contextstyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
        // 左边框
        contextstyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        // 上边框
        contextstyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
        // 下styleDetailTitle
        contextstyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);

        HSSFCellStyle styleDetailYellow = wb.createCellStyle();
        // 指定单元格居中对齐
        styleDetailYellow.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        // 指定单元格垂直居中对齐
        styleDetailYellow.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        // 指定单元格自动换行
        styleDetailYellow.setWrapText(true);
        // 设置单元格字体
        styleDetailYellow.setFont(fontDetail);
        // 右边框
        styleDetailYellow.setBorderRight(HSSFCellStyle.BORDER_THIN);
        // 左边框
        styleDetailYellow.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        // 上边框
        styleDetailYellow.setBorderTop(HSSFCellStyle.BORDER_THIN);
        // 下styleDetailTitle
        styleDetailYellow.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        styleDetailYellow.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
        styleDetailYellow.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);


        HSSFCellStyle styleDetailLeft = wb.createCellStyle();
        // 指定单元格居中对齐
        styleDetailLeft.setAlignment(HSSFCellStyle.ALIGN_LEFT);
        // 指定单元格垂直居中对齐
        styleDetailLeft.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        // 指定单元格自动换行
        styleDetailLeft.setWrapText(true);
        // 设置单元格字体
        styleDetailLeft.setFont(fontDetail);
        // 右边框
        styleDetailLeft.setBorderRight(HSSFCellStyle.BORDER_THIN);
        // 左边框
        styleDetailLeft.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        // 上边框
        styleDetailLeft.setBorderTop(HSSFCellStyle.BORDER_THIN);
        // 下styleDetailTitle
        styleDetailLeft.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        /**************** 数据行样式 end ****************/

        // 设置列宽
        sheet.setColumnWidth(0, 1 * 256 + 184);
        sheet.setColumnWidth(1, 6 * 256 + 184);
        sheet.setColumnWidth(2, 12 * 256 + 184);
        sheet.setColumnWidth(3, 12 * 256 + 184);
        sheet.setColumnWidth(4, 12 * 256 + 184);
        sheet.setColumnWidth(5, 12 * 256 + 184);
        sheet.setColumnWidth(6, 12 * 256 + 184);
        sheet.setColumnWidth(7, 12 * 256 + 184);
        sheet.setColumnWidth(8, 12 * 256 + 184);
        sheet.setColumnWidth(9, 12 * 256 + 184);
        sheet.setColumnWidth(10, 12 * 256 + 184);
        sheet.setColumnWidth(11, 12 * 256 + 184);
        sheet.setColumnWidth(12, 12 * 256 + 184);
        sheet.setColumnWidth(13, 12 * 256 + 184);
        sheet.setColumnWidth(14, 12 * 256 + 184);
        sheet.setColumnWidth(15, 1 * 256 + 184);

        // 创建单元格对象
        HSSFCell cell = null;

        // 创建打印设置对象
        HSSFPrintSetup ps = sheet.getPrintSetup();
        // 打印方向，true：横向，false：纵向(默认)
        ps.setLandscape(false);
        // // 打印质量
        // ps.setVResolution((short) 700)
        // 设置缩放比例
        ps.setScale((short) 80);
        // 纸张类型
        ps.setPaperSize(HSSFPrintSetup.A4_PAPERSIZE);


        int rownum = 1;
        HSSFRow row0 = sheet.createRow((int) rownum);
        row0.setHeightInPoints(25);
        cell = row0.createCell(1);
        cell.setCellStyle(styleTitle);
        cell.setCellValue("代储合同信息");
        sheet.addMergedRegion(new CellRangeAddress(rownum, rownum, (short) 1, (short) 13));
        cell = row0.createCell(2);
        cell.setCellStyle(styleTitle);
        cell = row0.createCell(3);
        cell.setCellStyle(styleTitle);
        cell = row0.createCell(4);
        cell.setCellStyle(styleTitle);
        cell = row0.createCell(5);
        cell.setCellStyle(styleTitle);
        cell = row0.createCell(6);
        cell.setCellStyle(styleTitle);
        cell = row0.createCell(7);
        cell.setCellStyle(styleTitle);
        cell = row0.createCell(8);
        cell.setCellStyle(styleTitle);
        cell = row0.createCell(9);
        cell.setCellStyle(styleTitle);
        cell = row0.createCell(10);
        cell.setCellStyle(styleTitle);
        cell = row0.createCell(11);
        cell.setCellStyle(styleTitle);
        cell = row0.createCell(12);
        cell.setCellStyle(styleTitle);
        cell = row0.createCell(13);
        cell.setCellStyle(styleTitle);
        cell = row0.createCell(14);
        cell.setCellStyle(styleTitle);
        rownum++;

        HSSFRow row1 = sheet.createRow((int) rownum);
        row1.setHeightInPoints(30);
        cell = row1.createCell(1);
        cell.setCellValue("序号");
        cell.setCellStyle(styleDetail);
        cell = row1.createCell(2);
        cell.setCellValue("合同编号");
        cell.setCellStyle(styleDetail);
        cell = row1.createCell(3);
        cell.setCellValue("货名");
        cell.setCellStyle(styleDetail);
        cell = row1.createCell(4);
        cell.setCellValue("买方");
        cell.setCellStyle(styleDetail);
        cell = row1.createCell(5);
        cell.setCellValue("卖方");
        cell.setCellStyle(styleDetail);
        cell = row1.createCell(6);
        cell.setCellValue("重量（吨）");
        cell.setCellStyle(styleDetail);
        cell = row1.createCell(7);
        cell.setCellValue("已完成（吨）");
        cell.setCellStyle(styleDetail);
        cell = row1.createCell(8);
        cell.setCellValue("粮款（元）");
        cell.setCellStyle(styleDetail);
        cell = row1.createCell(9);
        cell.setCellValue("代储费（元）");
        cell.setCellStyle(styleDetail);
        cell = row1.createCell(10);
        cell.setCellValue("合计应收（元）");
        cell.setCellStyle(styleDetail);
        cell = row1.createCell(11);
        cell.setCellValue("已收（元）");
        cell.setCellStyle(styleDetail);
        cell = row1.createCell(12);
        cell.setCellValue("已开发票（元）");
        cell.setCellStyle(styleDetail);
        cell = row1.createCell(13);
        cell.setCellValue("状态");
        cell.setCellStyle(styleDetail);
        cell = row1.createCell(14);
        cell.setCellValue("签订日期");
        cell.setCellStyle(styleDetail);


        rownum++;

        // 详情信息
        if (CollectionUtils.isNotEmpty(contractManagementInfos)) {
            for (int i = 0; i < contractManagementInfos.size(); i++) {
                ContractManagementInfo contractManagementInfo = contractManagementInfos.get(i);
                HSSFRow rowx = sheet.createRow((int) rownum);
                rowx.setHeightInPoints(20);
                cell = rowx.createCell(1);
                cell.setCellValue(i + 1);
                cell.setCellStyle(styleDetail);
                cell = rowx.createCell(2);
                cell.setCellValue(editString(contractManagementInfo.getContractNo()));
                cell.setCellStyle(styleDetail);
                cell = rowx.createCell(3);
                cell.setCellValue(editString(contractManagementInfo.getGoodsName()));
                cell.setCellStyle(styleDetail);
                cell = rowx.createCell(4);
                cell.setCellValue(editString(contractManagementInfo.getBuyer()));
                cell.setCellStyle(styleDetail);
                cell = rowx.createCell(5);
                cell.setCellValue(editString(contractManagementInfo.getSeller()));
                cell.setCellStyle(styleDetail);
                cell = rowx.createCell(6);
                cell.setCellValue(editFloat(contractManagementInfo.getWeight()));
                cell.setCellStyle(contextstyle);
                HSSFDataFormat format1 = wb.createDataFormat(); // 此处设置数据格式
                contextstyle.setDataFormat(format1.getFormat("0.00"));
                cell = rowx.createCell(7);
                cell.setCellValue(editDouble(contractManagementInfo.getCompletedQuantity()));
                cell.setCellStyle(contextstyle);
                cell = rowx.createCell(8);
                cell.setCellValue(editDouble(contractManagementInfo.getGrainMoney()));
                cell.setCellStyle(contextstyle);
                cell = rowx.createCell(9);
                cell.setCellValue(editDouble(contractManagementInfo.getStorageFeeNew()));
                cell.setCellStyle(contextstyle);
                cell = rowx.createCell(10);
                cell.setCellValue(editDouble(contractManagementInfo.getGrainMoney()+contractManagementInfo.getStorageFeeNew()));
                cell.setCellStyle(contextstyle);
                cell = rowx.createCell(11);
                cell.setCellValue(editDouble(contractManagementInfo.getGrainMoneyEd()+contractManagementInfo.getDepositReceived()));
                cell.setCellStyle(contextstyle);
                cell = rowx.createCell(12);
                cell.setCellValue(editDouble(contractManagementInfo.getGoodsNames()));
                cell.setCellStyle(styleDetail);
                cell = rowx.createCell(13);
                cell.setCellValue(editString(contractManagementInfo.getStatus()!=null?contractManagementInfo.getStatus():contractManagementInfo.getApproveStatus()));
                cell.setCellStyle(styleDetail);
                cell = rowx.createCell(14);
                cell.setCellValue(DateUtil.formatDate(contractManagementInfo.getSigningDate() != null ? addDateOneDay(contractManagementInfo.getSigningDate()) : addDateOneDay(new Date()), DateUtils.DATE_FMT_YYYY_MM_DD));
                cell.setCellStyle(styleDetail);
                rownum++;
            }

        }


        String path = null;
        String tempPath = null;
        String excelPath = null;

        try {

            // 取得绝对路径
            tempPath = URLDecoder.decode((localPath), "utf-8");

            // EXCEL路径
            excelPath = "/web/temp/repair/" + DateUtil.formatDate(new Date(), DateUtils.DATE_FMT_YYYYMMDD_NS) + '/'
                    + UUID.randomUUID().toString().replaceAll("-", "");

            path = tempPath + excelPath + '/' + "代收合同信息"
                    + ".xls";

        } catch (Exception e) {
            log.debug(e.getMessage());
        }
        // 下载
        download(path, response, wb);
    }

    @Override
    public Double selectSumSale(String compId) {
        return baseMapper.selectSumSale(compId);
    }
    @Override
    public Double selectSumBuy(String compId) {
        return baseMapper.selectSumBuy(compId);
    }

    /**
     * 删除
     *
     * @param id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteInfo(String id) {
        ContractManagementInfo contractManagementInfo = this.selectById(id);
        if (contractManagementInfo != null) {
            //合同信息
            this.deleteById(contractManagementInfo.getId());
            // 先删除任务
            noticeService.removeNotice(BaseNotice.NoticeStatus.TASK, "BUY-CONTRACT-APPROVE",
                    contractManagementInfo.getId(), null);
            noticeService.removeNotice(BaseNotice.NoticeStatus.TASK, "SALE-CONTRACT-APPROVE",
                    contractManagementInfo.getId(), null);
            noticeService.removeNotice(BaseNotice.NoticeStatus.TASK, "DAISHOU-CONTRACT-APPROVE",
                    contractManagementInfo.getId(), null);
            noticeService.removeNotice(BaseNotice.NoticeStatus.TASK, "DAICHU-CONTRACT-APPROVE",
                    contractManagementInfo.getId(), null);
            //货物信息
            ContractGoodsInfo contractGoodsInfo = contractGoodsInfoService.selectOne(new EntityWrapper<ContractGoodsInfo>().eq(ContractGoodsInfo.QueryFiles.CONTRACT_ID, id));
            //流程信息
            ContractProcessInfo contractProcessInfo = contractProcessInfoService.selectOne(new EntityWrapper<ContractProcessInfo>().eq(ContractGoodsInfo.QueryFiles.CONTRACT_ID, id));
            contractGoodsInfoService.deleteById(contractGoodsInfo.getId());
            contractProcessInfoService.deleteById(contractProcessInfo.getId());
            if ("2".equals(contractManagementInfo.getContractType()) && "1".equals(contractManagementInfo.getDeliverType())) {
                //临时仓库信息
                WarehouseBaseInfo warehouseBaseInfo = warehouseBaseInfoService.selectOne(new EntityWrapper<WarehouseBaseInfo>()
                        .eq(WarehouseBaseInfo.QueryFiles.WAREHOUSE_NAME, contractManagementInfo.getContractNo())
                        .eq("comp_id",contractManagementInfo.getCompId()));
                warehouseBaseInfoService.deleteById(warehouseBaseInfo.getId());
                //临时仓库出入库信息
                List<WarehouseInOutInfo> warehouseInOutInfos = warehouseInOutInfoService.selectList(new EntityWrapper<WarehouseInOutInfo>().eq(WarehouseInOutInfo.QueryFiles.BASE_ID, warehouseBaseInfo.getId()));
                if (!CollectionUtils.isEmpty(warehouseInOutInfos)) {
                    for (WarehouseInOutInfo warehouseInOutInfo : warehouseInOutInfos) {
                        warehouseInOutInfoService.deleteById(warehouseInOutInfo.getId());
                    }

                }
            }

        }
        cacheComponent.delPrefixKey(Const.ADMIN_CONTRACTINFO);

    }


    /**
     * 导出
     *
     * @return
     * @throws Exception
     */
    @Override
    public void export(ContractManagementInfo example, HttpServletResponse response) throws Exception {


        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        // 查询在船船员
        Page<ContractManagementInfo> contractManagementInfoPage = this.selectInfo(example);
        List<ContractManagementInfo> contractManagementInfos = contractManagementInfoPage.getRecords();


        // 1.Excel的头部信息
        String headerTitle = "";

        // 2.创建一个webbook 对应一个Excel文件
        HSSFWorkbook wb = new HSSFWorkbook();

        // 3.在webbook中添加一个sheet，对应Excel文件中的sheet
        HSSFSheet sheet;

        sheet = wb.createSheet("合同信息");
        headerTitle = "合同信息";

        // 4.设置打印参数
        sheet.setMargin(HSSFSheet.TopMargin, (short) 1);// 页边距（上）
        sheet.setMargin(HSSFSheet.BottomMargin, (short) 1);// 页边距（下）
        sheet.setMargin(HSSFSheet.LeftMargin, (short) 1);// 页边距（左）
        sheet.setMargin(HSSFSheet.RightMargin, (short) 1);// 页边距（右）

        // 不显示网格
        sheet.setDisplayGridlines(false);
        // 设置水平居中
        sheet.setHorizontallyCenter(true);

        /**************** 数据行样式 start ****************/
        HSSFFont fontTitle = wb.createFont();
        fontTitle.setFontName("宋体");
        fontTitle.setFontHeightInPoints((short) 14);
        // 设置字体加粗
        fontTitle.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);

        HSSFFont fontComp = wb.createFont();
        fontComp.setFontName("宋体");
        fontComp.setFontHeightInPoints((short) 16);
        // 设置字体加粗
        fontComp.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);

        HSSFFont fontDetail = wb.createFont();
        fontDetail.setFontName("宋体");
        fontDetail.setFontHeightInPoints((short) 12);

        // title
        HSSFCellStyle styleTitle = wb.createCellStyle();
        // 指定单元格居中对齐
        styleTitle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        // 指定单元格垂直居中对齐
        styleTitle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        // 指定单元格自动换行
        styleTitle.setWrapText(true);
        // 设置单元格字体
        styleTitle.setFont(fontTitle);
        // 右边框
        styleTitle.setBorderRight(HSSFCellStyle.BORDER_NONE);
        // 左边框
        styleTitle.setBorderLeft(HSSFCellStyle.BORDER_NONE);
        // 上边框
        styleTitle.setBorderTop(HSSFCellStyle.BORDER_NONE);
        // 下边框
        styleTitle.setBorderBottom(HSSFCellStyle.BORDER_NONE);

        // title
        HSSFCellStyle styleComp = wb.createCellStyle();
        // 指定单元格居中对齐
        styleComp.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        // 指定单元格垂直居中对齐
        styleComp.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        // 指定单元格自动换行
        styleComp.setWrapText(true);
        // 设置单元格字体
        styleComp.setFont(fontComp);
        // 右边框
        styleComp.setBorderRight(HSSFCellStyle.BORDER_NONE);
        // 左边框
        styleComp.setBorderLeft(HSSFCellStyle.BORDER_NONE);
        // 上边框
        styleComp.setBorderTop(HSSFCellStyle.BORDER_NONE);
        // 下边框
        styleComp.setBorderBottom(HSSFCellStyle.BORDER_NONE);

        HSSFCellStyle styleInfo = wb.createCellStyle();
        // 指定单元格居中对齐
        styleInfo.setAlignment(HSSFCellStyle.ALIGN_LEFT);
        // 指定单元格垂直居中对齐
        styleInfo.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        // 指定单元格自动换行
        styleInfo.setWrapText(true);
        // 设置单元格字体
        styleInfo.setFont(fontDetail);
        // 右边框
        styleInfo.setBorderRight(HSSFCellStyle.BORDER_NONE);
        // 左边框
        styleInfo.setBorderLeft(HSSFCellStyle.BORDER_NONE);
        // 上边框
        styleInfo.setBorderTop(HSSFCellStyle.BORDER_NONE);
        // 下边框
        styleInfo.setBorderBottom(HSSFCellStyle.BORDER_NONE);

        HSSFCellStyle styleDetail = wb.createCellStyle();
        // 指定单元格居中对齐
        styleDetail.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        // 指定单元格垂直居中对齐
        styleDetail.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        // 指定单元格自动换行
        styleDetail.setWrapText(true);
        // 设置单元格字体
        styleDetail.setFont(fontDetail);
        // 右边框
        styleDetail.setBorderRight(HSSFCellStyle.BORDER_THIN);
        // 左边框
        styleDetail.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        // 上边框
        styleDetail.setBorderTop(HSSFCellStyle.BORDER_THIN);
        // 下styleDetailTitle
        styleDetail.setBorderBottom(HSSFCellStyle.BORDER_THIN);

        HSSFCellStyle contextstyle = wb.createCellStyle();
        // 指定单元格居中对齐
        contextstyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        // 指定单元格垂直居中对齐
        contextstyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        // 指定单元格自动换行
        contextstyle.setWrapText(true);
        // 设置单元格字体
        contextstyle.setFont(fontDetail);
        // 右边框
        contextstyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
        // 左边框
        contextstyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        // 上边框
        contextstyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
        // 下styleDetailTitle
        contextstyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);

        HSSFCellStyle contextstyles = wb.createCellStyle();
        // 指定单元格居中对齐
        contextstyles.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        // 指定单元格垂直居中对齐
        contextstyles.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        // 指定单元格自动换行
        contextstyles.setWrapText(true);
        // 设置单元格字体
        contextstyles.setFont(fontDetail);
        // 右边框
        contextstyles.setBorderRight(HSSFCellStyle.BORDER_THIN);
        // 左边框
        contextstyles.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        // 上边框
        contextstyles.setBorderTop(HSSFCellStyle.BORDER_THIN);
        // 下styleDetailTitle
        contextstyles.setBorderBottom(HSSFCellStyle.BORDER_THIN);

        HSSFCellStyle styleDetailYellow = wb.createCellStyle();
        // 指定单元格居中对齐
        styleDetailYellow.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        // 指定单元格垂直居中对齐
        styleDetailYellow.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        // 指定单元格自动换行
        styleDetailYellow.setWrapText(true);
        // 设置单元格字体
        styleDetailYellow.setFont(fontDetail);
        // 右边框
        styleDetailYellow.setBorderRight(HSSFCellStyle.BORDER_THIN);
        // 左边框
        styleDetailYellow.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        // 上边框
        styleDetailYellow.setBorderTop(HSSFCellStyle.BORDER_THIN);
        // 下styleDetailTitle
        styleDetailYellow.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        styleDetailYellow.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
        styleDetailYellow.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);


        HSSFCellStyle styleDetailLeft = wb.createCellStyle();
        // 指定单元格居中对齐
        styleDetailLeft.setAlignment(HSSFCellStyle.ALIGN_LEFT);
        // 指定单元格垂直居中对齐
        styleDetailLeft.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        // 指定单元格自动换行
        styleDetailLeft.setWrapText(true);
        // 设置单元格字体
        styleDetailLeft.setFont(fontDetail);
        // 右边框
        styleDetailLeft.setBorderRight(HSSFCellStyle.BORDER_THIN);
        // 左边框
        styleDetailLeft.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        // 上边框
        styleDetailLeft.setBorderTop(HSSFCellStyle.BORDER_THIN);
        // 下styleDetailTitle
        styleDetailLeft.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        /**************** 数据行样式 end ****************/

        // 设置列宽
        sheet.setColumnWidth(0, 1 * 256 + 184);
        sheet.setColumnWidth(1, 6 * 256 + 184);
        sheet.setColumnWidth(2, 12 * 256 + 184);
        sheet.setColumnWidth(3, 12 * 256 + 184);
        sheet.setColumnWidth(4, 12 * 256 + 184);
        sheet.setColumnWidth(5, 12 * 256 + 184);
        sheet.setColumnWidth(6, 12 * 256 + 184);
        sheet.setColumnWidth(7, 12 * 256 + 184);
        sheet.setColumnWidth(8, 12 * 256 + 184);
        sheet.setColumnWidth(9, 12 * 256 + 184);
        sheet.setColumnWidth(10, 12 * 256 + 184);
        sheet.setColumnWidth(11, 12 * 256 + 184);
        sheet.setColumnWidth(12, 12 * 256 + 184);
        sheet.setColumnWidth(13, 12 * 256 + 184);
        sheet.setColumnWidth(14, 12 * 256 + 184);
        sheet.setColumnWidth(15, 12 * 256 + 184);
        sheet.setColumnWidth(16, 12 * 256 + 184);
        sheet.setColumnWidth(17, 1 * 256 + 184);

        // 创建单元格对象
        HSSFCell cell = null;

        // 创建打印设置对象
        HSSFPrintSetup ps = sheet.getPrintSetup();
        // 打印方向，true：横向，false：纵向(默认)
        ps.setLandscape(false);
        // // 打印质量
        // ps.setVResolution((short) 700)
        // 设置缩放比例
        ps.setScale((short) 80);
        // 纸张类型
        ps.setPaperSize(HSSFPrintSetup.A4_PAPERSIZE);


        int rownum = 1;
        HSSFRow row0 = sheet.createRow((int) rownum);
        row0.setHeightInPoints(25);
        cell = row0.createCell(1);
        cell.setCellStyle(styleTitle);
        cell.setCellValue("合同信息");
        sheet.addMergedRegion(new CellRangeAddress(rownum, rownum, (short) 1, (short) 13));
        cell = row0.createCell(2);
        cell.setCellStyle(styleTitle);
        cell = row0.createCell(3);
        cell.setCellStyle(styleTitle);
        cell = row0.createCell(4);
        cell.setCellStyle(styleTitle);
        cell = row0.createCell(5);
        cell.setCellStyle(styleTitle);
        cell = row0.createCell(6);
        cell.setCellStyle(styleTitle);
        cell = row0.createCell(7);
        cell.setCellStyle(styleTitle);
        cell = row0.createCell(8);
        cell.setCellStyle(styleTitle);
        cell = row0.createCell(9);
        cell.setCellStyle(styleTitle);
        cell = row0.createCell(10);
        cell.setCellStyle(styleTitle);
        cell = row0.createCell(11);
        cell.setCellStyle(styleTitle);
        cell = row0.createCell(12);
        cell.setCellStyle(styleTitle);
        cell = row0.createCell(13);
        cell.setCellStyle(styleTitle);
        cell = row0.createCell(14);
        cell.setCellStyle(styleTitle);
        cell = row0.createCell(15);
        cell.setCellStyle(styleTitle);
        cell = row0.createCell(16);
        cell.setCellStyle(styleTitle);

        rownum++;

        HSSFRow row1 = sheet.createRow((int) rownum);
        row1.setHeightInPoints(30);
        cell = row1.createCell(1);
        cell.setCellValue("序号");
        cell.setCellStyle(styleDetail);
        cell = row1.createCell(2);
        cell.setCellValue("合同编号");
        cell.setCellStyle(styleDetail);
        cell = row1.createCell(3);
        cell.setCellValue("货名");
        cell.setCellStyle(styleDetail);
        cell = row1.createCell(4);
        cell.setCellValue("品级");
        cell.setCellStyle(styleDetail);
        cell = row1.createCell(5);
        cell.setCellValue("重量（吨）");
        cell.setCellStyle(styleDetail);
        cell = row1.createCell(6);
        cell.setCellValue("合同单价（元）");
        cell.setCellStyle(styleDetail);
        cell = row1.createCell(7);
        cell.setCellValue("包装方式");
        cell.setCellStyle(styleDetail);
        cell = row1.createCell(8);
        cell.setCellValue("买方");
        cell.setCellStyle(styleDetail);
        cell = row1.createCell(9);
        cell.setCellValue("卖方");
        cell.setCellStyle(styleDetail);
        cell = row1.createCell(10);
        cell.setCellValue("已完成（吨）");
        cell.setCellStyle(styleDetail);
        cell = row1.createCell(11);
        cell.setCellValue("状态");
        cell.setCellStyle(styleDetail);
        cell = row1.createCell(12);
        cell.setCellValue("签订日期");
        cell.setCellStyle(styleDetail);
        cell = row1.createCell(13);
        cell.setCellValue("未回款/已付款（元）");
        cell.setCellStyle(styleDetail);
        cell = row1.createCell(14);
        cell.setCellValue("已开发票金额（元）");
        cell.setCellStyle(styleDetail);
        cell = row1.createCell(15);
        cell.setCellValue("未完成吨数");
        cell.setCellStyle(styleDetail);
        cell = row1.createCell(16);
        cell.setCellValue("运费（元）");
        cell.setCellStyle(styleDetail);

        rownum++;

        // 详情信息
        if (CollectionUtils.isNotEmpty(contractManagementInfos)) {
            for (int i = 0; i < contractManagementInfos.size(); i++) {
                ContractManagementInfo contractManagementInfo = contractManagementInfos.get(i);
                ContractProcessInfo contractProcessInfo = contractProcessInfoService.selectOne(new EntityWrapper<ContractProcessInfo>()
                .eq("contract_id",contractManagementInfo.getId()));
//                if("1".equals(contractManagementInfo.getDeliverType())){
//                    //汽运结算报表
//                    List<TranSettlementReport> tranSettlementReportList = tranSettlementReportService.selectList(new EntityWrapper<TranSettlementReport>()
//                            .eq("contract_no",contractManagementInfo.getContractNo())
//                            .eq("comp_id",contractManagementInfo.getCompId())
//                            .eq("delete_flag","0"));
//                    if(CollectionUtils.isNotEmpty(tranSettlementReportList)){
//                        for(TranSettlementReport tranSettlementReport : tranSettlementReportList){
//                            freight = freight + tranSettlementReport.getAmountIngPayable();
//                        }
//                    }
//                }

                HSSFRow rowx = sheet.createRow((int) rownum);
                rowx.setHeightInPoints(20);
                cell = rowx.createCell(1);
                cell.setCellValue(i + 1);
                cell.setCellStyle(styleDetail);
                cell = rowx.createCell(2);
                cell.setCellValue(editString(contractManagementInfo.getContractNo()));
                cell.setCellStyle(styleDetail);
                cell = rowx.createCell(3);
                cell.setCellValue(editString(contractManagementInfo.getGoodsName()));
                cell.setCellStyle(styleDetail);
                cell = rowx.createCell(4);
                cell.setCellValue(editString(contractManagementInfo.getGrade()));
                cell.setCellStyle(styleDetail);
                cell = rowx.createCell(5);
                cell.setCellValue(editFloat(contractManagementInfo.getWeight()));
                cell.setCellStyle(styleDetail);
                cell = rowx.createCell(6);
                cell.setCellValue(editDouble(contractManagementInfo.getUnitContractPrice()));
                cell.setCellStyle(styleDetail);
                cell = rowx.createCell(7);
                cell.setCellValue(editString(contractManagementInfo.getPackingMethod()));
                cell.setCellStyle(styleDetail);
                cell = rowx.createCell(8);
                cell.setCellValue(editString(contractManagementInfo.getBuyer()));
                cell.setCellStyle(styleDetail);
                cell = rowx.createCell(9);
                cell.setCellValue(editString(contractManagementInfo.getSeller()));
                cell.setCellStyle(styleDetail);
                HSSFDataFormat format = wb.createDataFormat(); // 此处设置数据格式
                contextstyle.setDataFormat(format.getFormat("0.000"));
                cell = rowx.createCell(10);
                cell.setCellValue(editDouble(contractManagementInfo.getCompletedQuantity()));
                cell.setCellStyle(contextstyle);
                cell = rowx.createCell(11);
                cell.setCellValue(editString(contractManagementInfo.getStatus()!=null?contractManagementInfo.getStatus():contractManagementInfo.getApproveStatus()));
                cell.setCellStyle(styleDetail);
                cell = rowx.createCell(12);
                cell.setCellValue(DateUtil.formatDate(contractManagementInfo.getSigningDate() != null ? addDateOneDay(contractManagementInfo.getSigningDate()) : addDateOneDay(new Date()), DateUtils.DATE_FMT_YYYY_MM_DD));
                cell.setCellStyle(styleDetail);
                cell = rowx.createCell(13);
                cell.setCellValue(editFloat(contractManagementInfo.getMildewGrain()));
                cell.setCellStyle(contextstyles);
                cell = rowx.createCell(14);
                cell.setCellValue(editFloat(Float.valueOf(String.valueOf(contractProcessInfo.getGoodsName()!=null?contractProcessInfo.getGoodsName():"0"))));
                cell.setCellStyle(contextstyles);
                cell = rowx.createCell(15);
                cell.setCellValue(editDouble(Double.valueOf(contractManagementInfo.getWeight()) - contractManagementInfo.getCompletedQuantity()));
                cell.setCellStyle(contextstyle);
                HSSFDataFormat format1 = wb.createDataFormat(); // 此处设置数据格式
                contextstyles.setDataFormat(format1.getFormat("0.00"));
                cell = rowx.createCell(16);
                if("1".equals(contractManagementInfo.getDeliverType())){
                    //汽运结算报表
                    List<TranSettlementReport> tranSettlementReportList = tranSettlementReportService.selectList(new EntityWrapper<TranSettlementReport>()
                            .eq("contract_no",contractManagementInfo.getContractNo())
                            .eq("comp_id",contractManagementInfo.getCompId())
                            .eq("delete_flag","0"));
                    //运费
                    Double freight = 0d;
                    if(CollectionUtils.isNotEmpty(tranSettlementReportList)){
                        for(TranSettlementReport tranSettlementReport : tranSettlementReportList){
                            freight = freight + tranSettlementReport.getAmountIngPayable();
                        }
                    }
                    cell.setCellValue(editDouble(freight));
                    cell.setCellStyle(contextstyles);
                }else {
                    cell.setCellValue("他运");
                    cell.setCellStyle(styleDetail);
                }
                rownum++;
            }

        }


        String path = null;
        String tempPath = null;
        String excelPath = null;

        try {

            // 取得绝对路径
            tempPath = URLDecoder.decode((localPath), "utf-8");

            // EXCEL路径
            excelPath = "/web/temp/repair/" + DateUtil.formatDate(new Date(), DateUtils.DATE_FMT_YYYYMMDD_NS) + '/'
                    + UUID.randomUUID().toString().replaceAll("-", "");

            path = tempPath + excelPath + '/' + "合同信息"
                    + ".xls";

        } catch (Exception e) {
            log.debug(e.getMessage());
        }
        // 下载
        download(path, response, wb);

    }


    private Date addDateOneDay(Date date) {
        if (null == date) {
            return date;
        }
        Calendar c = Calendar.getInstance();
        c.setTime(date); // 设置当前日期
        c.add(Calendar.DATE, 1); // 日期加1天
        date = c.getTime();
        return date;
    }

    /**
     * 判断字符串
     *
     * @param example
     * @return
     */
    private String editString(String example) {
        String exampleOne = example != null ? example : "";
        return exampleOne;
    }


    /**
     * 判断浮点数
     *
     * @param example
     * @return
     */
    private Float editFloat(Float example) {
        Float exampleOne = example != null ? example : 0f;
        return exampleOne;
    }

    /**
     * 判断浮点数
     *
     * @param example
     * @return
     */
    private Double editDouble(Double example) {
        Double exampleOne = example != null ? example : 0.00;
        return exampleOne;
    }


    /**
     * 下载
     *
     * @param path
     * @param response
     */
    private void download(String path, HttpServletResponse response, Workbook wb) {

        try {

            // path是指欲下载的文件的路径。
            File file = new File(path);
            // 取得文件名。
            String fileName = file.getName();
            // 给文件名编码
            fileName = new String(fileName.getBytes("GBK"), "ISO-8859-1");

            response.setContentType("application/vnd.ms-excel");
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);

            // 定义byte输出流
            ByteArrayOutputStream out = new ByteArrayOutputStream();

            // 写导出文件
            wb.write(out);

            // 取得模板文件中的数据
            byte[] result = out.toByteArray();

            // 设置输出数据类型
            response.setContentType("application/vnd.ms-excel");
            // 设置输出数据长度
            response.setContentLength(result.length);

            // 设置文件名称
            response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
            // 将文件流输出到画面
            response.getOutputStream().write(result);

            out.flush();
            out.close();

        } catch (IOException ex) {
            log.debug(ex.getMessage());
        }

    }

    /**
     * 合同利润详情列表查询
     * @param contractManagementInfo
     * @return
     */
    @Override
    public Page<ContractManagementInfo> selectContractInfo(ContractManagementInfo contractManagementInfo) {
        Map<String, Object> pageView = new HashMap<>();
        pageView.put("startRecord", (contractManagementInfo.getCurrentPage() - 1)
                * contractManagementInfo.getPageSize());
        //  公司ID
        pageView.put("compId", AuthSecurityUtils.getCurrentUserInfo().getCompId());
        pageView.put("searchKeyWord", contractManagementInfo.getSearchKeyWord());
        pageView.put("startDate", contractManagementInfo.getStartDate());
        pageView.put("endDate", contractManagementInfo.getEndDate());
        pageView.put("searchTypeCon", contractManagementInfo.getSearchTypeCon());
        pageView.put("searchContractType", contractManagementInfo.getSearchContractType());
        pageView.put("agreementType", contractManagementInfo.getAgreementType());
        pageView.put("pageSize", contractManagementInfo.getPageSize());
        pageView.put("currentPage", contractManagementInfo.getCurrentPage());
        // 查询服务商总数
        Integer dataCount = baseMapper.getContractCountByCondition(pageView);
        List<ContractManagementInfo> dataList = baseMapper.getContractListByCondition(pageView);

        Page<ContractManagementInfo> page = new Page<>();
        page.setRecords(dataList == null ? Lists.newArrayList() : dataList);
        page.setTotal(dataCount == null ? 0 : dataCount);
        page.setCurrent(contractManagementInfo.getCurrentPage());
        page.setSize(contractManagementInfo.getPageSize());

        return page;
    }

    @Override
    public ContractManagementInfo selectContractChart(ContractManagementInfo contractManagementInfo) {
        ContractManagementInfo  contractManagementInfo1=new ContractManagementInfo();
        Map<String, Object> pageView = new HashMap<>();
        //  公司ID
        pageView.put("compId", AuthSecurityUtils.getCurrentUserInfo().getCompId());
        pageView.put("startDate", contractManagementInfo.getStartDate());
        pageView.put("endDate", contractManagementInfo.getEndDate());
        List<ContractManagementInfo> dataList = baseMapper.getContractChartByCondition(pageView);
        List<ContractManagementInfo> dataList1 = baseMapper.getContractFormByCondition(pageView);
        contractManagementInfo1.setChartList(dataList);
        contractManagementInfo1.setFormList(dataList1);

        return contractManagementInfo1;
    }

}
