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

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.collect.Lists;
import com.winsea.svc.base.base.entity.CommonStaff;
import com.winsea.svc.base.base.entity.CommonStaffRole;
import com.winsea.svc.base.base.service.ICommonRoleResourceService;
import com.winsea.svc.base.base.service.ICommonStaffRoleService;
import com.winsea.svc.base.base.service.ICommonStaffService;
import com.winsea.svc.base.security.util.AuthSecurityUtils;
import com.winsea.svc.base.workflow.entity.Workflow;
import com.winsea.svc.notice.entity.NoticeTaskInfo;
import com.winsea.svc.notice.entity.base.BaseNotice;
import com.winsea.svc.notice.service.INoticeService;
import com.winsea.svc.notice.service.INoticeTaskService;
import com.yh.saas.common.support.util.IdGenerator;
import com.yh.saas.common.support.util.StringUtils;
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.TranProcessInfoMapper;
import com.yh.saas.plugin.yiliangyiyun.service.*;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.yh.saas.plugin.yiliangyiyun.util.Const;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.aggregation.ArrayOperators;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

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

/**
 * <p>
 * 记录调度 服务实现类
 * </p>
 *
 * @author Gongdc
 * @since 2021-05-31
 */
@Service
public class TranProcessInfoServiceImpl extends ServiceImpl<TranProcessInfoMapper, TranProcessInfo> implements ITranProcessInfoService {
    @Autowired
    private ICommonBillOperateHisService billOperateHisService;
    @Autowired
    private ITranCarInfoService tranCarInfoService;
    @Autowired
    private ITranTaskInfoService tranTaskInfoService;
    @Autowired
    private ITranSettlementReportService tranSettlementReportService;
    @Autowired
    private ITranPriceApproveService tranPriceApproveService;
    @Autowired
    private IDriverViewInfoService driverViewInfoService;
    @Autowired
    private IDriverPayeeInfoService driverPayeeInfoService;
    @Autowired
    private INewWorkflowService workflowService;
    @Autowired
    private INoticeService noticeService;
    @Autowired
    private INoticeTaskService noticeTaskService;
    @Autowired
    private ICommonStaffService staffService;
    @Autowired
    private ICommonRoleResourceService roleResourceService;
    @Autowired
    private IStockSaleReceiptReportService stockSaleReceiptReportService;
    @Autowired
    private IContractManagementInfoService contractManagementInfoService;
    @Autowired
    private ICommonStaffRoleService commonStaffRoleService;
    @Autowired
    private IBatchReviewInfoService batchReviewInfoService;
    @Autowired
    private CacheComponent cacheComponent;
    /**
     * 汽运调度分页列表查询
     *
     * @param tranProcessInfo
     * @return
     */
    @Override
    public Page<TranProcessInfo> selectTranProcessInfo(TranProcessInfo tranProcessInfo) {
        Map<String, Object> pageView = new HashMap<>();

        pageView.put("startRecord", (tranProcessInfo.getCurrentPage() - 1)
                * tranProcessInfo.getPageSize());
        //  公司ID
        pageView.put("compId", AuthSecurityUtils.getCurrentUserInfo().getCompId());
        pageView.put("searchKeyWord", tranProcessInfo.getSearchKeyWord());
        pageView.put("searchType", tranProcessInfo.getSearchType());
        pageView.put("startDate", tranProcessInfo.getStartDate());
        pageView.put("endDate", tranProcessInfo.getEndDate());
        //只有指定的人才能看到需要反馈的数据  发货反馈(发货执行中1已完成2全部3)
        if("1".equals(tranProcessInfo.getFeedbackFlag())||"2".equals(tranProcessInfo.getFeedbackFlag())||"3".equals(tranProcessInfo.getFeedbackFlag())){
            tranProcessInfo.setSenderPhone(AuthSecurityUtils.getStaffById(AuthSecurityUtils.getCurrentUserId()).getStaffMobilePhone());
        }
        //收货反馈(收货执行中4已完成5全部6)
        if("4".equals(tranProcessInfo.getFeedbackFlag())||"5".equals(tranProcessInfo.getFeedbackFlag())||"6".equals(tranProcessInfo.getFeedbackFlag())){
            tranProcessInfo.setReceiverPhone(AuthSecurityUtils.getStaffById(AuthSecurityUtils.getCurrentUserId()).getStaffMobilePhone());
        }
        pageView.put("senderPhone", tranProcessInfo.getSenderPhone());
        pageView.put("receiverPhone", tranProcessInfo.getReceiverPhone());
        pageView.put("pageSize", tranProcessInfo.getPageSize());
        pageView.put("currentPage", tranProcessInfo.getCurrentPage());
        pageView.put("tranTypeKey", tranProcessInfo.getTranTypeKey());
        pageView.put("feedbackFlag", tranProcessInfo.getFeedbackFlag());
        // 查询汽运调度总数
        Integer dataCount = baseMapper.getCountByCondition(pageView);
        List<TranProcessInfo> dataList = baseMapper.getListByCondition(pageView);
        Page<TranProcessInfo> page = new Page<>();
        page.setRecords(dataList == null ? Lists.newArrayList() : dataList);
        page.setTotal(dataCount == null ? 0 : dataCount);
        page.setCurrent(tranProcessInfo.getCurrentPage());
        page.setSize(tranProcessInfo.getPageSize());

        return page;
    }

    /**
     * 更改状态
     *
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String editStatus(String id) {
        // 查询调度信息
        TranProcessInfo tranProcessInfo = this.selectById(id);
        if (tranProcessInfo != null) {
            if (StatusEnum.PROCESS_DO.getFlag().equals(tranProcessInfo.getProcessStatusFlag())) {
                tranProcessInfo.setProcessStatusFlag(StatusEnum.PROCESS_COMPLETED.getFlag());
                tranProcessInfo.setProcessStatus(StatusEnum.PROCESS_COMPLETED.getName());

            }
            this.updateById(tranProcessInfo);
            // 插入操作历史
            String staffName = this.billOperateHisService.getStaffAndName();
            // 插入操作历史
            this.billOperateHisService.saveBillOperateHis(tranProcessInfo.getId(), NumberConstant.CONSTANT_PROCESS, staffName, null,
                    tranProcessInfo.getProcessStatus(), null, "");
            return "OK";
        }
        return "NG";
    }

    /**
     * 查看运输调度
     *
     * @param id
     * @return
     */
    @Override
    public TranProcessInfo getTranProcess(String id) {
        //查看运输信息
        TranProcessInfo tranProcessInfo = this.selectById(id);
        TranTaskInfo tranTaskInfo=tranTaskInfoService.selectById(tranProcessInfo.getInfoId());
        ContractManagementInfo contractManagementInfo=contractManagementInfoService.selectOne(new EntityWrapper<ContractManagementInfo>()
                .eq("contract_no",tranProcessInfo.getContractNo())
                .eq("comp_id",tranTaskInfo.getCompId()));
        if(contractManagementInfo != null){
            if (contractManagementInfo.getPriceType()!=null) {
                tranProcessInfo.setPriceType(contractManagementInfo.getPriceType());
            }
        }
        if (tranTaskInfo.getTaskType()!=null) {
            tranProcessInfo.setTaskType(tranTaskInfo.getTaskType());
            if ("移库".equals(tranTaskInfo.getTaskType())) {
                ContractManagementInfo contractManagementInfo1 = contractManagementInfoService.selectOne(new EntityWrapper<ContractManagementInfo>()
                        .eq("contract_no", tranTaskInfo.getSendWarehouse())
                        .eq("comp_id", tranTaskInfo.getCompId()));
                if (contractManagementInfo1 != null) {
                    //关联合同
                    tranProcessInfo.setRelatedContract(contractManagementInfo1.getContractNo());
                }
            }
        }
        //查看车次信息
        List<TranCarInfo> tranCarInfoList = tranCarInfoService.selectList(new EntityWrapper<TranCarInfo>()
                .eq(TranCarInfo.QueryFiles.PROCESS_ID, id).eq(TranCarInfo.QueryFiles.DELETE_FLAG, NumberConstant.CONSTANT0).orderBy("tran_car_no").orderBy("box_no"));
        //查看审核记录
        List<TranPriceApprove> tranPriceApproveList = tranPriceApproveService.selectList(new EntityWrapper<TranPriceApprove>()
                .eq(TranPriceApprove.QueryFiles.PROCESS_ID, id).eq("record_type", "1").eq(TranPriceApprove.QueryFiles.DELETE_FLAG, NumberConstant.CONSTANT0));
        Map<String, Object> pageView = new HashMap<>();
        pageView.put("id", id);
        // 查询派车总数包括已删除的
        Integer dataCount = baseMapper.getCarByCondition(pageView);
        tranProcessInfo.setCount(dataCount);
        tranProcessInfo.setTranCarInfoList(tranCarInfoList);
        tranProcessInfo.setTranPriceApproveList(tranPriceApproveList);
        return tranProcessInfo;
    }

    /**
     * 派车
     *
     * @param tranProcessInfo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String insertTranCar(TranProcessInfo tranProcessInfo) {
        this.updateById(tranProcessInfo);
        List<TranCarInfo> tranCarInfoList = tranProcessInfo.getTranCarInfoList();
        BatchReviewInfo batchReviewInfo = new BatchReviewInfo();
        batchReviewInfo.setId(IdGenerator.generateUUID());
        String flagBatch = "0";
        if (!CollectionUtils.isEmpty(tranCarInfoList)) {
            for (TranCarInfo tranCarInfo : tranCarInfoList) {
                if (tranCarInfo.getLoadNetWeight() == null) {
                    tranCarInfo.setLoadNetWeight(0f);
                }
                //新增
                if (StringUtils.isEmpty(tranCarInfo.getId())) {
                    TranTaskInfo tranTaskInfo=tranTaskInfoService.selectById(tranProcessInfo.getInfoId());
                    tranCarInfo.setCompId(tranTaskInfo.getCompId());
                    //船运集装箱
                    if (tranCarInfoList.get(0).getTranType().equals(NumberConstant.CONSTANT3)&&"集装箱".equals(tranCarInfoList.get(0).getShipType())) {
                        for(int i=0;i<tranCarInfoList.get(0).getBoxNumber();i++){
                            tranCarInfo.setProcessId(tranProcessInfo.getId());
                            tranCarInfo.setInfoId(tranProcessInfo.getInfoId());
                            tranCarInfo.setId(IdGenerator.generateUUID());
                            tranCarInfo.setStatusFlag(StatusEnum.NOT_LOADED.getFlag());
                            tranCarInfo.setStatus(StatusEnum.NOT_LOADED.getName());
                            tranCarInfoService.insert(tranCarInfo);
                        }
                    }
                    else {
                        tranCarInfo.setProcessId(tranProcessInfo.getId());
                        tranCarInfo.setInfoId(tranProcessInfo.getInfoId());
                        tranCarInfo.setId(IdGenerator.generateUUID());
                        if (!NumberConstant.CONSTANT1.equals(tranCarInfo.getTemporaryDriverFlag()) && tranCarInfo.getLoadNetWeight() > 0) {
                            tranCarInfo.setSignStatus(StatusEnum.NOT_SIGNED.getName());
                            tranCarInfo.setSignStatusFlag(StatusEnum.NOT_SIGNED.getFlag());
                        }
                        tranCarInfo.setContractNo(tranTaskInfo.getContractNo());
                        tranCarInfo.setStatusFlag(StatusEnum.NOT_LOADED.getFlag());
                        tranCarInfo.setStatus(StatusEnum.NOT_LOADED.getName());
                        tranCarInfoService.insert(tranCarInfo);
                    }
                }
                //编辑
                else {
                    //非临时司机卸货时未签合同状态
                    if (!NumberConstant.CONSTANT1.equals(tranCarInfo.getTemporaryDriverFlag()) && tranCarInfo.getLoadNetWeight() > 0) {
                        tranCarInfo.setSignStatus(StatusEnum.NOT_SIGNED.getName());
                        tranCarInfo.setSignStatusFlag(StatusEnum.NOT_SIGNED.getFlag());
                    }
                    TranTaskInfo tranTaskInfo = tranTaskInfoService.selectById(tranProcessInfo.getInfoId());
                    //装车反馈时状态改为已装车
                    if (tranCarInfo.getLoadNetWeight() > 0&&tranCarInfo.getUnloadNetWeight() == 0) {
                        tranCarInfo.setStatusFlag(StatusEnum.LOADED.getFlag());
                        tranCarInfo.setStatus(StatusEnum.LOADED.getName());
                        tranCarInfo.setContractNo(tranTaskInfo.getContractNo());
                        //汽运类型
                        if (tranCarInfo.getTranType().equals(NumberConstant.CONSTANT1)) {
                            TranSettlementReport tranSettlementReport1 = tranSettlementReportService.selectOne(new EntityWrapper<TranSettlementReport>()
                                    .eq("car_id", tranCarInfo.getId()));
                            if (tranSettlementReport1!=null) {
//                                if (tranCarInfo.getLoadNetWeight() > 0&&tranProcessInfo.getFlag()!=null) {
//                                    for (TranSettlementReport tranSettlementReport : tranSettlementReportList) {
                                        tranSettlementReport1.setLoadingImg(tranCarInfo.getLoadPoundImg());
//                                        tranSettlementReport.setUnloadingWeight(tranCarInfo.getUnloadNetWeight());
//                                        tranSettlementReport.setUnloadingImg(tranCarInfo.getUnloadPoundImg());
//                                        //损耗
//                                        tranSettlementReport.setLossWeight(tranCarInfo.getLoadNetWeight() - tranCarInfo.getUnloadNetWeight());
//                                        //结算重量
//                                        if ("0".equals(tranSettlementReport.getManualFlag())) {
//                                            //卸车不为空时，结算重量=装卸取小
//                                            tranSettlementReport.setSettlementWeight(tranCarInfo.getLoadNetWeight() > tranCarInfo.getUnloadNetWeight() ? tranCarInfo.getUnloadNetWeight() : tranCarInfo.getLoadNetWeight());
//                                        }
//                                        //扣款
//                                        if (tranSettlementReport.getLossWeight() <= (tranCarInfo.getLoadNetWeight() / 1000)) {
//                                            tranSettlementReport.setDeductionAmount("0");
//                                            //应付=单价x结算重量-扣款
//                                            tranSettlementReport.setAmountIngPayable(tranSettlementReport.getTransportPrice() * tranSettlementReport.getSettlementWeight());
//                                        } else {
//                                            tranSettlementReport.setDeductionAmount(String.format("%.2f", (Float.valueOf(tranCarInfo.getLoadNetWeight() - tranCarInfo.getUnloadNetWeight()) - (tranCarInfo.getLoadNetWeight() / 1000)) * Float.valueOf(tranCarInfo.getTranPrice())));
//                                            //应付=单价x结算重量-扣款
//                                            tranSettlementReport.setAmountIngPayable(tranSettlementReport.getTransportPrice() * tranSettlementReport.getSettlementWeight() - Float.valueOf(tranSettlementReport.getDeductionAmount()));
//                                        }
                                        tranSettlementReportService.updateById(tranSettlementReport1);
//                                    }
//                                }
                            } else {
                                //生成汽运报表
                                TranSettlementReport tranSettlementReport = new TranSettlementReport();
                                tranSettlementReport.setCompId(tranTaskInfo.getCompId());
                                tranSettlementReport.setCarId(tranCarInfo.getId());
                                tranSettlementReport.setId(IdGenerator.generateUUID());
                                tranSettlementReport.setTranType("汽运");
                                tranSettlementReport.setTranTypeKey("1");
                                tranSettlementReport.setContractNo(tranTaskInfo.getContractNo());
                                tranSettlementReport.setProcessNo(tranProcessInfo.getProcessNo());
                                tranSettlementReport.setName(tranCarInfo.getDriver());
                                tranSettlementReport.setPhone(tranCarInfo.getDriverPhone());
                                tranSettlementReport.setCarNo(tranCarInfo.getCarNo());
                                //查询账户信息
                                List<DriverViewInfo> driverViewInfoList = driverViewInfoService.selectList(new EntityWrapper<DriverViewInfo>()
                                        .eq("driver_name", tranCarInfo.getDriver())
                                        .eq("delete_flag", "0"));
                                if (!CollectionUtils.isEmpty(driverViewInfoList)) {
                                    for (DriverViewInfo driverViewInfo : driverViewInfoList) {
                                        List<DriverPayeeInfo> driverPayeeInfoList = driverPayeeInfoService.selectList(new EntityWrapper<DriverPayeeInfo>()
                                                .eq("driver_id", driverViewInfo.getId())
                                                .eq("delete_flag", "0"));
                                        if (!CollectionUtils.isEmpty(driverPayeeInfoList)) {
                                            //本次收款账户
                                            tranSettlementReport.setCardNo(driverPayeeInfoList.get(0).getBankCard());
                                        }
                                    }
                                }
                                tranSettlementReport.setSettlementWeight(tranCarInfo.getLoadNetWeight());
                                //应付
                                tranSettlementReport.setAmountIngPayable(Float.valueOf(tranCarInfo.getTranPrice()) * tranSettlementReport.getSettlementWeight());
                                //未付
                                tranSettlementReport.setAmountNotPayable(Float.valueOf(tranCarInfo.getTranPrice()) * tranSettlementReport.getSettlementWeight());
                                tranSettlementReport.setTranCarNo(tranCarInfo.getTranCarNo());
                                tranSettlementReport.setLoadingWeight(tranCarInfo.getLoadNetWeight());
                                tranSettlementReport.setLoadingImg(tranCarInfo.getLoadPoundImg());
                                tranSettlementReport.setTransportPrice(Float.valueOf(tranCarInfo.getTranPrice()));
                                tranSettlementReport.setBatchId(batchReviewInfo.getId());
                                tranSettlementReportService.insert(tranSettlementReport);
                                flagBatch = "1";
//                                boolean isStartWorkflow = org.apache.commons.lang3.StringUtils.isBlank(tranSettlementReport.getWorkflowId());
//                                // 不是退回的单子
//                                if (isStartWorkflow) {
//                                    Workflow workflow = workflowService
//                                            .findLatestWorkflowByBusinessCodeByApp(tranSettlementReport.getCompId(), "TRANSPORTATION-SETTLEMENT-REPORT");
//                                    // 没配置审核流程，直接结束并处理信息
//                                    if (workflow == null) {
//                                        throw new YException(YExceptionEnum.PURCHASE_ORDER_ERROR);
//                                    }
//                                    // 开启审核流
//                                    else {
//
//                                        // 设置状态 已提交审核
//                                        tranSettlementReport.setWorkflowId(workflow.getId());
//                                        tranSettlementReportService.updateById(tranSettlementReport);
//                                        workflowService.startInstance(workflow.getId(), tranSettlementReport.getId());
//                                    }
//                                }
                            }
                        }
                        //火运类型
                        else if (tranCarInfo.getTranType().equals(NumberConstant.CONSTANT2)) {
                            TranSettlementReport tranSettlementReport1 = tranSettlementReportService.selectOne(new EntityWrapper<TranSettlementReport>()
                                    .eq("car_id", tranCarInfo.getId()));
                            if (tranSettlementReport1!=null) {
                                tranSettlementReport1.setLoadingImg(tranCarInfo.getLoadPoundImg());
                                tranSettlementReportService.updateById(tranSettlementReport1);
                            } else {
                                //生成火运报表
                                TranSettlementReport tranSettlementReport = new TranSettlementReport();
                                tranSettlementReport.setCompId(tranTaskInfo.getCompId());
                                tranSettlementReport.setCarId(tranCarInfo.getId());
                                tranSettlementReport.setId(IdGenerator.generateUUID());
                                tranSettlementReport.setTranType("火运");
                                tranSettlementReport.setTranTypeKey("2");
                                tranSettlementReport.setContractNo(tranTaskInfo.getContractNo());
                                tranSettlementReport.setTaskNo(tranTaskInfo.getTaskNo());
                                tranSettlementReport.setProcessNo(tranProcessInfo.getProcessNo());
                                tranSettlementReport.setBoxNo(tranCarInfo.getBoxNo());
                                tranSettlementReport.setSettlementWeight(tranCarInfo.getLoadNetWeight());
                                TranProcessInfo tranProcessInfo1 = this.selectById(tranProcessInfo.getId());
                                //应付
                                tranSettlementReport.setAmountIngPayable(tranProcessInfo1.getTranPrice());
                                //未付
                                tranSettlementReport.setAmountNotPayable(tranProcessInfo1.getTranPrice());
                                tranSettlementReport.setLoadingWeight(tranCarInfo.getLoadNetWeight());
                                tranSettlementReport.setLoadingImg(tranCarInfo.getLoadPoundImg());
                                tranSettlementReport.setBatchId(batchReviewInfo.getId());
                                tranSettlementReportService.insert(tranSettlementReport);
                                flagBatch = "1";
                            }
                         }
                        //船运类型
                        else if (tranCarInfo.getTranType().equals(NumberConstant.CONSTANT3)) {
                            TranSettlementReport tranSettlementReport1 = tranSettlementReportService.selectOne(new EntityWrapper<TranSettlementReport>()
                                    .eq("car_id", tranCarInfo.getId()));
                            if (tranSettlementReport1!=null) {
                                tranSettlementReport1.setLoadingImg(tranCarInfo.getLoadPoundImg());
                            } else {
                                //生成船运报表
                                TranSettlementReport tranSettlementReport = new TranSettlementReport();
                                tranSettlementReport.setCompId(tranTaskInfo.getCompId());
                                tranSettlementReport.setCarId(tranCarInfo.getId());
                                tranSettlementReport.setId(IdGenerator.generateUUID());
                                tranSettlementReport.setTranType("船运");
                                tranSettlementReport.setTranTypeKey("3");
                                tranSettlementReport.setTaskNo(tranTaskInfo.getTaskNo());
                                tranSettlementReport.setProcessNo(tranProcessInfo.getProcessNo());
                                if ("集装箱".equals(tranCarInfo.getShipType())){
                                    tranSettlementReport.setBoxNo(tranCarInfo.getCaseNo());
                                }
                                else{
                                    tranSettlementReport.setBoxNo(tranCarInfo.getBinNumber());
                                }
                                tranSettlementReport.setShipType(tranCarInfo.getShipType());
                                tranSettlementReport.setContractNo(tranTaskInfo.getContractNo());
                                tranSettlementReport.setSettlementWeight(tranCarInfo.getLoadNetWeight());
                                TranProcessInfo tranProcessInfo1=this.selectById(tranProcessInfo.getId());
                                //应付
                                tranSettlementReport.setAmountIngPayable(tranProcessInfo1.getTranPrice());
                                //未付
                                tranSettlementReport.setAmountNotPayable(tranProcessInfo1.getTranPrice());
                                tranSettlementReport.setTranCarNo(tranCarInfo.getTranCarNo());
                                tranSettlementReport.setLoadingWeight(tranCarInfo.getLoadNetWeight());
                                tranSettlementReport.setLoadingImg(tranCarInfo.getLoadPoundImg());
                                tranSettlementReport.setTransportPrice(tranProcessInfo.getTranPrice());
                                tranSettlementReport.setBatchId(batchReviewInfo.getId());
                                tranSettlementReportService.insert(tranSettlementReport);
                                flagBatch = "1";
                            }
                        }
                    }
                    //卸车反馈时状态改为已送达
                    else if (tranCarInfo.getUnloadNetWeight() > 0) {
                        tranCarInfo.setStatusFlag(StatusEnum.DELIVERED.getFlag());
                        tranCarInfo.setStatus(StatusEnum.DELIVERED.getName());
                        //卸车反馈时更新报表卸车数据
                        TranSettlementReport tranSettlementReport1 = tranSettlementReportService.selectOne(new EntityWrapper<TranSettlementReport>()
                                    .eq("car_id", tranCarInfo.getId()));
                        if (tranSettlementReport1!=null) {
                            if (tranCarInfo.getUnloadNetWeight() > 0&&tranProcessInfo.getFlag()!=null) {
                                tranSettlementReport1.setLoadingImg(tranCarInfo.getLoadPoundImg());
                                tranSettlementReport1.setUnloadingWeight(tranCarInfo.getUnloadNetWeight());
                                tranSettlementReport1.setUnloadingImg(tranCarInfo.getUnloadPoundImg());
                                //损耗
                                tranSettlementReport1.setLossWeight(tranCarInfo.getLoadNetWeight() - tranCarInfo.getUnloadNetWeight());
                                //汽运类型
                                if (tranCarInfo.getTranType().equals(NumberConstant.CONSTANT1)) {
                                    //结算重量
                                    if ("0".equals(tranSettlementReport1.getManualFlag())) {
                                        //卸车不为空时，结算重量=装卸取小
                                        tranSettlementReport1.setSettlementWeight(tranCarInfo.getLoadNetWeight() > tranCarInfo.getUnloadNetWeight() ? tranCarInfo.getUnloadNetWeight() : tranCarInfo.getLoadNetWeight());
                                    }
                                    //扣款
                                    if (tranSettlementReport1.getLossWeight() <= (tranCarInfo.getLoadNetWeight() / 1000)) {
                                        tranSettlementReport1.setDeductionAmount("0");
                                        //应付=单价x结算重量-扣款
                                        tranSettlementReport1.setAmountIngPayable(tranSettlementReport1.getTransportPrice() * tranSettlementReport1.getSettlementWeight());
                                    } else {
                                        tranSettlementReport1.setDeductionAmount(String.format("%.2f", (Float.valueOf(tranCarInfo.getLoadNetWeight() - tranCarInfo.getUnloadNetWeight()) - (tranCarInfo.getLoadNetWeight() / 1000)) * Float.valueOf(tranCarInfo.getTranPrice())));
                                        //应付=单价x结算重量-扣款
                                        tranSettlementReport1.setAmountIngPayable(tranSettlementReport1.getTransportPrice() * tranSettlementReport1.getSettlementWeight() - Float.valueOf(tranSettlementReport1.getDeductionAmount()));
                                    }
                                }
                                tranSettlementReportService.updateById(tranSettlementReport1);
                                }
                            }
                        else {
                            TranSettlementReport tranSettlementReport=new TranSettlementReport();
                            //生成汽运报表
                            tranSettlementReport.setCompId(tranTaskInfo.getCompId());
                            tranSettlementReport.setCarId(tranCarInfo.getId());
                            tranSettlementReport.setId(IdGenerator.generateUUID());
                            tranSettlementReport.setTranType("汽运");
                            tranSettlementReport.setTranTypeKey("1");
                            tranSettlementReport.setContractNo(tranTaskInfo.getContractNo());
                            tranSettlementReport.setProcessNo(tranProcessInfo.getProcessNo());
                            tranSettlementReport.setName(tranCarInfo.getDriver());
                            tranSettlementReport.setPhone(tranCarInfo.getDriverPhone());
                            tranSettlementReport.setCarNo(tranCarInfo.getCarNo());
                            //查询账户信息
                            List<DriverViewInfo> driverViewInfoList = driverViewInfoService.selectList(new EntityWrapper<DriverViewInfo>()
                                    .eq("driver_name", tranCarInfo.getDriver())
                                    .eq("delete_flag", "0"));
                            if (!CollectionUtils.isEmpty(driverViewInfoList)) {
                                for (DriverViewInfo driverViewInfo : driverViewInfoList) {
                                    List<DriverPayeeInfo> driverPayeeInfoList = driverPayeeInfoService.selectList(new EntityWrapper<DriverPayeeInfo>()
                                            .eq("driver_id", driverViewInfo.getId())
                                            .eq("delete_flag", "0"));
                                    if (!CollectionUtils.isEmpty(driverPayeeInfoList)) {
                                        //本次收款账户
                                        tranSettlementReport.setCardNo(driverPayeeInfoList.get(0).getBankCard());
                                    }
                                }
                            }
                            tranSettlementReport.setSettlementWeight(tranCarInfo.getLoadNetWeight());
                            tranSettlementReport.setTranCarNo(tranCarInfo.getTranCarNo());
                            tranSettlementReport.setLoadingWeight(tranCarInfo.getLoadNetWeight());
                            tranSettlementReport.setLoadingImg(tranCarInfo.getLoadPoundImg());
                            tranSettlementReport.setTransportPrice(Float.valueOf(tranCarInfo.getTranPrice()));
                            tranSettlementReport.setLoadingImg(tranCarInfo.getLoadPoundImg());
                            tranSettlementReport.setUnloadingWeight(tranCarInfo.getUnloadNetWeight());
                            tranSettlementReport.setUnloadingImg(tranCarInfo.getUnloadPoundImg());
                            //损耗
                            tranSettlementReport.setLossWeight(tranCarInfo.getLoadNetWeight() - tranCarInfo.getUnloadNetWeight());
                            //扣款
                            if (tranSettlementReport.getLossWeight() <= (tranCarInfo.getLoadNetWeight() / 1000)) {
                                tranSettlementReport.setDeductionAmount("0");
                                //应付=单价x结算重量-扣款
                                tranSettlementReport.setAmountIngPayable(tranSettlementReport.getTransportPrice() * tranSettlementReport.getSettlementWeight());
                            } else {
                                tranSettlementReport.setDeductionAmount(String.format("%.2f", (Float.valueOf(tranCarInfo.getLoadNetWeight() - tranCarInfo.getUnloadNetWeight()) - (tranCarInfo.getLoadNetWeight() / 1000)) * Float.valueOf(tranCarInfo.getTranPrice())));
                                //应付=单价x结算重量-扣款
                                tranSettlementReport.setAmountIngPayable(tranSettlementReport.getTransportPrice() * tranSettlementReport.getSettlementWeight() - Float.valueOf(tranSettlementReport.getDeductionAmount()));
                            }
                            //未付
                            tranSettlementReport.setAmountNotPayable(tranSettlementReport.getAmountIngPayable());
                            tranSettlementReport.setBatchId(batchReviewInfo.getId());
                            tranSettlementReportService.insert(tranSettlementReport);
                            flagBatch="1";
//                            boolean isStartWorkflow = org.apache.commons.lang3.StringUtils.isBlank(tranSettlementReport.getWorkflowId());
//                            // 不是退回的单子
//                            if (isStartWorkflow) {
//                                Workflow workflow = workflowService
//                                        .findLatestWorkflowByBusinessCodeByApp(tranSettlementReport.getCompId(), "TRANSPORTATION-SETTLEMENT-REPORT");
//                                // 没配置审核流程，直接结束并处理信息
//                                if (workflow == null) {
//                                    throw new YException(YExceptionEnum.PURCHASE_ORDER_ERROR);
//                                }
//                                // 开启审核流
//                                else {
//
//                                    // 设置状态 已提交审核
//                                    tranSettlementReport.setWorkflowId(workflow.getId());
//                                    tranSettlementReportService.updateById(tranSettlementReport);
//                                    workflowService.startInstance(workflow.getId(), tranSettlementReport.getId());
//                                }
//                            }
//                            // 退回的单子 再启用
//                            else {
//                                tranSettlementReportService.updateById(tranSettlementReport);
//                                workflowService.activateInstance(tranSettlementReport.getWorkflowId(), tranSettlementReport.getId());
//                            }
                        }
                    }
                    TranProcessInfo tranProcessInfo1 = this.selectById(tranProcessInfo.getId());
                    //粮款结算阶段
//                  if ("1".equals(tranProcessInfo1.getEndFlag())) {
                    CommonStaff commonStaff = staffService.getInfo(AuthSecurityUtils.getCurrentUserId());
                    //自运的销售合同
                    ContractManagementInfo contractManagementInfo = contractManagementInfoService.selectOne(new EntityWrapper<ContractManagementInfo>()
                            .eq("contract_no", tranProcessInfo1.getContractNo())
                            .eq("deliver_type", "1")
                            .eq("delete_flag", "0"));
                    if (contractManagementInfo != null) {
                            if ("汽运".equals(tranProcessInfo1.getTranType())) {
                                StockSaleReceiptReport stockSaleReceiptReport = stockSaleReceiptReportService.selectOne(new EntityWrapper<StockSaleReceiptReport>()
                                        .eq("process_id", tranProcessInfo1.getId())
                                        .eq("tran_car_no", tranCarInfo.getTranCarNo()));
                                if (stockSaleReceiptReport != null) {
                                    //现货销售出库报表
                                    stockSaleReceiptReport.setFeedbackPerson(commonStaff.getStaffName());
                                    stockSaleReceiptReport.setFeedbackDate(new Date());
                                    stockSaleReceiptReport.setFeedbackWeight(Double.valueOf(String.valueOf(tranCarInfo.getUnloadNetWeight())));
                                    //按收货重量结算时
                                    if("2".equals(contractManagementInfo.getSettlementWeightMethod())&&tranCarInfo.getUnloadNetWeight() > 0){
                                        stockSaleReceiptReport.setSettlementWeight(Double.valueOf(String.valueOf(tranCarInfo.getUnloadNetWeight())));
                                        //定价销售
                                        if(contractManagementInfo.getUnitContractPrice()!=null) {
                                            stockSaleReceiptReport.setSettlementPrice(contractManagementInfo.getUnitContractPrice());
                                            stockSaleReceiptReport.setAmountIngReceivable(tranCarInfo.getUnloadNetWeight()*
                                                    (contractManagementInfo.getUnitContractPrice()));
                                            stockSaleReceiptReport.setAmountEdReceivable(0.00);
                                            stockSaleReceiptReport.setAmountNotReceivable(stockSaleReceiptReport.getAmountIngReceivable());
                                        }
                                        //随行就市
                                        else {
                                            stockSaleReceiptReport.setSettlementPrice(Double.valueOf(String.valueOf(tranCarInfo.getContractPrice())));
                                            stockSaleReceiptReport.setAmountIngReceivable(Double.valueOf(String.valueOf(tranCarInfo.getUnloadNetWeight() *tranCarInfo.getContractPrice())));
                                            stockSaleReceiptReport.setAmountEdReceivable(0.00);
                                            stockSaleReceiptReport.setAmountNotReceivable(stockSaleReceiptReport.getAmountIngReceivable());
                                        }
                                    }
                                    //按出库重量结算时
                                    else if("1".equals(contractManagementInfo.getSettlementWeightMethod())){
                                        //随行就市
                                        if(contractManagementInfo.getUnitContractPrice()==null) {
                                            stockSaleReceiptReport.setSettlementPrice(Double.valueOf(String.valueOf(tranCarInfo.getContractPrice())));
                                            stockSaleReceiptReport.setAmountIngReceivable(Double.valueOf(String.valueOf(stockSaleReceiptReport.getSettlementWeight()*
                                                    (tranCarInfo.getContractPrice()))));
                                            stockSaleReceiptReport.setAmountEdReceivable(0.00);
                                            stockSaleReceiptReport.setAmountNotReceivable(stockSaleReceiptReport.getAmountIngReceivable());
                                        }
                                    }
                                    stockSaleReceiptReportService.updateById(stockSaleReceiptReport);
                                }
                            }
                            else if ("火运".equals(tranProcessInfo1.getTranType())) {
                                StockSaleReceiptReport stockSaleReceiptReport = stockSaleReceiptReportService.selectOne(new EntityWrapper<StockSaleReceiptReport>()
                                        .eq("process_id", tranProcessInfo1.getId())
                                        .eq("car_no", tranCarInfo.getCarNo())
                                        .eq("box_no", tranCarInfo.getBoxNo()));
                                if (stockSaleReceiptReport != null) {
                                    //现货销售出库报表
                                    stockSaleReceiptReport.setFeedbackPerson(commonStaff.getStaffName());
                                    stockSaleReceiptReport.setFeedbackDate(new Date());
                                    stockSaleReceiptReport.setFeedbackWeight(Double.valueOf(String.valueOf(tranCarInfo.getUnloadNetWeight())));
                                    //按收货重量结算时
                                    if("1".equals(contractManagementInfo.getSettlementWeightMethod())){
                                        stockSaleReceiptReport.setSettlementWeight(Double.valueOf(String.valueOf(tranCarInfo.getUnloadNetWeight())));
                                        //定价销售
                                        if(contractManagementInfo.getUnitContractPrice()!=null) {
                                            stockSaleReceiptReport.setSettlementPrice(contractManagementInfo.getUnitContractPrice());
                                            stockSaleReceiptReport.setAmountIngReceivable(tranCarInfo.getUnloadNetWeight()*
                                                    (contractManagementInfo.getUnitContractPrice()));
                                            stockSaleReceiptReport.setAmountEdReceivable(0.00);
                                            stockSaleReceiptReport.setAmountNotReceivable(stockSaleReceiptReport.getAmountIngReceivable());
                                        }
                                        //随行就市
                                        else {
                                            stockSaleReceiptReport.setSettlementPrice(Double.valueOf(String.valueOf(tranCarInfo.getContractPrice())));
                                            stockSaleReceiptReport.setAmountIngReceivable(Double.valueOf(String.valueOf(tranCarInfo.getUnloadNetWeight() *tranCarInfo.getContractPrice())));
                                            stockSaleReceiptReport.setAmountEdReceivable(0.00);
                                            stockSaleReceiptReport.setAmountNotReceivable(stockSaleReceiptReport.getAmountIngReceivable());
                                        }
                                    }
                                    //按出库重量结算时
                                    else{
                                        //随行就市
                                        if(contractManagementInfo.getUnitContractPrice()==null) {
                                            stockSaleReceiptReport.setSettlementPrice(Double.valueOf(String.valueOf(tranCarInfo.getContractPrice())));
                                            stockSaleReceiptReport.setAmountIngReceivable(Double.valueOf(String.valueOf(stockSaleReceiptReport.getSettlementWeight()*
                                                    (tranCarInfo.getContractPrice()))));
                                            stockSaleReceiptReport.setAmountEdReceivable(0.00);
                                            stockSaleReceiptReport.setAmountNotReceivable(stockSaleReceiptReport.getAmountIngReceivable());
                                        }
                                    }
                                    stockSaleReceiptReportService.updateById(stockSaleReceiptReport);
                                }
                            }
                            else if (tranCarInfo.getShipType() != null && "散船".equals(tranCarInfo.getShipType())) {
                                StockSaleReceiptReport stockSaleReceiptReport = stockSaleReceiptReportService.selectOne(new EntityWrapper<StockSaleReceiptReport>()
                                        .eq("process_id", tranProcessInfo1.getId())
                                        .eq("ship_no", tranCarInfo.getShipNo())
                                        .eq("ship_name", tranCarInfo.getShipName()));
                                if (stockSaleReceiptReport != null) {
                                    //现货销售出库报表
                                    stockSaleReceiptReport.setFeedbackPerson(commonStaff.getStaffName());
                                    stockSaleReceiptReport.setFeedbackDate(new Date());
                                    stockSaleReceiptReport.setFeedbackWeight(Double.valueOf(String.valueOf(tranCarInfo.getUnloadNetWeight())));
                                    //按收货重量结算时
                                    if("1".equals(contractManagementInfo.getSettlementWeightMethod())){
                                        stockSaleReceiptReport.setSettlementWeight(Double.valueOf(String.valueOf(tranCarInfo.getUnloadNetWeight())));
                                        //定价销售
                                        if(contractManagementInfo.getUnitContractPrice()!=null) {
                                            stockSaleReceiptReport.setSettlementPrice(contractManagementInfo.getUnitContractPrice());
                                            stockSaleReceiptReport.setAmountIngReceivable(tranCarInfo.getUnloadNetWeight()*
                                                    (contractManagementInfo.getUnitContractPrice()));
                                            stockSaleReceiptReport.setAmountEdReceivable(0.00);
                                            stockSaleReceiptReport.setAmountNotReceivable(stockSaleReceiptReport.getAmountIngReceivable());
                                        }
                                        //随行就市
                                        else {
                                            stockSaleReceiptReport.setSettlementPrice(Double.valueOf(String.valueOf(tranCarInfo.getContractPrice())));
                                            stockSaleReceiptReport.setAmountIngReceivable(Double.valueOf(String.valueOf(tranCarInfo.getUnloadNetWeight() *tranCarInfo.getContractPrice())));
                                            stockSaleReceiptReport.setAmountEdReceivable(0.00);
                                            stockSaleReceiptReport.setAmountNotReceivable(stockSaleReceiptReport.getAmountIngReceivable());
                                        }
                                    }
                                    //按出库重量结算时
                                    else{
                                        //随行就市
                                        if(contractManagementInfo.getUnitContractPrice()==null) {
                                            stockSaleReceiptReport.setSettlementPrice(Double.valueOf(String.valueOf(tranCarInfo.getContractPrice())));
                                            stockSaleReceiptReport.setAmountIngReceivable(Double.valueOf(String.valueOf(stockSaleReceiptReport.getSettlementWeight()*
                                                    (tranCarInfo.getContractPrice()))));
                                            stockSaleReceiptReport.setAmountEdReceivable(0.00);
                                            stockSaleReceiptReport.setAmountNotReceivable(stockSaleReceiptReport.getAmountIngReceivable());
                                        }
                                    }
                                    stockSaleReceiptReportService.updateById(stockSaleReceiptReport);
                                }
                            }
                            else if (tranCarInfo.getShipType() != null && "集装箱".equals(tranCarInfo.getShipType())) {
                                StockSaleReceiptReport stockSaleReceiptReport = stockSaleReceiptReportService.selectOne(new EntityWrapper<StockSaleReceiptReport>()
                                        .eq("process_id", tranProcessInfo1.getId())
                                        .eq("title_no", tranCarInfo.getTitleNo())
                                        .eq("case_no", tranCarInfo.getCaseNo()));
                                if (stockSaleReceiptReport != null) {
                                    //现货销售出库报表
                                    stockSaleReceiptReport.setFeedbackPerson(commonStaff.getStaffName());
                                    stockSaleReceiptReport.setFeedbackDate(new Date());
                                    stockSaleReceiptReport.setFeedbackWeight(Double.valueOf(String.valueOf(tranCarInfo.getUnloadNetWeight())));
                                    //按收货重量结算时
                                    if("1".equals(contractManagementInfo.getSettlementWeightMethod())){
                                        stockSaleReceiptReport.setSettlementWeight(Double.valueOf(String.valueOf(tranCarInfo.getUnloadNetWeight())));
                                        //定价销售
                                        if(contractManagementInfo.getUnitContractPrice()!=null) {
                                            stockSaleReceiptReport.setSettlementPrice(contractManagementInfo.getUnitContractPrice());
                                            stockSaleReceiptReport.setAmountIngReceivable(tranCarInfo.getUnloadNetWeight()*
                                                    (contractManagementInfo.getUnitContractPrice()));
                                            stockSaleReceiptReport.setAmountEdReceivable(0.00);
                                            stockSaleReceiptReport.setAmountNotReceivable(stockSaleReceiptReport.getAmountIngReceivable());
                                        }
                                        //随行就市
                                        else {
                                            stockSaleReceiptReport.setSettlementPrice(Double.valueOf(String.valueOf(tranCarInfo.getContractPrice())));
                                            stockSaleReceiptReport.setAmountIngReceivable(Double.valueOf(String.valueOf(tranCarInfo.getUnloadNetWeight() *tranCarInfo.getContractPrice())));
                                            stockSaleReceiptReport.setAmountEdReceivable(0.00);
                                            stockSaleReceiptReport.setAmountNotReceivable(stockSaleReceiptReport.getAmountIngReceivable());
                                        }
                                    }
                                    //按出库重量结算时
                                    else{
                                        //随行就市
                                        if(contractManagementInfo.getUnitContractPrice()==null) {
                                            stockSaleReceiptReport.setSettlementPrice(Double.valueOf(String.valueOf(tranCarInfo.getContractPrice())));
                                            stockSaleReceiptReport.setAmountIngReceivable(Double.valueOf(String.valueOf(stockSaleReceiptReport.getSettlementWeight()*
                                                    (tranCarInfo.getContractPrice()))));
                                            stockSaleReceiptReport.setAmountEdReceivable(0.00);
                                            stockSaleReceiptReport.setAmountNotReceivable(stockSaleReceiptReport.getAmountIngReceivable());
                                        }
                                    }
                                    stockSaleReceiptReportService.updateById(stockSaleReceiptReport);
                                }
                            }
                        }
                    }
                    //船运集装箱
                    if (tranCarInfoList.get(0).getTranType().equals(NumberConstant.CONSTANT3)&&"集装箱".equals(tranCarInfoList.get(0).getShipType())) {
                       //查到一个阶段下的集装箱信息
                        List<TranCarInfo> tranCarInfos=tranCarInfoService.selectList(new EntityWrapper<TranCarInfo>()
                       .eq("process_id",tranCarInfo.getProcessId()));
                       if (!CollectionUtils.isEmpty(tranCarInfos)){
                          for (TranCarInfo tranCarInfo1:tranCarInfos){
                              tranCarInfo1.setShipName(tranCarInfo.getShipName());
                              tranCarInfo1.setShipNo(tranCarInfo.getShipNo());
                              //更新
                              tranCarInfoService.updateById(tranCarInfo1);
                          }
                       }
                    }
                    tranCarInfoService.updateById(tranCarInfo);
                }
            // 批次开启审核流
            if("1".equals(flagBatch)){
                batchReviewInfo.setCompId(AuthSecurityUtils.getCurrentUserInfo().getCompId());
                batchReviewInfoService.insert(batchReviewInfo);
                boolean isStartWorkflow = org.apache.commons.lang3.StringUtils.isBlank(batchReviewInfo.getWorkflowId());
                // 不是退回的单子
                if (isStartWorkflow) {
                    Workflow workflow = workflowService
                            .findLatestWorkflowByBusinessCodeByApp(batchReviewInfo.getCompId(), "TRANSPORTATION-SETTLEMENT-REPORT");
                    // 没配置审核流程，直接结束并处理信息
                    if (workflow == null) {
                        throw new YException(YExceptionEnum.PURCHASE_ORDER_ERROR);
                    }
                    // 开启审核流
                    else {

                        // 设置状态 已提交审核
                        batchReviewInfo.setWorkflowId(workflow.getId());
                        batchReviewInfoService.updateById(batchReviewInfo);
                        workflowService.startInstance(workflow.getId(), batchReviewInfo.getId());
                    }
                }
                //  更新详细状态
                batchReviewInfo = batchReviewInfoService.selectById(batchReviewInfo.getId());
                List<TranSettlementReport> tranSettlementReports = tranSettlementReportService.selectList(new EntityWrapper<TranSettlementReport>()
                        .eq("batch_id",batchReviewInfo.getId()));
                if(!CollectionUtils.isEmpty(tranSettlementReports)){
                    for(int i=0;i<tranSettlementReports.size();i++){
                        TranSettlementReport settlementReport = tranSettlementReports.get(i);
                        settlementReport.setWorkflowId(batchReviewInfo.getWorkflowId());
                        settlementReport.setStatus(batchReviewInfo.getStatus());
                        settlementReport.setApproveStatus(batchReviewInfo.getApproveStatus());
                    }
                    tranSettlementReportService.updateBatchById(tranSettlementReports);
                }
            }
        }
        cacheComponent.delPrefixKey(Const.ADMIN_CONTRACTINFO);
        return tranProcessInfo.getId();
    }

    /**
     * 更改发货反馈状态
     *
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String editFeedbackStatus(String id) {
        //查询反馈信息
        TranProcessInfo tranProcessInfo = this.selectById(id);
        if (tranProcessInfo != null) {
            if (StatusEnum.FEEDBACK_DO.getFlag().equals(tranProcessInfo.getFeedbackStatusFlag())) {
                tranProcessInfo.setFeedbackStatusFlag(StatusEnum.FEEDBACK_COMPLETED.getFlag());
                tranProcessInfo.setFeedbackStatus(StatusEnum.FEEDBACK_COMPLETED.getName());
            } else {
                tranProcessInfo.setFeedbackStatusFlag(StatusEnum.FEEDBACK_DO.getFlag());
                tranProcessInfo.setFeedbackStatus(StatusEnum.FEEDBACK_DO.getName());
            }
            this.updateById(tranProcessInfo);
            // 插入操作历史
            String staffName = this.billOperateHisService.getStaffAndName();
            // 插入操作历史
            this.billOperateHisService.saveBillOperateHis(tranProcessInfo.getId(), NumberConstant.CONSTANT_FEEDBACK, staffName, null,
                    tranProcessInfo.getProcessStatus(), null, "");
            return "OK";
        }
        return "NG";
    }
    /**
     * 更改收货反馈状态
     *
     * @param tranProcessInfo
     * @return
     */
    @Override
    public String editReceivingStatus(TranProcessInfo tranProcessInfo) {
        //查询反馈信息
        TranProcessInfo tranProcessInfo1 = this.selectById(tranProcessInfo.getId());
        if (tranProcessInfo1 != null) {
            if (StatusEnum.FEEDBACK_DO.getFlag().equals(tranProcessInfo1.getReceivingStatusFlag())) {
                //打入完货净重
                if (tranProcessInfo.getWeight()!=null){
                    tranProcessInfo1.setWeight(tranProcessInfo.getWeight());
                }
                tranProcessInfo1.setReceivingStatusFlag(StatusEnum.FEEDBACK_COMPLETED.getFlag());
                tranProcessInfo1.setReceivingStatus(StatusEnum.FEEDBACK_COMPLETED.getName());
            } else {
                tranProcessInfo1.setReceivingStatusFlag(StatusEnum.FEEDBACK_DO.getFlag());
                tranProcessInfo1.setReceivingStatus(StatusEnum.FEEDBACK_DO.getName());
            }
            this.updateById(tranProcessInfo1);
            // 插入操作历史
            String staffName = this.billOperateHisService.getStaffAndName();
            // 插入操作历史
            this.billOperateHisService.saveBillOperateHis(tranProcessInfo1.getId(), NumberConstant.CONSTANT_FEEDBACK, staffName, null,
                    tranProcessInfo1.getProcessStatus(), null, "");
            return "OK";
        }
        return "NG";
    }

    /**
     * 删除运输阶段
     *
     * @param id
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteTranProcess(String id) {
        TranProcessInfo tranProcessInfo = this.selectById(id);
        if (tranProcessInfo != null) {
            this.deleteById(tranProcessInfo.getId());
        }
    }

    /**
     * 设置运输价格
     *
     * @param tranProcessInfo
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public String setUpTranPrice(TranProcessInfo tranProcessInfo) {
        //物流部提交
        if ("1".equals(tranProcessInfo.getFlag())) {
            tranProcessInfo.setPriceStatus("审核中");
            List<String> roleIdList = Lists.newArrayList();
            if("1".equals(tranProcessInfo.getTranTypeKey())){
                roleIdList = roleResourceService.getBindRoleIdsByResourceIds(AuthSecurityUtils.getCurrentUserInfo().getCompId(),
                        Lists.newArrayList("transportationInfo-Exe"));
                tesk(tranProcessInfo,roleIdList);
            }
            else if("2".equals(tranProcessInfo.getTranTypeKey())){
                roleIdList = roleResourceService.getBindRoleIdsByResourceIds(AuthSecurityUtils.getCurrentUserInfo().getCompId(),
                        Lists.newArrayList("transportationInfo-Trian"));
                tesk(tranProcessInfo,roleIdList);
            }
            else{
                roleIdList = roleResourceService.getBindRoleIdsByResourceIds(AuthSecurityUtils.getCurrentUserInfo().getCompId(),
                        Lists.newArrayList("transportationInfo-Ship"));
                tesk(tranProcessInfo,roleIdList);
            }

        }
        //决策人审核
        else if ("2".equals(tranProcessInfo.getFlag())) {
            tranProcessInfo.setTranPrice(tranProcessInfo.getTranPriceIng());
            tranProcessInfo.setTranPriceIng(0.0f);
            tranProcessInfo.setPriceStatus("已通过");
            //汽运生成审核记录
            if(tranProcessInfo.getTranTypeKey()!=null&&"1".equals(tranProcessInfo.getTranTypeKey())) {
                //生成审核记录
                TranPriceApprove tranPriceApprove = new TranPriceApprove();
                tranPriceApprove.setProcessId(tranProcessInfo.getId());
                tranPriceApprove.setId(IdGenerator.generateUUID());
                tranPriceApprove.setReviewer(tranProcessInfo.getReviewer());
                tranPriceApprove.setResult("通过");
                tranPriceApprove.setRecordType("1");
                tranPriceApprove.setTranPrice(tranProcessInfo.getTranPrice());
                tranPriceApproveService.insert(tranPriceApprove);
            }
            // 先删除任务
            noticeService.removeNotice(BaseNotice.NoticeStatus.TASK, "TRAN-TASK-APPROVE",
                    tranProcessInfo.getId(), null);
        }
        this.updateById(tranProcessInfo);
        return "ok";
    }

    @Override
    public String setUpTranPriceCar(TranProcessInfo tranProcessInfo) {
        //物流部提交
        if ("1".equals(tranProcessInfo.getFlag())) {
            tranProcessInfo.setPriceStatusCar("审核中");
            List<String> roleIdList = Lists.newArrayList();
            if("1".equals(tranProcessInfo.getTranTypeKey())){
                roleIdList = roleResourceService.getBindRoleIdsByResourceIds(AuthSecurityUtils.getCurrentUserInfo().getCompId(),
                        Lists.newArrayList("transportationInfo-Execar"));
                teskCar(tranProcessInfo,roleIdList);
            }
            else if("2".equals(tranProcessInfo.getTranTypeKey())){
                roleIdList = roleResourceService.getBindRoleIdsByResourceIds(AuthSecurityUtils.getCurrentUserInfo().getCompId(),
                        Lists.newArrayList("transportationInfo-Triancar"));
                teskCar(tranProcessInfo,roleIdList);
            }
            else{
                roleIdList = roleResourceService.getBindRoleIdsByResourceIds(AuthSecurityUtils.getCurrentUserInfo().getCompId(),
                        Lists.newArrayList("transportationInfo-Shipcar"));
                teskCar(tranProcessInfo,roleIdList);
            }

        }
        //决策人审核
        else if ("2".equals(tranProcessInfo.getFlag())) {
            tranProcessInfo.setTranPriceCar(tranProcessInfo.getTranPriceIngCar());
            tranProcessInfo.setTranPriceIngCar(0.0f);
            tranProcessInfo.setPriceStatusCar("已通过");
            //汽运生成审核记录
            if(tranProcessInfo.getTranTypeKey()!=null&&"1".equals(tranProcessInfo.getTranTypeKey())) {
                //生成审核记录
                TranPriceApprove tranPriceApprove = new TranPriceApprove();
                tranPriceApprove.setProcessId(tranProcessInfo.getId());
                tranPriceApprove.setId(IdGenerator.generateUUID());
                tranPriceApprove.setReviewer(tranProcessInfo.getReviewer());
                tranPriceApprove.setResult("通过");
                tranPriceApprove.setRecordType("1");
                tranPriceApprove.setTranPrice(tranProcessInfo.getTranPriceCar());
                tranPriceApproveService.insert(tranPriceApprove);
            }
            // 先删除任务
            noticeService.removeNotice(BaseNotice.NoticeStatus.TASK, "TRAN-TEAM-APPROVE",
                    tranProcessInfo.getId(), null);
        }
        this.updateById(tranProcessInfo);
        return "ok";
    }


    /**
     * 任务
     *
     * @param tranProcessInfo
     */
    private void tesk(TranProcessInfo tranProcessInfo, List<String> roleIdList) {
        // 先删除任务
        noticeService.removeNotice(BaseNotice.NoticeStatus.TASK, "TRAN-TASK-APPROVE",
                tranProcessInfo.getId(), null);
        String staffName = "XXX";
        CommonStaff commitUserInfo = staffService.getInfo(AuthSecurityUtils.getCurrentUserId());
        if (commitUserInfo != null) {
            staffName = commitUserInfo.getMajorRole() != null
                    ? commitUserInfo.getMajorRole().getRoleName() + " " + commitUserInfo.getStaffName()
                    : commitUserInfo.getStaffName();
        }
        String taskContent = "";
        // 向下一步操作人发送任务通知
            taskContent =  staffName + "提交的运输单价等待审核";
        NoticeTaskInfo taskInfo = new NoticeTaskInfo();
        taskInfo.setCompId(commitUserInfo.getCompId());
        taskInfo.setAcceptType(BaseNotice.AcceptStatus.ROLE);
        taskInfo.setBusinessId(tranProcessInfo.getId());
        taskInfo.setBusinessType("Tran");
        taskInfo.setMessageContent(taskContent);
        taskInfo.setBusinessCode("TRAN-TASK-APPROVE");
//            taskInfo.setNoticeTaskStatus(NoticeTaskInfo.NoticeTaskStatus.RETURN);
        noticeTaskService.createNoticeTask(roleIdList,
                null, taskInfo);

    }

    private void teskCar(TranProcessInfo tranProcessInfo, List<String> roleIdList) {
        // 先删除任务
        noticeService.removeNotice(BaseNotice.NoticeStatus.TASK, "TRAN-TEAM-APPROVE",
                tranProcessInfo.getId(), null);
        String staffName = "XXX";
        CommonStaff commitUserInfo = staffService.getInfo(AuthSecurityUtils.getCurrentUserId());
        if (commitUserInfo != null) {
            staffName = commitUserInfo.getMajorRole() != null
                    ? commitUserInfo.getMajorRole().getRoleName() + " " + commitUserInfo.getStaffName()
                    : commitUserInfo.getStaffName();
        }
        List<CommonStaffRole> commonStaffRoles = commonStaffRoleService.findStaff(roleIdList);
        List<String> staffIds = commonStaffRoles.stream().map(CommonStaffRole::getStaffId).collect(Collectors.toList());
        String taskContent = "";
        // 向下一步操作人发送任务通知
        taskContent =  staffName + "提交的运输单价等待审核";
        NoticeTaskInfo taskInfo = new NoticeTaskInfo();
        taskInfo.setCompId(commitUserInfo.getCompId());
        taskInfo.setAcceptType(BaseNotice.AcceptStatus.STAFF);
        taskInfo.setBusinessId(tranProcessInfo.getId());
        taskInfo.setBusinessType("Tran");
        taskInfo.setMessageContent(taskContent);
        taskInfo.setBusinessCode("TRAN-TEAM-APPROVE");
//            taskInfo.setNoticeTaskStatus(NoticeTaskInfo.NoticeTaskStatus.RETURN);
        noticeTaskService.createNoticeTask(staffIds,
                null, taskInfo);

    }

    /**
     * 他运反馈
     * @param tranProcessInfo
     * @return
     */
    @Override
    public String addTranCar(TranProcessInfo tranProcessInfo){
        ContractManagementInfo contractManagementInfo = contractManagementInfoService.selectOne(new EntityWrapper<ContractManagementInfo>()
            .eq("contract_no",tranProcessInfo.getContractNo())
            .eq("delete_flag","0"));
        TranTaskInfo tranTaskInfo=tranTaskInfoService.selectById(tranProcessInfo.getInfoId());
        //采购
        if("2".equals(contractManagementInfo.getContractType())){
            //更改运输调度发货运输方式
            this.updateById(tranProcessInfo);
            List<TranCarInfo> tranCarInfoList1 = tranProcessInfo.getTranCarInfoList1();
            if (!CollectionUtils.isEmpty(tranCarInfoList1)) {
                for (TranCarInfo tranCarInfo : tranCarInfoList1) {
                    //新增
                    if (StringUtils.isEmpty(tranCarInfo.getId())) {
                        tranCarInfo.setCompId(tranTaskInfo.getCompId());
                        tranCarInfo.setProcessId(tranProcessInfo.getId());
                        tranCarInfo.setInfoId(tranProcessInfo.getInfoId());
                        tranCarInfo.setId(IdGenerator.generateUUID());
                        tranCarInfo.setThreeTranType("汽运");
                        tranCarInfo.setTranType("4");
                        tranCarInfo.setContractNo(tranProcessInfo.getContractNo());
                        tranCarInfo.setStatusFlag(StatusEnum.LOADED.getFlag());
                        tranCarInfo.setStatus(StatusEnum.LOADED.getName());
                        tranCarInfoService.insert(tranCarInfo);
                    }
                }
            }
            List<TranCarInfo> tranCarInfoList2 = tranProcessInfo.getTranCarInfoList2();
            if (!CollectionUtils.isEmpty(tranCarInfoList2)) {
                for (TranCarInfo tranCarInfo : tranCarInfoList2) {
                    //新增
                    if (StringUtils.isEmpty(tranCarInfo.getId())) {
                        tranCarInfo.setCompId(tranTaskInfo.getCompId());
                        tranCarInfo.setProcessId(tranProcessInfo.getId());
                        tranCarInfo.setInfoId(tranProcessInfo.getInfoId());
                        tranCarInfo.setId(IdGenerator.generateUUID());
                        tranCarInfo.setThreeTranType("火运");
                        tranCarInfo.setTranType("4");
                        tranCarInfo.setContractNo(tranProcessInfo.getContractNo());
                        tranCarInfo.setStatusFlag(StatusEnum.LOADED.getFlag());
                        tranCarInfo.setStatus(StatusEnum.LOADED.getName());
                        tranCarInfoService.insert(tranCarInfo);
                    }
                }
            }
            List<TranCarInfo> tranCarInfoList3 = tranProcessInfo.getTranCarInfoList3();
            if (!CollectionUtils.isEmpty(tranCarInfoList3)) {
                for (TranCarInfo tranCarInfo : tranCarInfoList3) {
                    //新增
                    if (StringUtils.isEmpty(tranCarInfo.getId())) {
                        tranCarInfo.setCompId(tranTaskInfo.getCompId());
                        tranCarInfo.setProcessId(tranProcessInfo.getId());
                        tranCarInfo.setInfoId(tranProcessInfo.getInfoId());
                        tranCarInfo.setId(IdGenerator.generateUUID());
                        tranCarInfo.setThreeTranType("散船");
                        tranCarInfo.setTranType("4");
                        tranCarInfo.setContractNo(tranProcessInfo.getContractNo());
                        tranCarInfo.setStatusFlag(StatusEnum.LOADED.getFlag());
                        tranCarInfo.setStatus(StatusEnum.LOADED.getName());
                        tranCarInfoService.insert(tranCarInfo);
                    }
                }
            }
            List<TranCarInfo> tranCarInfoList4 = tranProcessInfo.getTranCarInfoList4();
            if (!CollectionUtils.isEmpty(tranCarInfoList4)) {
                for (TranCarInfo tranCarInfo : tranCarInfoList4) {
                    //新增
                    if (StringUtils.isEmpty(tranCarInfo.getId())) {
                        tranCarInfo.setCompId(tranTaskInfo.getCompId());
                        tranCarInfo.setProcessId(tranProcessInfo.getId());
                        tranCarInfo.setInfoId(tranProcessInfo.getInfoId());
                        tranCarInfo.setId(IdGenerator.generateUUID());
                        tranCarInfo.setThreeTranType("集装箱船");
                        tranCarInfo.setTranType("4");
                        tranCarInfo.setContractNo(tranProcessInfo.getContractNo());
                        tranCarInfo.setStatusFlag(StatusEnum.LOADED.getFlag());
                        tranCarInfo.setStatus(StatusEnum.LOADED.getName());
                        tranCarInfoService.insert(tranCarInfo);
                    }
                }
            }
        }
        //销售
        else{
            List<TranCarInfo> tranCarInfoList1 = tranProcessInfo.getTranCarInfoList1();
            if (!CollectionUtils.isEmpty(tranCarInfoList1)) {
                for (TranCarInfo tranCarInfo : tranCarInfoList1) {
                    tranCarInfo.setStatusFlag(StatusEnum.DELIVERED.getFlag());
                    tranCarInfo.setStatus(StatusEnum.DELIVERED.getName());
                    tranCarInfoService.updateById(tranCarInfo);
                    StockSaleReceiptReport stockSaleReceiptReport = stockSaleReceiptReportService.selectOne(new EntityWrapper<StockSaleReceiptReport>()
                            .eq("process_id",tranProcessInfo.getId())
                            .eq("car_no",tranCarInfo.getCarNo()));
                    if (stockSaleReceiptReport != null){
                        stockSaleReceiptReport.setFeedbackWeight(Double.valueOf(String.valueOf(tranCarInfo.getUnloadNetWeight())));
                        stockSaleReceiptReport.setFeedbackDate(tranCarInfo.getUnloadingDate());
                        stockSaleReceiptReportService.updateById(stockSaleReceiptReport);
                    }
                }
            }
            List<TranCarInfo> tranCarInfoList2 = tranProcessInfo.getTranCarInfoList2();
            if (!CollectionUtils.isEmpty(tranCarInfoList2)) {
                for (TranCarInfo tranCarInfo : tranCarInfoList2) {
                    tranCarInfo.setStatusFlag(StatusEnum.DELIVERED.getFlag());
                    tranCarInfo.setStatus(StatusEnum.DELIVERED.getName());
                    tranCarInfoService.updateById(tranCarInfo);
                    StockSaleReceiptReport stockSaleReceiptReport = stockSaleReceiptReportService.selectOne(new EntityWrapper<StockSaleReceiptReport>()
                            .eq("process_id",tranProcessInfo.getId())
                            .eq("car_no",tranCarInfo.getCarNo())
                            .eq("box_no",tranCarInfo.getBoxNo()));
                    if (stockSaleReceiptReport != null){
                        stockSaleReceiptReport.setFeedbackWeight(Double.valueOf(String.valueOf(tranCarInfo.getUnloadNetWeight())));
                        stockSaleReceiptReport.setFeedbackDate(tranCarInfo.getUnloadingDate());
                        stockSaleReceiptReportService.updateById(stockSaleReceiptReport);
                    }
                }
            }
            List<TranCarInfo> tranCarInfoList3 = tranProcessInfo.getTranCarInfoList3();
            if (!CollectionUtils.isEmpty(tranCarInfoList3)) {
                for (TranCarInfo tranCarInfo : tranCarInfoList3) {
                    tranCarInfo.setStatusFlag(StatusEnum.DELIVERED.getFlag());
                    tranCarInfo.setStatus(StatusEnum.DELIVERED.getName());
                    tranCarInfoService.updateById(tranCarInfo);
                    StockSaleReceiptReport stockSaleReceiptReport = stockSaleReceiptReportService.selectOne(new EntityWrapper<StockSaleReceiptReport>()
                            .eq("process_id",tranProcessInfo.getId())
                            .eq("ship_name",tranCarInfo.getShipName())
                            .eq("ship_no",tranCarInfo.getShipNo()));
                    if (stockSaleReceiptReport != null){
                        stockSaleReceiptReport.setFeedbackWeight(Double.valueOf(String.valueOf(tranCarInfo.getUnloadNetWeight())));
                        stockSaleReceiptReport.setFeedbackDate(tranCarInfo.getUnloadingDate());
                        stockSaleReceiptReportService.updateById(stockSaleReceiptReport);
                    }
                }
            }
            List<TranCarInfo> tranCarInfoList4 = tranProcessInfo.getTranCarInfoList4();
            if (!CollectionUtils.isEmpty(tranCarInfoList4)) {
                for (TranCarInfo tranCarInfo : tranCarInfoList4) {
                    tranCarInfo.setStatusFlag(StatusEnum.DELIVERED.getFlag());
                    tranCarInfo.setStatus(StatusEnum.DELIVERED.getName());
                    tranCarInfoService.updateById(tranCarInfo);
                    StockSaleReceiptReport stockSaleReceiptReport = stockSaleReceiptReportService.selectOne(new EntityWrapper<StockSaleReceiptReport>()
                            .eq("process_id",tranProcessInfo.getId())
                            .eq("case_no",tranCarInfo.getCaseNo())
                            .eq("title_no",tranCarInfo.getTitleNo()));
                    if (stockSaleReceiptReport != null){
                        stockSaleReceiptReport.setFeedbackWeight(Double.valueOf(String.valueOf(tranCarInfo.getUnloadNetWeight())));
                        stockSaleReceiptReport.setFeedbackDate(tranCarInfo.getUnloadingDate());
                        stockSaleReceiptReportService.updateById(stockSaleReceiptReport);
                    }
                }
            }
        }
        return "Ok";
    }

    /**
     * 查看他运反馈
     * @param id
     * @return
     */
    @Override
    public TranProcessInfo getThreeTranProcess (String id){
        //查看运输信息
        TranProcessInfo tranProcessInfo = this.selectById(id);
        //查看车次信息
        List<TranCarInfo> tranCarInfoList1 = tranCarInfoService.selectList(new EntityWrapper<TranCarInfo>()
                .eq(TranCarInfo.QueryFiles.PROCESS_ID, id)
                .eq(TranCarInfo.QueryFiles.DELETE_FLAG, NumberConstant.CONSTANT0)
                .eq("three_tran_type","汽运")
                .orderBy("tran_car_no").orderBy("box_no"));
        //查看车次信息
        List<TranCarInfo> tranCarInfoList2 = tranCarInfoService.selectList(new EntityWrapper<TranCarInfo>()
                .eq(TranCarInfo.QueryFiles.PROCESS_ID, id)
                .eq(TranCarInfo.QueryFiles.DELETE_FLAG, NumberConstant.CONSTANT0)
                .eq("three_tran_type","火运")
                .orderBy("tran_car_no").orderBy("box_no"));
        //查看车次信息
        List<TranCarInfo> tranCarInfoList3 = tranCarInfoService.selectList(new EntityWrapper<TranCarInfo>()
                .eq(TranCarInfo.QueryFiles.PROCESS_ID, id)
                .eq(TranCarInfo.QueryFiles.DELETE_FLAG, NumberConstant.CONSTANT0)
                .eq("three_tran_type","散船")
                .orderBy("tran_car_no").orderBy("box_no"));
        //查看车次信息
        List<TranCarInfo> tranCarInfoList4 = tranCarInfoService.selectList(new EntityWrapper<TranCarInfo>()
                .eq(TranCarInfo.QueryFiles.PROCESS_ID, id)
                .eq(TranCarInfo.QueryFiles.DELETE_FLAG, NumberConstant.CONSTANT0)
                .eq("three_tran_type","集装箱船")
                .orderBy("tran_car_no").orderBy("box_no"));
        if(!CollectionUtils.isEmpty(tranCarInfoList1)){
            tranProcessInfo.setTranCarInfoList1(tranCarInfoList1);
        }
        if(!CollectionUtils.isEmpty(tranCarInfoList2)){
            tranProcessInfo.setTranCarInfoList2(tranCarInfoList2);
        }
        if(!CollectionUtils.isEmpty(tranCarInfoList3)){
            tranProcessInfo.setTranCarInfoList3(tranCarInfoList3);
        }
        if(!CollectionUtils.isEmpty(tranCarInfoList4)){
            tranProcessInfo.setTranCarInfoList4(tranCarInfoList4);
        }
        return tranProcessInfo;
    }
}
