package com.ruoyi.warehouseBusiness.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.ruoyi.approvalFlow.domain.AuditItems;
import com.ruoyi.approvalFlow.mapper.AuditItemsMapper;
import com.ruoyi.approvalFlow.mapper.AuditItemsUsersMapper;
import com.ruoyi.approvalFlow.service.impl.AuditItemsServiceImpl;
import com.ruoyi.basicData.domain.*;
import com.ruoyi.basicData.mapper.*;
import com.ruoyi.basicData.service.impl.TWarehouseServiceImpl;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.entity.TWarehouse;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.WarehouseException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ip.AddressUtils;
import com.ruoyi.common.utils.poi.ExcelUtils;
import com.ruoyi.quotation.domain.TSeaprice;
import com.ruoyi.quotation.mapper.TSeapriceMapper;
import com.ruoyi.reportManagement.domain.TWareHouseItemsExcel;
import com.ruoyi.reportManagement.domain.TWhgenleg;
import com.ruoyi.reportManagement.mapper.TWhgenlegMapper;
import com.ruoyi.shipping.domain.*;
import com.ruoyi.shipping.excel.DeriveInventoryExcel;
import com.ruoyi.shipping.excel.SingleVoyageByShipExcel;
import com.ruoyi.shipping.excel.TWarehousebillsCntritemsExcel;
import com.ruoyi.shipping.mapper.*;
import com.ruoyi.system.domain.SysCheckCode;
import com.ruoyi.system.domain.SysConfig;
import com.ruoyi.system.mapper.SysConfigMapper;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.mapper.SysDictDataMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.impl.SysConfigServiceImpl;
import com.ruoyi.warehouseBusiness.component.CalculationWarehouseService;
import com.ruoyi.warehouseBusiness.component.WarehouseBillsfilterService;
import com.ruoyi.warehouseBusiness.component.impl.QueryWhgenlegServiceImpl;
import com.ruoyi.warehouseBusiness.domain.*;
import com.ruoyi.warehouseBusiness.domain.dto.CalculateStorageFeesDTO;
import com.ruoyi.warehouseBusiness.domain.dto.WarehousebillsDTO;
import com.ruoyi.warehouseBusiness.domain.enums.FeesTypeEnum;
import com.ruoyi.warehouseBusiness.domain.enums.WarehouseActIdEnum;
import com.ruoyi.warehouseBusiness.domain.enums.WarehouseTypeEnum;
import com.ruoyi.warehouseBusiness.domain.vo.AppWarehouseInfoVO;
import com.ruoyi.warehouseBusiness.domain.vo.CalculateStorageFeesInfoVO;
import com.ruoyi.warehouseBusiness.domain.vo.StorageFeeCalculationResultVO;
import com.ruoyi.warehouseBusiness.domain.vo.WarehouseBillsVO;
import com.ruoyi.warehouseBusiness.excel.*;
import com.ruoyi.warehouseBusiness.mapper.*;
import com.ruoyi.warehouseBusiness.service.ITWarehouseBillsService;
import lombok.AllArgsConstructor;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import static com.ruoyi.common.utils.poi.Excel.filter;
import static java.util.stream.Collectors.toList;

/**
 * 详情主表Service业务层处理
 *
 * @author ruoyi
 * @date 2020-12-11
 */
@Service
@AllArgsConstructor
public class TWarehouseBillsServiceImpl implements ITWarehouseBillsService {

    @Autowired
    private TFeesMapper tFeesMapper;

    @Autowired
    private TCntrMapper tCntrMapper;

    @Autowired
    private TGoodsMapper tGoodsMapper;

    @Autowired
    private TCorpsMapper tCorpsMapper;

    @Autowired
    private TCustomerContactMapper tCustomerContactMapper;

    @Autowired
    private SysConfigMapper configMapper;

    @Autowired
    private TVoyageMapper tVoyageMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Autowired
    private BillnoDelMapper billnoDelMapper;

    @Autowired
    private TWhgenlegMapper tWhgenlegMapper;

    @Autowired
    private SysConfigMapper sysConfigMapper;

    @Autowired
    private TWarehouseMapper tWarehouseMapper;

    @Autowired
    private TSeapriceMapper tSeapriceMapper;

    @Autowired
    private AuditItemsMapper auditItemsMapper;

    @Autowired
    private TEnclosureMapper tEnclosureMapper;

    @Autowired
    private SysDictDataMapper sysDictDataMapper;

    @Autowired
    private QueryWhgenlegServiceImpl queryWhgenlegService;

    @Autowired
    private CalculationWarehouseService calculationWarehouseService;

    @Autowired
    private SysConfigServiceImpl sysConfigServiceImpl;

    @Autowired
    private AuditItemsServiceImpl auditItemsService;

    @Autowired
    private TWarehouseAreaMapper tWarehouseAreaMapper;

    @Autowired
    private TWarehouseServiceImpl warehouseServiceImpl;

    @Autowired
    private TWarehouseBillsMapper tWarehouseBillsMapper;

    @Autowired
    private BillnoSerialServiceImpl billnoSerialServiceImpl;

    @Autowired
    private TWarehousebillsLogMapper tWarehousebillsLogMapper;

    @Autowired
    private TWarehousebillsCntrMapper tWarehousebillsCntrMapper;

    @Autowired
    private TWarehousebillsfeesMapper tWarehousebillsfeesMapper;

    @Autowired
    private TWarehousebillsitemsMapper tWarehousebillsitemsMapper;

    @Autowired
    private TWarehouseAgreementServiceImpl tWarehouseAgreementService;

    @Autowired
    private WarehouseBillsfilterService warehouseBillsfilterService;

    @Autowired
    private TWarehousebillsCntritemsMapper tWarehousebillsCntritemsMapper;
    @Autowired
    private TTemporaryFileMapper tTemporaryFileMapper;
    @Autowired
    private TWarehousebillsLoggerMapper tWarehousebillsLoggerMapper;
    @Autowired
    private TWarehousebillsCntrLoggerMapper tWarehousebillsCntrLoggerMapper;
    @Autowired
    private TWarehousebillsCntritemsLoggerMapper tWarehousebillsCntritemsLoggerMapper;
    @Autowired
    private TWarehousebillsfeesLoggerMapper tWarehousebillsfeesLoggerMapper;
    @Autowired
    private TVesselMapper tVesselMapper;
    @Autowired
    private TCntrnoMapper tCntrnoMapper;
    @Autowired
    private TAddressMapper tAddressMapper;
    @Autowired
    private TCntrtrackingMapper tCntrtrackingMapper;
    @Autowired
    private TCtnpriceItemsMapper tCtnpriceItemsMapper;
    @Autowired
    private AuditItemsUsersMapper auditItemsUsersMapper;

    private static final Logger log = LoggerFactory.getLogger(AddressUtils.class);


    /**
     * 查询详情主表
     *
     * @param fId 详情主表ID
     * @return 详情主表
     */
    @Override
    public Map<String, Object> selectTWarehousebillsById(Long fId) {
        Map<String, Object> map = new HashMap<>();
        // 查询仓库主表数据
        TWarehouseBills tWarehousebills = tWarehouseBillsMapper.selectTWarehousebillsById(fId);
        // 客户表
        List<Long> corpsId = new ArrayList<>();
        // 用户表
        List<SysUser> sysUserList = new ArrayList<>();
        // 仓库表
        List<TWarehouse> warehouseList = new ArrayList<>();
        // 商品
        List<Long> goodsId = new ArrayList<>();
        // 费用
        List<Long> feesId = new ArrayList<>();
        // 车队
        List<Long> fleetId = new ArrayList<>();
        // 库区
        List<Long> warehouseAreaId = new ArrayList<>();
        if (!StringUtils.isNull(tWarehousebills)) {
            if (StringUtils.isNotNull(tWarehousebills.getfTocorpid())) {
                corpsId.add(tWarehousebills.getfTocorpid());
            }
            if (StringUtils.isNotNull(tWarehousebills.getfLabour())) {
                corpsId.add(tWarehousebills.getfLabour());
            }
            if (StringUtils.isNotNull(tWarehousebills.getfFleet())) {
                corpsId.add(tWarehousebills.getfFleet());
            }
            corpsId.add(tWarehousebills.getfCorpid());
            // 查询制单人
            SysUser logUser = sysUserMapper.selectUserByUserName(tWarehousebills.getCreateBy());
            if (StringUtils.isNotNull(logUser)) {
                SysDept sysDept = sysDeptMapper.selectDeptById(logUser.getDeptId());
                sysUserList.add(logUser);
                map.put("dept", sysDept);
            }
            SysUser sysUser = sysUserMapper.selectUserByUserName(tWarehousebills.getfStorekeeper());
            if (StringUtils.isNotNull(sysUser)) {
                sysUserList.add(sysUser);
            }
            // 查询仓库
            TWarehouse tWarehouse = tWarehouseMapper.selectTWarehouseById(tWarehousebills.getfWarehouseid());
            if (StringUtils.isNotNull(tWarehouse)) {
                warehouseList.add(tWarehouse);
            }
            //查询业务员
            if (tWarehousebills.getfSalesmanId() != null) {
                SysUser user = sysUserMapper.selectUserById(tWarehousebills.getfSalesmanId());
                map.put("fSalesman", user);
            }
            // 查询经营单位
            corpsId.add(tWarehousebills.getfSbu());
            map.put("warehousebills", tWarehousebills);
        }
        // 查询箱型 箱量表
        TWarehousebillsCntr cntr = new TWarehousebillsCntr();
        cntr.setfPid(fId);
        map.put("tCntrList", tWarehousebillsCntrMapper.selectTWarehousebillsCntrList(cntr));
        // 查询仓库明细从表数据
        TWarehousebillsitems tWarehousebillsitems = new TWarehousebillsitems();
        tWarehousebillsitems.setfPid(fId);
        List<Map<String, Object>> mapList = tWarehousebillsitemsMapper.selectGoodsTransferitemsList(tWarehousebillsitems);
        if (StringUtils.isNotEmpty(mapList)) {
            for (Map<String, Object> wb : mapList) {
                /*TWhgenleg tWhgenleg = new TWhgenleg();
                tWhgenleg.setfCorpid(tWarehousebills.getfCorpid());
                if (StringUtils.isNotNull(wb.get("fGoodsid"))) {
                    tWhgenleg.setfGoodsid(((Integer) wb.get("fGoodsid")).longValue());
                }
                if (StringUtils.isNotNull(wb.get("fWarehouselocid"))) {
                    tWhgenleg.setfWarehouseLocationid(((Integer) wb.get("fWarehouselocid")).longValue());
                }
                tWhgenleg.setfTrademodeid(tWarehousebills.getfTrademodeid());
                tWhgenleg.setfMblno(tWarehousebills.getfMblno());
                TWhgenleg whgenleg = tWhgenlegMapper.selectTWhgenleg(tWhgenleg);
                if (StringUtils.isNotNull(whgenleg)) {
                    wb.put("fQtyblc", whgenleg.getfQtyblc());
                }*/
                if (StringUtils.isNotNull(wb.get("fGoodsid"))) {
                    Integer fGoodsid = (Integer) wb.get("fGoodsid");
                    goodsId.add(fGoodsid.longValue());
                }
                if (StringUtils.isNotNull(wb.get("fFleet"))) {
                    Integer fFleetid = (Integer) wb.get("fFleet");
                    fleetId.add(fFleetid.longValue());
                }
                if (StringUtils.isNotNull(wb.get("fWarehouselocid"))) {
                    Long fWarehouselocid = Long.valueOf(String.valueOf(wb.get("fWarehouselocid")));
                    if (wb.get("fTransferWarehouselocid") != null) {
                        Long fTransferWarehouselocid = Long.valueOf(String.valueOf(wb.get("fTransferWarehouselocid")));
                        warehouseAreaId.add(fTransferWarehouselocid);
                    }
                    warehouseAreaId.add(fWarehouselocid);
                }
            }
            map.put("warehouseBillsItem", mapList);
        }
        // 查询仓库费用明细表数据
        TWarehousebillsfees tWarehousebillsfees = new TWarehousebillsfees();
        tWarehousebillsfees.setfPid(fId);
        List<TWarehousebillsfees> warehousebillsfeesDr = new ArrayList<>();
        List<TWarehousebillsfees> warehousebillsfeesCr = new ArrayList<>();
        List<TWarehousebillsfees> warehousebillsfees = tWarehousebillsfeesMapper.selectTWarehousebillsfeesList(tWarehousebillsfees);
        if (StringUtils.isNotEmpty(warehousebillsfees)) {
            for (TWarehousebillsfees fees : warehousebillsfees) {
                if ("C".equals(fees.getfDc())) {
                    warehousebillsfeesCr.add(fees);
                } else {
                    warehousebillsfeesDr.add(fees);
                }
                corpsId.add(fees.getfCorpid());
                feesId.add(fees.getfFeeid());
            }
        }
        // 查询附件表数据
        TEnclosure enclosure = new TEnclosure();
        enclosure.setfPid(fId);
        List<TEnclosure> enclosures = tEnclosureMapper.selectTEnclosureList(enclosure);
        if (StringUtils.isNotEmpty(enclosures)) {
            map.put("enclosures", enclosures);
        }
        List<TCorps> corpsList = new ArrayList<>();
        List<Long> corpsIdList = StringUtils.integerDeduplication(corpsId);
        for (Long corpId : corpsIdList) {
            TCorps corps = tCorpsMapper.selectTCorpsById(corpId);
            if (StringUtils.isNotNull(corps)) {
                corpsList.add(corps);
            }
        }
        List<TWarehouseArea> warehouseAreaList = new ArrayList<>();
        /*List<Long> warehouseAreaIdList = StringUtils.integerDeduplication(warehouseAreaId);
        for (Long warehouseArea : warehouseAreaIdList) {
            TWarehouseArea tWarehouseArea = tWarehouseAreaMapper.selectTWarehouseAreaById(warehouseArea);
            if (StringUtils.isNotNull(tWarehouseArea)) {
                warehouseAreaList.add(tWarehouseArea);
            }
        }*/
        List<TGoods> goodsList = new ArrayList<>();
        List<Long> goodsIdList = StringUtils.integerDeduplication(goodsId);
        for (Long goods : goodsIdList) {
            TGoods tGoods = tGoodsMapper.selectTGoodsById(goods);
            if (StringUtils.isNotNull(tGoods)) {
                goodsList.add(tGoods);
            }
        }
        List<TCorps> fleetList = new ArrayList<>();
        List<Long> fleetIdList = StringUtils.integerDeduplication(fleetId);
        for (Long goods : fleetIdList) {
            TCorps fleet = tCorpsMapper.selectTCorpsById(goods);
            if (StringUtils.isNotNull(fleet)) {
                fleetList.add(fleet);
            }
        }
        List<TFees> feesList = new ArrayList<>();
        List<Long> longList = StringUtils.integerDeduplication(feesId);
        for (Long fees : longList) {
            TFees tFees = tFeesMapper.selectTFeesById(fees);
            if (StringUtils.isNotNull(tFees)) {
                feesList.add(tFees);
            }
        }
        map.put("corps", corpsList);
        map.put("goodsList", goodsList);
        map.put("feesList", feesList);
        map.put("fleetList", fleetList);
        map.put("sysUser", sysUserList);
        map.put("warehouse", warehouseList);
        map.put("warehouseAreas", warehouseAreaList);
        map.put("warehousebillsfeesDr", warehousebillsfeesDr);
        map.put("warehousebillsfeesCr", warehousebillsfeesCr);
        map.put("dept", sysDeptMapper.selectDeptById(tWarehousebills.getfDeptid()));
        return map;
    }

    @Override
    public AjaxResult selectTWarehousebills(Long fId) {
        TWarehouseBills warehouseBills = tWarehouseBillsMapper.selectTWarehousebillsById(fId);
        TWarehousebillsCntr tWarehousebillsCntr = new TWarehousebillsCntr();
        tWarehousebillsCntr.setfPid(fId);
        List<TWarehousebillsCntr> warehousebillsCntrs = tWarehousebillsCntrMapper.selectTWarehousebillsCntrList(tWarehousebillsCntr);
        TWarehousebillsCntritems tWarehousebillsCntritems = new TWarehousebillsCntritems();
        tWarehousebillsCntritems.setfPid(fId);
        List<TWarehousebillsCntritems> warehousebillsCntritems = tWarehousebillsCntritemsMapper.selectTWarehousebillsCntritemsList(tWarehousebillsCntritems);
        Map<String, Object> map = new HashMap<>();
        map.put("warehouseBills", warehouseBills);
        map.put("warehousebillsCntrs", warehousebillsCntrs);
        map.put("warehousebillsCntritems", warehousebillsCntritems);
        return AjaxResult.success("成功", map);
    }

    /**
     * 查询详情主表列表
     *
     * @param tWarehousebills 详情主表
     * @return 详情主表
     */
    @Override
    public List<Map<String, Object>> selectWarehouseBusinessList(TWarehouseBills tWarehousebills) {
        if (tWarehousebills.getfBilltype().equals(WarehouseTypeEnum.JSCCF.getType())) {
            List<Map<String, Object>> mapList = tWarehouseBillsMapper.selecStorageFeeList(tWarehousebills);
            if (CollectionUtils.isNotEmpty(mapList)) {
                mapList.forEach(li -> {
                    li.put("fBillstatus", WarehouseTypeEnum.fromTypeAndBusinessType(li.get("fBillstatus").toString(), "storageStatus").getName());
                });
            }
            return mapList;
        } else if (tWarehousebills.getfBilltype().equals(WarehouseTypeEnum.HQZY.getType())) {
            return tWarehouseBillsMapper.selectWarehouseBusinessList1(tWarehousebills);
        } else {
            List<Map<String, Object>> billsList = tWarehouseBillsMapper.selectWarehouseBusinessList(tWarehousebills);

            for (Map<String, Object> billsMap : billsList) {
                // 查询箱型、箱量表
                TWarehousebillsCntr cntr = new TWarehousebillsCntr();
                cntr.setfPid(Long.parseLong(billsMap.get("fId").toString()));
                List<TWarehousebillsCntr> cntrList = tWarehousebillsCntrMapper.selectTWarehousebillsCntrList(cntr);

                // 创建map统计箱型箱量
                Map<String, Long> countMap = new HashMap<>();
                for (TWarehousebillsCntr temp : cntrList) {
                    String cntrName = temp.getCntrName();
                    Long fCntrcount = temp.getfCntrcount();
                    if (StringUtils.isNotNull(cntrName) && StringUtils.isNotNull(fCntrcount)) {
                        if (countMap.containsKey(cntrName)) {
                            countMap.put(cntrName, countMap.get(cntrName) + fCntrcount);
                        } else {
                            countMap.put(cntrName, fCntrcount);
                        }
                    }
                }

                // 组装返回
                String fCntval = "";
                if (countMap.size() > 0) {
                    StringBuilder sb = new StringBuilder();
                    for (String key : countMap.keySet()) {
                        sb.append(key).append("×").append(countMap.get(key)).append("，");
                    }
                    fCntval = sb.deleteCharAt(sb.length() - 1).toString();
                }
                billsMap.put("fCntval", fCntval);
            }

            return billsList;
        }
    }

    /**
     * 查询导出所需主表列表
     *
     * @param tWarehousebills 详情主表
     * @return 详情主表
     */
    @Override
    public List<TWarehouseBills> selectTWarehousebillsList(TWarehouseBills tWarehousebills) {
        return tWarehouseBillsMapper.selectTWarehousebillsList(tWarehousebills);
    }

    /**
     * 根据条件查询总账是否存在
     *
     * @param warehouseBills      仓库主表
     * @param warehousebillsitems 仓库明细表
     * @param ifCntrno            是否判断箱号
     * @return 库存总账
     */
    public TWhgenleg queryTWhgenleg(TWarehouseBills warehouseBills, TWarehousebillsitems warehousebillsitems, String ifCntrno) {
        // 货转时如果调出操作是10-1且计费日期10-1那么调入的时候也要判断计费日期10-1业务日期10-1，调入之后吧id赋值给费用明细新加字段中
        // 调拨同理
        TWhgenleg tWhgenleg = new TWhgenleg();
        // 客户
        tWhgenleg.setfCorpid(warehouseBills.getfCorpid());
        // 提单号
        if (WarehouseTypeEnum.HQZY.getType().equals(warehouseBills.getfBilltype()) ||
                WarehouseTypeEnum.CKDB.getType().equals(warehouseBills.getfBilltype()) ||
                WarehouseTypeEnum.HWTG.getType().equals(warehouseBills.getfBilltype()) ||
                WarehouseTypeEnum.SJCK.getType().equals(warehouseBills.getfBilltype())) {
            tWhgenleg.setfMblno(warehousebillsitems.getfMblno());
        } else {
            tWhgenleg.setfMblno(warehouseBills.getfMblno());
        }
        // 业务日期
        if (WarehouseTypeEnum.CKDB.getType().equals(warehouseBills.getfBilltype()) ||
                WarehouseTypeEnum.HWTG.getType().equals(warehouseBills.getfBilltype())) {
            // 转换日期最小值
            tWhgenleg.setfBsdate(DateUtils.dateConversionMin(warehousebillsitems.getfBsdate()));
        } else {
            tWhgenleg.setfBsdate(warehousebillsitems.getfOriginalbilldate());
        }
        // 业务类型
        tWhgenleg.setfBusinessType(warehousebillsitems.getfBusinessType());
        // 业务类型详情
        tWhgenleg.setfMarks(warehousebillsitems.getfMarks());
        if ("1".equals(ifCntrno)) {
            tWhgenleg.setfCntrno(warehousebillsitems.getfCntrno());
        }
        // 库区
        tWhgenleg.setfWarehouseLocationid(warehousebillsitems.getfWarehouselocid());
        // 货物品名
        tWhgenleg.setfGoodsid(warehousebillsitems.getfGoodsid());
        // 贸易方式
        tWhgenleg.setfTrademodeid(warehouseBills.getfTrademodeid());
        return tWhgenlegMapper.selectTWhgenleg(tWhgenleg);
    }

    /**
     * 新增库存总账
     *
     * @param warehouseBills      仓库主表
     * @param warehousebillsitems 仓库明细表
     * @return 结果
     */
    public Long instalTWhgenleg(TWarehouseBills warehouseBills, TWarehousebillsitems warehousebillsitems) {
        TWhgenleg tWhgenleg = new TWhgenleg();
        if (WarehouseTypeEnum.SJRK.getType().equals(warehouseBills.getfBilltype())) {
            tWhgenleg.setfOriginalbilldate(warehousebillsitems.getfBsdate());
            if (StringUtils.isNotEmpty(warehouseBills.getfCustomno())) {
                tWhgenleg.setfCustomno(warehouseBills.getfCustomno());
            }
            if (StringUtils.isNotEmpty(warehouseBills.getRemark())) {
                tWhgenleg.setRemark(warehouseBills.getRemark());
            }
        }
        if (WarehouseTypeEnum.HQZY.getType().equals(warehouseBills.getfBilltype()) || WarehouseTypeEnum.CKDB.getType().equals(warehouseBills.getfBilltype()) ||
                WarehouseTypeEnum.HWTG.getType().equals(warehouseBills.getfBilltype())) {
            tWhgenleg.setfOriginalbilldate(warehousebillsitems.getfOriginalbilldate());
            if (WarehouseTypeEnum.CKDB.getType().equals(warehouseBills.getfBilltype()) || WarehouseTypeEnum.HWTG.getType().equals(warehouseBills.getfBilltype())) {
                tWhgenleg.setfCorpid(warehouseBills.getfCorpid());
            } else {
                // 客户
                tWhgenleg.setfCorpid(warehouseBills.getfTocorpid());
            }
            // 提单号
            tWhgenleg.setfMblno(warehousebillsitems.getfMblno());
            // 原始单号
            tWhgenleg.setfOriginalbillno(warehousebillsitems.getfMblno());
        } else {
            // 客户
            tWhgenleg.setfCorpid(warehouseBills.getfCorpid());
            // 提单号
            tWhgenleg.setfMblno(warehouseBills.getfMblno());
            // 原始单号
            tWhgenleg.setfOriginalbillno(warehouseBills.getfMblno());
        }
        // 库内箱号
        if (StringUtils.isNotEmpty(warehousebillsitems.getfLocalcntrno())) {
            tWhgenleg.setfLocalcntrno(warehousebillsitems.getfLocalcntrno());
        }
        if (WarehouseTypeEnum.HQZY.getType().equals(warehouseBills.getfBilltype()) || WarehouseTypeEnum.CKDB.getType().equals(warehouseBills.getfBilltype()) ||
                WarehouseTypeEnum.HWTG.getType().equals(warehouseBills.getfBilltype())) {
            // 仓储计费日期
            tWhgenleg.setfChargedate(warehousebillsitems.getfBsdate());
        } else {
            // 仓储计费日期
            tWhgenleg.setfChargedate(warehousebillsitems.getfChargedate());
        }
        // 业务日期
        tWhgenleg.setfBsdate(warehousebillsitems.getfBsdate());
        // 明细类型
        tWhgenleg.setfBusinessType(warehousebillsitems.getfBusinessType());
        // 仓库
        tWhgenleg.setfWarehouseid(warehouseBills.getfWarehouseid());
        // 库区
        if (WarehouseTypeEnum.CKDB.getType().equals(warehouseBills.getfBilltype()) || WarehouseTypeEnum.HWTG.getType().equals(warehouseBills.getfBilltype())) {
            tWhgenleg.setfWarehouseLocationid(warehousebillsitems.getfTransferWarehouselocid());
        } else {
            tWhgenleg.setfWarehouseLocationid(warehousebillsitems.getfWarehouselocid());
        }
        // 货物品名
        tWhgenleg.setfGoodsid(warehousebillsitems.getfGoodsid());
        // 计费方式
        tWhgenleg.setfBillingway(warehousebillsitems.getfBillingway());
        // 贸易方式
        if (WarehouseTypeEnum.HWTG.getType().equals(warehouseBills.getfBilltype())) {
            tWhgenleg.setfTrademodeid(warehouseBills.getfNewTrademodeid());
        } else {
            tWhgenleg.setfTrademodeid(warehouseBills.getfTrademodeid());
        }
        // 入库数
        tWhgenleg.setfQtyd(warehousebillsitems.getfQty());
        // 入库尺码
        tWhgenleg.setfVolumnd(warehousebillsitems.getfVolumn());
        // 唛头
        tWhgenleg.setfMarks(warehousebillsitems.getfMarks());
        // 入库毛重
        tWhgenleg.setfGrossweightd(warehousebillsitems.getfGrossweight());
        // 入库净重
        tWhgenleg.setfNetweightd(warehousebillsitems.getfNetweight());
        // 入库箱号
        tWhgenleg.setfCntrno(warehousebillsitems.getfCntrno());
        // 创建人
        tWhgenleg.setCreateBy(SecurityUtils.getUsername());
        // 创建人
        tWhgenleg.setCreateTime(new Date());
        // 状态
        tWhgenleg.setfStatus("T");
        // 结余件数
        tWhgenleg.setfQtyblc(warehousebillsitems.getfQty());
        tWhgenlegMapper.insertTWhgenleg(tWhgenleg);
        return tWhgenleg.getfId();
    }

    @Transactional
    public int updateTWhgenlegData(TWarehousebillsitems warehousebillsitems, long whgenlegId, String billtype) {
        Map<String, Object> map = new HashMap<>();
        map.put("whgenlegId", whgenlegId);
        map.put("billType", billtype);
        map.put("warehousebillsitems", warehousebillsitems);
        return tWhgenlegMapper.updateTWhgenlegData(map);
    }

    /**
     * 仓库暂存接口
     *
     * @param tWarehouseBills       仓库主表
     * @param tWarehousebillsfeesCr 仓库费付款用明细表
     * @param tWarehousebillsfeesDr 仓库费收
     *                              款用明细表
     * @param tWarehousebillsitems  仓库货物明细表
     * @param loginUser             当前登陆人
     * @param billsType             判断标识
     * @return 结果
     */
    @Override
    @Transactional
    public AjaxResult insertTWarehousebills(String tWarehouseBills, String tWarehousebillsfeesCr, String tWarehousebillsfeesDr
            , String tWarehousebillsitems, String tEnclosure, LoginUser loginUser, String tCntr, String billsType) {
        Long fPid = null;
        Map<String, Object> map = new HashMap<>();
        TWarehouseBills warehouseBills = JSONArray.parseObject(tWarehouseBills, TWarehouseBills.class);
        Long timestamp = DateUtils.getTimestamp(new Date());
        warehouseBills.setfDateChanged(timestamp.toString() + (int) (Math.random() * 900) + 100);
        TWarehousebillsitems itemInFo = tWarehousebillsitemsMapper.selectItemQtyByFPid(warehouseBills.getfId());
        warehouseBills.setfQty(itemInFo.getfQty());
        warehouseBills.setfNetweight(itemInFo.getfNetweight());
        warehouseBills.setfGrossweight(itemInFo.getfGrossweight());
        if (StringUtils.isNull(warehouseBills.getfId())) {
            // 如果是新数据
            warehouseBills.setfBillstatus(2L);
            warehouseBills.setCreateBy(loginUser.getUser().getUserName());
            warehouseBills.setfBilltype(billsType);
            warehouseBills.setfBsdeptid(loginUser.getUser().getDeptId());
            warehouseBills.setfDeptid(loginUser.getUser().getDeptId());
            // 业务编码
            String billNo = billnoSerialServiceImpl.getBillNo(billsType, warehouseBills.getfBsdate());
            warehouseBills.setfBillno(billNo);
            if ("SJRK".equals(billsType) || WarehouseTypeEnum.HQZY.getType().equals(billsType)) {
                // 存货编码
                Date time = new Date();
                String bscorpno = billnoSerialServiceImpl.getCorpNo(warehouseBills.getfCorpid(), time);
                warehouseBills.setfBscorpno(bscorpno);
            } else {
                warehouseBills.setfChargedate(warehouseBills.getfBsdate());
            }
            tWarehouseBillsMapper.insertTWarehousebills(warehouseBills);
            fPid = warehouseBills.getfId();
        } else {
            fPid = warehouseBills.getfId();
            if (!"SJRK".equals(billsType) && !WarehouseTypeEnum.HQZY.getType().equals(billsType)) {
                warehouseBills.setfChargedate(warehouseBills.getfBsdate());
            }
            warehouseBills.setUpdateBy(loginUser.getUser().getUserName());
            warehouseBills.setUpdateTime(new Date());
            tWarehousebillsCntrMapper.deleteTWarehousebillsCntrfPid(fPid);
            tWarehouseBillsMapper.updateTWarehousebills(warehouseBills);
            tWarehousebillsfeesMapper.deleteByFPid(fPid);
            tEnclosureMapper.deleteByFPid(fPid);
            // 删除  从表中 未打印账单的数据
            deleteBillsitems(fPid, tWarehousebillsitems);
        }
        // 库存明细添加
        if (StringUtils.isNotNull(tWarehousebillsitems) && !"[]".equals(tWarehousebillsitems)) {
            JSONArray warehouseJSON = JSONArray.parseArray(tWarehousebillsitems);
            List<TWarehousebillsitems> warehousebillsitemsList = JSONObject.parseArray(warehouseJSON.toJSONString(), TWarehousebillsitems.class);
            Date mixDate = new Date();
            if (CollectionUtils.isNotEmpty(warehousebillsitemsList)) {
                Date minDate = warehousebillsitemsList.get(0).getfBsdate();
                for (int i = 0; i < warehousebillsitemsList.size(); i++) {
                    Date date = warehousebillsitemsList.get(i).getfBsdate();
                    if (minDate.after(date)) {
                        minDate = date;
                    }
                }
                mixDate = minDate;
            }
            for (TWarehousebillsitems wbItem : warehousebillsitemsList) {
                boolean warehouseStatus = "SJRK".equals(billsType) || "SJCK".equals(billsType) || WarehouseTypeEnum.CKDB.getType().equals(billsType) ||
                        WarehouseTypeEnum.HWTG.getType().equals(billsType) || "CDZZ".equals(billsType);
                // 仓储计费日期
                wbItem.setfBilltype(billsType);
                if ("SJRK".equals(billsType) && warehouseBills.getfId() != null && "0".equals(warehouseBills.getfChargetype())) {
                    if (!this.getFchargedate(fPid, wbItem.getfBsdate())) {
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return AjaxResult.error("入库日期不能小于最小仓储费计算日期");
                    }
                }
                if ("SJRK".equals(billsType)) {
                    if ("1".equals(warehouseBills.getfChargetype())) {
                        wbItem.setfChargedate(wbItem.getfBsdate());
                    } else if ("0".equals(warehouseBills.getfChargetype())) {
                        Date fchargedate = tWarehousebillsitemsMapper.getFchargedate(fPid);
                        if (fchargedate != null) {
                            wbItem.setfChargedate(fchargedate);
                        } else {
                            wbItem.setfChargedate(mixDate);
                        }
                    }
                    wbItem.setfBillingway(warehouseBills.getfBillingway());
                    wbItem.setfMblno(warehouseBills.getfMblno());// 入库更新库存前执行update更新明细的提单号等于主表的提单号
                }
                if (null != wbItem.getfId()) {
                    wbItem.setUpdateTime(wbItem.getfBsdate());
                    wbItem.setUpdateBy(loginUser.getUser().getUserName());
                    tWarehousebillsitemsMapper.updateTWarehousebillsitems(wbItem);
                } else {
                    // 添加主表 业务单号
                    wbItem.setfBillno(warehouseBills.getfBillno());
                    if (!"CDZZ".equals(billsType)) {
                        if (!warehouseStatus) {
                            wbItem.setfBillstatus(1L);
                        } else {
                            wbItem.setfBillstatus(10L);
                        }
                    }
                    wbItem.setfPid(fPid);
                    wbItem.setCreateBy(loginUser.getUser().getUserName());
                    wbItem.setCreateTime(new Date());
                    tWarehousebillsitemsMapper.insertTWarehousebillsitems(wbItem);
                    if (!warehouseStatus) {
                        // 添加状态log
                        insertTWarehousebillsLog(wbItem, 10L);
                    }
                }
            }
        }
        //  附件添加
        if (StringUtils.isNotNull(tEnclosure) && !"[]".equals(tEnclosure)) {
            JSONArray jsonDrArray = JSONArray.parseArray(tEnclosure);
            List<TEnclosure> tEnclosureList = JSONObject.parseArray(jsonDrArray.toJSONString(), TEnclosure.class);
            for (TEnclosure enclosure : tEnclosureList) {
                enclosure.setfPid(fPid);
                enclosure.setCreateBy(loginUser.getUser().getUserName());
                enclosure.setCreateTime(new Date());
                tEnclosureMapper.insertTEnclosure(enclosure);
            }
        }
        //  箱型数据
        if (StringUtils.isNotNull(tCntr) && !"[]".equals(tCntr)) {
            JSONArray jsonDrArray = JSONArray.parseArray(tCntr);
            List<TWarehousebillsCntr> tWarehousebillsCntrs = JSONObject.parseArray(jsonDrArray.toJSONString(), TWarehousebillsCntr.class);
            int line = 0;
            for (TWarehousebillsCntr cntr : tWarehousebillsCntrs) {
                line++;
                if (StringUtils.isNull(cntr.getfCntrid()) || StringUtils.isNull(cntr.getfCntrcount()) || cntr.getfCntrcount() == 0) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error("箱型数据第" + line + "行数据缺少必填数据");
                }
                cntr.setfPid(fPid);
                cntr.setfGoodsid(0L);
                cntr.setfPackageid("0");
                cntr.setfCntrweight(new BigDecimal(0));
                cntr.setCreateBy(loginUser.getUser().getUserName());
                cntr.setCreateTime(new Date());
                tWarehousebillsCntrMapper.insertTWarehousebillsCntr(cntr);
            }
        }
        // 收款明细添加
        if (StringUtils.isNotNull(tWarehousebillsfeesDr) && !"[]".equals(tWarehousebillsfeesDr)) {
            JSONArray jsonDrArray = JSONArray.parseArray(tWarehousebillsfeesDr);
            List<TWarehousebillsfees> warehousebillsfeesDrList = JSONObject.parseArray(jsonDrArray.toJSONString(), TWarehousebillsfees.class);
            for (TWarehousebillsfees wbDr : warehousebillsfeesDrList) {
                // 检验  数量*单价=金额
                wbDr.setfPid(fPid);
                wbDr.setfDc("D");
                wbDr.setfBilltype(billsType);
                wbDr.setCreateTime(new Date());
                wbDr.setSrcBillNo(warehouseBills.getfBillno());
                wbDr.setfChargedate(warehouseBills.getfChargedate());
                wbDr.setfBillingDeadline(warehouseBills.getfChargedate());
                wbDr.setCreateBy(loginUser.getUser().getUserName());
                if (warehouseBills.getfBsdate() != null && !"".equals(warehouseBills.getfBsdate())) {
                    wbDr.setfBsdate(warehouseBills.getfBsdate());
                }
                tWarehousebillsfeesMapper.insertTWarehousebillsfees(wbDr);
            }
        }
        // 付款明细添加
        if (StringUtils.isNotNull(tWarehousebillsfeesCr) && !"[]".equals(tWarehousebillsfeesCr)) {
            JSONArray jsonCrArray = JSONArray.parseArray(tWarehousebillsfeesCr);
            List<TWarehousebillsfees> warehousebillsfeesCrList = JSONObject.parseArray(jsonCrArray.toJSONString(), TWarehousebillsfees.class);
            for (TWarehousebillsfees wbCr : warehousebillsfeesCrList) {
                wbCr.setfPid(fPid);
                wbCr.setfDc("C");
                wbCr.setfBilltype(billsType);
                wbCr.setCreateTime(new Date());
                wbCr.setSrcBillNo(warehouseBills.getfBillno());
                wbCr.setCreateBy(loginUser.getUser().getUserName());
                wbCr.setfChargedate(warehouseBills.getfChargedate());
                wbCr.setfBillingDeadline(warehouseBills.getfChargedate());
                if (warehouseBills.getfBsdate() != null && !warehouseBills.getfBsdate().equals("")) {
                    wbCr.setfBsdate(warehouseBills.getfBsdate());
                }
                tWarehousebillsfeesMapper.insertTWarehousebillsfees(wbCr);
            }
        }
        //查询删除的仓储费收费信息
        List<Long> longs = tWarehousebillsfeesMapper.selectTWarehousebillsfeesSrcId(fPid);
        if (CollectionUtils.isNotEmpty(longs)) {
            tWarehousebillsitemsMapper.updatefStorageFeeDeadline(fPid, longs);
        } else {
            tWarehousebillsitemsMapper.updatefStorageFeeDeadlinefPid(fPid);
        }
        calculationWarehouseService.calculationBillStatus(warehouseBills);
        tWarehouseBillsMapper.updateTWarehousebills(warehouseBills);
        TWarehousebillsitems warehousebillsitems = new TWarehousebillsitems();
        warehousebillsitems.setfPid(fPid);
        map.put("warehouseBills", tWarehouseBillsMapper.selectTWarehousebillsById(warehouseBills.getfId()));
        map.put("warehousebillsitems", tWarehousebillsitemsMapper.selectGoodsTransferitemsList(warehousebillsitems));
        return AjaxResult.success("成功", map);
    }

    @Override
    public int insertTWarehousebills(TWarehouseBills tWarehousebills) {
        return tWarehouseBillsMapper.insertTWarehousebills(tWarehousebills);
    }

    /**
     * 凯和订单计划暂存
     *
     * @param tWarehousebills     主表信息
     * @param tWarehousebillsCntr 从表信息
     * @param billsType
     * @param loginUser
     * @return
     */
    @Override
    @Transactional
    public AjaxResult TSPlantMessage(String tWarehousebills, String tWarehousebillsCntr,
                                     String billsType, LoginUser loginUser) {
        Map<String, Object> map = new HashMap<>();
        TWarehouseBills warehouseBills = JSONArray.parseObject(tWarehousebills, TWarehouseBills.class);
        JSONArray jsonCrArray = JSONArray.parseArray(tWarehousebillsCntr);
        List<TWarehousebillsCntr> tWarehousebillsCntrs = JSONObject.parseArray(jsonCrArray.toJSONString(), TWarehousebillsCntr.class);
        if (warehouseBills.getfId() == null) {
            String billNo = billnoSerialServiceImpl.getBillNo("SE", warehouseBills.getfBsdate());
            warehouseBills.setfBillno(billNo);
            warehouseBills.setCreateTime(DateUtils.getNowDate());
            warehouseBills.setCreateBy(SecurityUtils.getUsername());
            warehouseBills.setfBilltype(billsType);
            warehouseBills.setfTypeid(1);
            warehouseBills.setfBillstatus(2L);
            warehouseBills.setfDeptid(loginUser.getUser().getDeptId());
            warehouseBills.setfBsdeptid(loginUser.getUser().getDeptId());
            int i = tWarehouseBillsMapper.insertTWarehousebills(warehouseBills);
            if (CollectionUtils.isNotEmpty(tWarehousebillsCntrs)) {
                for (TWarehousebillsCntr warehousebillsCntr : tWarehousebillsCntrs) {
                    warehousebillsCntr.setfPid(warehouseBills.getfId());
                    warehousebillsCntr.setCreateTime(DateUtils.getNowDate());
                    warehousebillsCntr.setCreateBy(SecurityUtils.getUsername());
                    int cntr = tWarehousebillsCntrMapper.insertTWarehousebillsCntr(warehousebillsCntr);
                }
            }
        } else {
            TWarehouseBills tWarehouseBills = tWarehouseBillsMapper.selectTWarehousebillsById(warehouseBills.getfId());
            if (!"2".equals(tWarehouseBills.getfBillstatus()) || !"3".equals(tWarehouseBills.getfBillstatus())) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error("当前数据不允许暂存");
            }
            warehouseBills.setUpdateTime(DateUtils.getNowDate());
            warehouseBills.setUpdateBy(SecurityUtils.getUsername());
            tWarehouseBillsMapper.updateTWarehousebills(warehouseBills);
            tWarehousebillsCntrMapper.deleteTWarehousebillsCntrfPid(warehouseBills.getfId());
            if (CollectionUtils.isNotEmpty(tWarehousebillsCntrs)) {
                for (TWarehousebillsCntr warehousebillsCntr : tWarehousebillsCntrs) {
                    warehousebillsCntr.setfPid(warehouseBills.getfId());
                    warehousebillsCntr.setCreateTime(DateUtils.getNowDate());
                    warehousebillsCntr.setCreateBy(SecurityUtils.getUsername());
                    tWarehousebillsCntrMapper.insertTWarehousebillsCntr(warehousebillsCntr);
                }
            }
        }
        map.put("warehouseBills", warehouseBills);
        map.put("tWarehousebillsCntrs", tWarehousebillsCntrs);
        return AjaxResult.success("msg", map);
    }

    /**
     * 凯和订单计划提交
     *
     * @param tWarehousebills     主表信息
     * @param tWarehousebillsCntr 从表信息
     * @param billsType
     * @param loginUser
     * @return
     */
    @Override
    @Transactional
    public AjaxResult submitPlantMessage(String tWarehousebills, String tWarehousebillsCntr,
                                         String billsType, LoginUser loginUser) {
        boolean isApprove = false;//是否开启审批流
        String key = "";//键
        long actId = 0L;//活动id
        Long fPid = null;
        Long billStatus = null;
        Map<String, Object> map = new HashMap<>();
        if ("KHDD".equals(billsType)) {
            actId = 410L;
            key = "khwarehouse.warehousebills.ApprovalFlow";
        }
        SysConfig sysConfig = sysConfigMapper.checkConfigKeyUnique(key);
        if (StringUtils.isNull(sysConfig)) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("系统参数异常，未找到开启审批流参数");
        }
        if ("0".equals(sysConfig.getConfigValue())) {
            isApprove = true;
        }
        if (isApprove) {
            billStatus = 4L;
        } else {
            billStatus = 6L;
        }
        TWarehouseBills warehouseBills = JSONArray.parseObject(tWarehousebills, TWarehouseBills.class);
        JSONArray jsonCrArray = JSONArray.parseArray(tWarehousebillsCntr);
        List<TWarehousebillsCntr> tWarehousebillsCntrs = JSONObject.parseArray(jsonCrArray.toJSONString(), TWarehousebillsCntr.class);
        if (warehouseBills.getfVslid() == null) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("船名不能为空");
        }
        if (warehouseBills.getfVoyid() == null) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("航次不能为空");
        }
        //获取客户单位
        Long clientFid = tCorpsMapper.getClientFid(loginUser.getUser().getPhonenumber());
        if (warehouseBills.getfId() == null) {
            String billNo = billnoSerialServiceImpl.getBillNo("SE", DateUtils.getNowDate());
            warehouseBills.setfBillno(billNo);
            warehouseBills.setCreateTime(DateUtils.getNowDate());
            warehouseBills.setCreateBy(SecurityUtils.getUsername());
            warehouseBills.setfBilltype(billsType);
            warehouseBills.setfTypeid(1);
            warehouseBills.setfDeptid(loginUser.getUser().getDeptId());
            warehouseBills.setfBsdeptid(loginUser.getUser().getDeptId());
            warehouseBills.setfCorpid(clientFid);
            warehouseBills.setfContacts(loginUser.getUser().getUserName());
            warehouseBills.setfTel(loginUser.getUser().getPhonenumber());
            warehouseBills.setfBillstatus(billStatus);
            warehouseBills.setfTimes(1L);
            int i = tWarehouseBillsMapper.insertTWarehousebills(warehouseBills);
            if (CollectionUtils.isNotEmpty(tWarehousebillsCntrs)) {
                for (TWarehousebillsCntr warehousebillsCntr : tWarehousebillsCntrs) {
                    warehousebillsCntr.setfPid(warehouseBills.getfId());
                    warehousebillsCntr.setCreateTime(DateUtils.getNowDate());
                    warehousebillsCntr.setCreateBy(SecurityUtils.getUsername());
                    int cntr = tWarehousebillsCntrMapper.insertTWarehousebillsCntr(warehousebillsCntr);
                }
            }
            fPid = warehouseBills.getfId();
        } else {
            TWarehouseBills tWarehouseBills = tWarehouseBillsMapper.selectTWarehousebillsById(warehouseBills.getfId());
            if (tWarehouseBills.getfBillstatus() == 2L
                    || tWarehouseBills.getfBillstatus() == 3L) {
            } else {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error("当前数据不允许提交");
            }
            fPid = warehouseBills.getfId();
            warehouseBills.setUpdateTime(DateUtils.getNowDate());
            warehouseBills.setUpdateBy(SecurityUtils.getUsername());
            warehouseBills.setfBillstatus(billStatus);
            warehouseBills.setfTimes(tWarehouseBills.getfTimes() + 1);
            tWarehouseBillsMapper.updateTWarehousebills(warehouseBills);
            tWarehousebillsCntrMapper.deleteTWarehousebillsCntrfPid(warehouseBills.getfId());
            if (CollectionUtils.isNotEmpty(tWarehousebillsCntrs)) {
                for (TWarehousebillsCntr warehousebillsCntr : tWarehousebillsCntrs) {
                    warehousebillsCntr.setfPid(warehouseBills.getfId());
                    warehousebillsCntr.setCreateTime(DateUtils.getNowDate());
                    warehousebillsCntr.setCreateBy(SecurityUtils.getUsername());
                    int cntr = tWarehousebillsCntrMapper.insertTWarehousebillsCntr(warehousebillsCntr);
                }
            }
        }
        //获取海运费ID
        TFees tFees = tFeesMapper.selectTFeesByFName("海运费");
        if (tFees == null) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("费用信息中缺少海运费请维护");
        }
        //获取计价单位ID
        String dictValue = sysDictDataMapper.selectDictValue("data_unitfees", "箱量");
        if (StringUtils.isEmpty(dictValue)) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("计价单位中缺少箱量请维护");
        }
        //结算方式
        String fSrcType = sysDictDataMapper.selectDictValue("data_stltype_type", "月结");
        if (StringUtils.isEmpty(dictValue)) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("结算方式中缺少月结请维护");
        }
        //业务类型
        String fBusinessType = sysDictDataMapper.selectDictValue("data_billType", "内贸");
        if (StringUtils.isEmpty(dictValue)) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("业务类型中缺少内贸请维护");
        }
        //获取航次对应的运价
        List<TCtnpriceItems> tCtnpriceItems = tCtnpriceItemsMapper.selectItemMeaasge(warehouseBills.getfVoyid(), tWarehousebillsCntrs.get(0).getfCntrid());
        TVoyage voyage = tVoyageMapper.selectTVoyageByFid(warehouseBills.getfVoyid());
        //生成运价费用
        TWarehousebillsfees wbDr = new TWarehousebillsfees();
        wbDr.setfPid(warehouseBills.getfId());//主表ID
        wbDr.setfCorpid(clientFid);//客户ID
        wbDr.setfFeeid(tFees.getfId());//费用ID
        wbDr.setfFeeunitid(Long.valueOf(dictValue));//计价单位
        wbDr.setfQty(new BigDecimal(tWarehousebillsCntrs.get(0).getfCntrcount()));//数量
        if (CollectionUtils.isNotEmpty(tCtnpriceItems)) {
            wbDr.setfUnitprice(tCtnpriceItems.get(0).getfPrice());//单价
            wbDr.setfAmount(tCtnpriceItems.get(0).getfPrice().multiply(new BigDecimal(tWarehousebillsCntrs.get(0).getfCntrcount())));//金额
        } else {
            wbDr.setfUnitprice(new BigDecimal(0));//单价
            wbDr.setfAmount(new BigDecimal(0));//金额
        }
        wbDr.setfCurrency("RMB");//币别
        wbDr.setfExrate(new BigDecimal(1));//汇率
        wbDr.setfTaxrate(new BigDecimal(0));//税率
        wbDr.setfDc("D");//收付
        wbDr.setfStltypeid(Long.valueOf(fSrcType));//结算方式
        wbDr.setRemark(voyage.getfNo());//备注 航次名
        wbDr.setfSrcTypeId(2L);//来源订舱
        wbDr.setfBilltype(billsType);
        wbDr.setCreateTime(new Date());
        wbDr.setSrcBillNo(warehouseBills.getfBillno());
        wbDr.setCreateBy(loginUser.getUser().getUserName());
        wbDr.setfBusinessType(fBusinessType);//业务类型
        //wbDr.setfChargedate(warehouseBills.getfChargedate());
        //wbDr.setfBillingDeadline(warehouseBills.getfChargedate());
        if (warehouseBills.getfBsdate() != null && !warehouseBills.getfBsdate().equals("")) {
            wbDr.setfBsdate(warehouseBills.getfBsdate());
        }
        tWarehousebillsfeesMapper.insertTWarehousebillsfees(wbDr);
        map.put("TWarehousebillsfees", wbDr);
        if (isApprove) {
            AuditItems auditItems = new AuditItems();
            auditItems.setLevelId(0L);
            auditItems.setBillId(fPid);
            auditItems.setActId(actId);
            auditItems.setIffinalItem("F");
            auditItems.setBillNo(warehouseBills.getfBillno());
            // 存储委托方（货权方）
            auditItems.setRefno1(warehouseBills.getfCorpid() + "");
            // 存储业务类型（业务类型）
            auditItems.setRefno2(warehouseBills.getfBilltype());
            // 存储提单号（提单号）
            if (StringUtils.isNotEmpty(warehouseBills.getfMblno())) {
                auditItems.setRefno3(warehouseBills.getfMblno());
            } else {
                auditItems.setRefno3(warehouseBills.getfBillno());
            }
            auditItems.setSendUserId(loginUser.getUser().getUserId());
            auditItems.setSendName(SecurityUtils.getUsername());
            auditItems.setSendTime(new Date());
            auditItems.setAuditUserId(loginUser.getUser().getUserId());
            auditItems.setAuditItem(new Date());
            auditItems.setAuditOpTime(new Date());
            auditItems.setAuditMsg("提交");
            auditItems.setAuditStatus("O");
            auditItems.setFidStatus("f_billstatus");
            auditItems.setTimes(1L);
            AjaxResult approvalFlow = auditItemsService.createApprovalFlow(auditItems);
//            Long code = Long.valueOf(String.valueOf(approvalFlow.get("code"))).longValue();
            String code = approvalFlow.get("code").toString();
//                Long code = Long.valueOf(String.valueOf(ajaxResult.get("code"))).longValue();
            if ("500".equals(code)) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
            return approvalFlow;
        }
        map.put("warehouseBills", warehouseBills);
        map.put("tWarehousebillsCntrs", tWarehousebillsCntrs);
        return AjaxResult.success("msg", map);
    }

    /**
     * 配船暂存
     *
     * @param tWarehousebills          主表信息
     * @param tWarehousebillsCntritems 从表信息
     * @param billsType
     * @param loginUser
     * @return
     */
    @Override
    @Transactional
    public AjaxResult TSMakingMessage(String tWarehousebills, String tWarehousebillsCntritems, String billsType, LoginUser loginUser) {
        Map<String, Object> map = new HashMap<>();
        TWarehouseBills warehouseBills = JSONArray.parseObject(tWarehousebills, TWarehouseBills.class);
        JSONArray jsonCrArray = JSONArray.parseArray(tWarehousebillsCntritems);
        List<TWarehousebillsCntritems> tWarehousebillsCntrs = JSONObject.parseArray(jsonCrArray.toJSONString(), TWarehousebillsCntritems.class);
        TWarehouseBills tWarehouseBills = tWarehouseBillsMapper.selectTWarehousebillsById(warehouseBills.getfId());
        /*if (tWarehouseBills.getfBillstatus() == 7L
                || tWarehouseBills.getfBillstatus() == 6L) {
        } else {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("当前数据不允许暂存");
        }*/
        if (tWarehouseBills.getfBillstatus() != null && tWarehouseBills.getfBillstatus().longValue() == 6) {
            warehouseBills.setfBillstatus(7L);
        } else {
            warehouseBills.setfBillstatus(tWarehouseBills.getfBillstatus());
        }
        int i = tWarehouseBillsMapper.updateTWarehousebills(warehouseBills);
        TWarehousebillsCntr tWarehousebillsCntr = tWarehousebillsCntrMapper.selectTWarehousebillsCntrByPId(warehouseBills.getfId());
        int cntritemsfPid = tWarehousebillsCntritemsMapper.deleteTWarehousebillsCntritemsfPid(warehouseBills.getfId());
        if (CollectionUtils.isNotEmpty(tWarehousebillsCntrs)) {
            if (tWarehousebillsCntrs.size() > tWarehousebillsCntr.getfCntrcount()) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error("箱信息中的箱量不能大于货物中的箱量");
            }
            for (TWarehousebillsCntritems warehousebillsCntritems : tWarehousebillsCntrs) {
                AjaxResult ajaxResult = this.judgeBoxPile(warehousebillsCntritems, tWarehousebillsCntr.getfCntrid());
                String code = ajaxResult.get("code").toString();
                if ("500".equals(code)) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.success("error", ajaxResult.get("msg").toString());
                }
                warehousebillsCntritems.setfPid(warehouseBills.getfId());
                warehousebillsCntritems.setCreateTime(DateUtils.getNowDate());
                warehousebillsCntritems.setCreateBy(SecurityUtils.getUsername());
                int cntr = tWarehousebillsCntritemsMapper.insertTWarehousebillsCntritems(warehousebillsCntritems);
            }
        } else {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("箱信息不能为空");
        }
        map.put("warehouseBills", warehouseBills);
        map.put("tWarehousebillsCntrs", tWarehousebillsCntrs);
        return AjaxResult.success("msg", map);
    }

    /**
     * 配船提交
     *
     * @param tWarehousebills          主表信息
     * @param tWarehousebillsCntritems 从表信息
     * @param billsType
     * @param loginUser
     * @return
     */
    @Override
    @Transactional
    public AjaxResult submitMakingMessage(String tWarehousebills, String tWarehousebillsCntritems, String billsType, LoginUser loginUser) {
        boolean isApprove = false;//是否开启审批流
        String key = "";//键
        long actId = 0L;//活动id
        Long fPid = null;
        Map<String, Object> map = new HashMap<>();
        if ("KHDD".equals(billsType)) {
            actId = 420L;
            key = "khwarehouse.makingCargoPlan.ApprovalFlow";
        }
        SysConfig sysConfig = sysConfigMapper.checkConfigKeyUnique(key);
        if (StringUtils.isNull(sysConfig)) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("系统参数异常，未找到开启审批流参数");
        }
        if ("0".equals(sysConfig.getConfigValue())) {
            isApprove = true;
        }
        TWarehouseBills warehouseBills = JSONArray.parseObject(tWarehousebills, TWarehouseBills.class);
        JSONArray jsonCrArray = JSONArray.parseArray(tWarehousebillsCntritems);
        List<TWarehousebillsCntritems> tWarehousebillsCntritemsList = JSONObject.parseArray(jsonCrArray.toJSONString(), TWarehousebillsCntritems.class);
        fPid = warehouseBills.getfId();
        warehouseBills.setUpdateTime(DateUtils.getNowDate());
        warehouseBills.setUpdateBy(SecurityUtils.getUsername());
        if (isApprove) {
            warehouseBills.setfBillstatus(9L);
        } else {
            warehouseBills.setfBillstatus(11L);
            warehouseBills.setfReviewDate(new Date());
        }
        TWarehouseBills tWarehouseBills = tWarehouseBillsMapper.selectTWarehousebillsById(warehouseBills.getfId());
        if (tWarehouseBills.getfBillstatus() == 6L
                || tWarehouseBills.getfBillstatus() == 7L
                || tWarehouseBills.getfBillstatus() == 8L) {
        } else {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("当前数据不允许提交");
        }
        warehouseBills.setfTimes(tWarehouseBills.getfTimes() + 1);
        tWarehouseBillsMapper.updateTWarehousebills(warehouseBills);
        tWarehousebillsCntritemsMapper.deleteTWarehousebillsCntritemsfPid(warehouseBills.getfId());
        TWarehousebillsCntr tWarehousebillsCntr = tWarehousebillsCntrMapper.selectTWarehousebillsCntrByPId(warehouseBills.getfId());
        if (CollectionUtils.isNotEmpty(tWarehousebillsCntritemsList)) {
            for (TWarehousebillsCntritems warehousebillsCntritems : tWarehousebillsCntritemsList) {
                AjaxResult ajaxResult = this.judgeBoxPile(warehousebillsCntritems, tWarehousebillsCntr.getfCntrid());
                String code = ajaxResult.get("code").toString();
                if ("500".equals(code)) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return ajaxResult;
                }
                warehousebillsCntritems.setfPid(warehouseBills.getfId());
                warehousebillsCntritems.setCreateTime(DateUtils.getNowDate());
                warehousebillsCntritems.setCreateBy(SecurityUtils.getUsername());
                int cntr = tWarehousebillsCntritemsMapper.insertTWarehousebillsCntritems(warehousebillsCntritems);
            }
        } else {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("箱信息不能为空");
        }
        TWarehousebillsCntr warehousebillsCntr = new TWarehousebillsCntr();
        warehousebillsCntr.setfPid(warehouseBills.getfId());
        List<TWarehousebillsCntr> tWarehousebillsCntrs = tWarehousebillsCntrMapper.selectTWarehousebillsCntrList(warehousebillsCntr);
        TVoyage tVoyage = tVoyageMapper.selectTVoyageById(warehouseBills.getfVoyid());
        if (isApprove) {
            AuditItems auditItems = new AuditItems();
            auditItems.setLevelId(0L);
            auditItems.setBillId(fPid);
            auditItems.setActId(actId);
            auditItems.setIffinalItem("F");
            auditItems.setBillNo(tWarehouseBills.getfBillno());
            // 存储委托方（货权方）
            auditItems.setRefno1(tWarehouseBills.getfCorpid() + "");
            // 存储业务类型（业务类型）
            auditItems.setRefno2(tWarehouseBills.getfBilltype());
            // 存储提单号（提单号）
            auditItems.setRefno3(tWarehouseBills.getfMblno());
            auditItems.setSendUserId(loginUser.getUser().getUserId());
            auditItems.setSendName(SecurityUtils.getUsername());
            auditItems.setSendTime(new Date());
            auditItems.setAuditUserId(loginUser.getUser().getUserId());
            auditItems.setAuditItem(new Date());
            auditItems.setAuditOpTime(new Date());
            auditItems.setAuditMsg("提交");
            auditItems.setAuditStatus("O");
            auditItems.setFidStatus("f_billstatus");
            auditItems.setTimes(1L);
            AjaxResult approvalFlow = auditItemsService.createApprovalFlow(auditItems);
//            Long code = Long.valueOf(String.valueOf(approvalFlow.get("code"))).longValue();
            String code = approvalFlow.get("code").toString();
//                Long code = Long.valueOf(String.valueOf(ajaxResult.get("code"))).longValue();
            if ("500".equals(code)) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
            return approvalFlow;
        }
        map.put("warehouseBills", warehouseBills);
        map.put("tWarehousebillsCntrs", tWarehousebillsCntrs);
        map.put("tVoyageL", tVoyage);
        map.put("tWarehousebillsCntritems", tWarehousebillsCntritemsList);
        return AjaxResult.success("msg", map);
    }

    /**
     * 仓库模块提交接口
     *
     * @param tWarehouseBills       仓库主表
     * @param tWarehousebillsfeesCr 仓库费用付款明细表
     * @param tWarehousebillsfeesDr 仓库费用收款明细表
     * @param tWarehousebillsitems  仓库货物明细表
     * @param tEnclosure
     * @param loginUser             当前登陆人
     * @param billsType             操作状态
     * @return
     */
    @Override
    @Transactional
    public AjaxResult warehouseSubmission(String tWarehouseBills, String tWarehousebillsfeesCr, String tWarehousebillsfeesDr,
                                          String tWarehousebillsitems, String tEnclosure, LoginUser loginUser, String tCntr, String billsType) {
        Long fPid = null;
        boolean isApprove = false;
        Long actId = queryWarehouseActId(billsType);
        String key = "";
        if ("SJRK".equals(billsType)) {
            key = "warehouse.inStock.ApprovalFlow";
        } else if ("SJCK".equals(billsType)) {
            key = "warehouse.outStock.ApprovalFlow";
        } else if (WarehouseTypeEnum.CKDB.getType().equals(billsType)) {
            key = "warehouse.stockTransfer.ApprovalFlow";
        } else if (WarehouseTypeEnum.HQZY.getType().equals(billsType)) {
            key = "warehouse.transfer.ApprovalFlow";
        } else if (WarehouseTypeEnum.HWTG.getType().equals(billsType)) {
            key = "warehouse.cargoClearance.ApprovalFlow";
        } else if ("CDZZ".equals(billsType)) {
            key = "warehouse.yardLoading.ApprovalFlow";
        }
        SysConfig sysConfig = sysConfigMapper.checkConfigKeyUnique(key);
        if (StringUtils.isNull(sysConfig)) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("系统参数异常，未找到开启审批流参数");
        }
        if ("0".equals(sysConfig.getConfigValue())) {
            isApprove = true;
        }
        TWarehouseBills warehouseBills = JSONArray.parseObject(tWarehouseBills, TWarehouseBills.class);
        if ("SJRK".equals(billsType) || "SJCK".equals(billsType)) {
            SysConfig warehouseConfig = queryWarehouseConfig(billsType);
            if (StringUtils.isNull(warehouseConfig)) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error("系统参数异常，未找到接单审批流参数");
            }
        }
//        if ("0".equals(sysConfig.getConfigValue()) && (warehouseBills.getWarehouseStatus() == 4L || warehouseBills.getWarehouseStatus() == 5L)) {
//            return AjaxResult.error("接单审批正在进行中，无法进行提交");
//        }
        warehouseBills.setfItemsStatus(4L);
        Long timestamp = DateUtils.getTimestamp(new Date());
        warehouseBills.setfDateChanged(timestamp.toString() + (int) (Math.random() * 900) + 100);
        TWarehousebillsitems itemInFo = tWarehousebillsitemsMapper.selectItemQtyByFPid(warehouseBills.getfId());
        warehouseBills.setfQty(itemInFo.getfQty());
        warehouseBills.setfNetweight(itemInFo.getfNetweight());
        warehouseBills.setfGrossweight(itemInFo.getfGrossweight());
        warehouseBills.setfTimes(warehouseBills.getfTimes() + 1);
        if (StringUtils.isNull(warehouseBills.getfId())) {
            if (isApprove) {
                warehouseBills.setfBillstatus(4L);
            } else {
                warehouseBills.setfBillstatus(6L);
                warehouseBills.setfReviewDate(new Date());
            }
            warehouseBills.setfBilltype(billsType);
            if (!"SJRK".equals(billsType) && !WarehouseTypeEnum.HQZY.getType().equals(billsType)) {
                warehouseBills.setfChargedate(warehouseBills.getfBsdate());
            }
            warehouseBills.setfBsdeptid(loginUser.getUser().getDeptId());
            warehouseBills.setCreateBy(loginUser.getUser().getUserName());
            String billNo = billnoSerialServiceImpl.getBillNo(billsType, warehouseBills.getfBsdate());
            warehouseBills.setfBillno(billNo);
            Date time = new Date();
            String bscorpno = billnoSerialServiceImpl.getCorpNo(warehouseBills.getfCorpid(), time);
            warehouseBills.setfBscorpno(bscorpno);
            tWarehouseBillsMapper.insertTWarehousebills(warehouseBills);
            fPid = warehouseBills.getfId();
        } else {
            fPid = warehouseBills.getfId();
            if (isApprove) {
                warehouseBills.setfBillstatus(4L);
            } else {
                warehouseBills.setfBillstatus(6L);
                warehouseBills.setfReviewDate(new Date());
            }
            warehouseBills.setUpdateTime(new Date());
            if (!"SJRK".equals(billsType) && !WarehouseTypeEnum.HQZY.getType().equals(billsType)) {
                warehouseBills.setfChargedate(warehouseBills.getfBsdate());
            }
            warehouseBills.setUpdateBy(loginUser.getUser().getUserName());

            tEnclosureMapper.deleteByFPid(fPid);
            tWarehousebillsfeesMapper.deleteByFPid(fPid);
            if (!"CDZZ".equals(billsType)) {
                tWarehousebillsitemsMapper.deleteByFPid(fPid);
            }
            tWarehouseBillsMapper.updateTWarehousebills(warehouseBills);
            tWarehousebillsCntrMapper.deleteTWarehousebillsCntrfPid(fPid);
        }
        JSONArray warehouseJSON = JSONArray.parseArray(tWarehousebillsitems);
        List<TWarehousebillsitems> warehousebillsitemsList = JSONObject.parseArray(warehouseJSON.toJSONString(), TWarehousebillsitems.class);
        int line = 0;
        for (TWarehousebillsitems wbItem : warehousebillsitemsList) {
            line++;
            if ("SJRK".equals(billsType) || "SJCK".equals(billsType) || WarehouseTypeEnum.CKDB.getType().equals(billsType) || WarehouseTypeEnum.HWTG.getType().equals(billsType)) {
                // 除了入库其他模块不需要更新主表的 仓储费计费日期到明细表，其他模块 应从库存总账把仓储费计费日期 赋给明细表
                if ("SJRK".equals(billsType)) {
                    wbItem.setfMblno(warehouseBills.getfMblno());
                    wbItem.setfBillingway(warehouseBills.getfBillingway());
                    wbItem.setfChargedate(warehouseBills.getfChargedate());
                    wbItem.setfOriginalbilldate(warehouseBills.getfBsdate());
                    wbItem.setfMblno(warehouseBills.getfMblno());// 入库更新库存前执行update更新明细的提单号等于主表的提单号
                }
                if (!wbItem.getfBillstatus().equals(40L)) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error("库存明细第" + line + "行状态异常，请确认");
                }
            } else {
                if (!"CDZZ".equals(billsType) && !wbItem.getfBillstatus().equals(6L)) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error("库存明细第" + line + "行状态异常，请确认");
                }
            }

            if (!"CDZZ".equals(billsType)) {
                if (StringUtils.isNull(wbItem.getfChargedate())) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error("库存明细第" + line + "行未找到仓储费计费日期，请确认");
                }
                if (StringUtils.isNull(wbItem.getfBillingway())) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error("库存明细第" + line + "行未找到计费方式，请确认");
                }
                if (StringUtils.isNull(wbItem.getfOriginalbilldate())) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error("库存明细第" + line + "行未找到入库日期，请确认");
                }

                wbItem.setfPid(fPid);
                wbItem.setfBilltype(billsType);
                wbItem.setCreateTime(new Date());
                wbItem.setfBillno(warehouseBills.getfBillno());
                wbItem.setCreateBy(loginUser.getUser().getUserName());
                tWarehousebillsitemsMapper.insertTWarehousebillsitems(wbItem);
            }
        }
        //  箱型数据
        if (StringUtils.isNotNull(tCntr) && !"[]".equals(tCntr)) {
            JSONArray jsonDrArray = JSONArray.parseArray(tCntr);
            List<TWarehousebillsCntr> tWarehousebillsCntrs = JSONObject.parseArray(jsonDrArray.toJSONString(), TWarehousebillsCntr.class);
            int cntrLine = 0;
            for (TWarehousebillsCntr cntr : tWarehousebillsCntrs) {
                cntrLine++;
                if (StringUtils.isNull(cntr.getfCntrid()) || StringUtils.isNull(cntr.getfCntrcount()) || cntr.getfCntrcount() == 0) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error("箱型数据第" + cntrLine + "行数据缺少必填数据");
                }
                cntr.setfPid(fPid);
                cntr.setfGoodsid(0L);
                cntr.setfPackageid("0");
                cntr.setfCntrweight(new BigDecimal(0));
                cntr.setCreateBy(loginUser.getUser().getUserName());
                cntr.setCreateTime(new Date());
                tWarehousebillsCntrMapper.insertTWarehousebillsCntr(cntr);
            }
        }
        if (StringUtils.isNotNull(tWarehousebillsfeesCr) && !"[]".equals(tWarehousebillsfeesCr)) {
            JSONArray jsonCrArray = JSONArray.parseArray(tWarehousebillsfeesCr);
            List<TWarehousebillsfees> warehousebillsfeesCrList = JSONObject.parseArray(jsonCrArray.toJSONString(), TWarehousebillsfees.class);
            for (TWarehousebillsfees wbCr : warehousebillsfeesCrList) {
                wbCr.setfPid(fPid);
                wbCr.setfDc("C");
                wbCr.setfBilltype(billsType);
                wbCr.setCreateTime(new Date());
                wbCr.setSrcBillNo(warehouseBills.getfBillno());
                wbCr.setCreateBy(loginUser.getUser().getUserName());
                wbCr.setfChargedate(warehouseBills.getfChargedate());
                wbCr.setfBillingDeadline(warehouseBills.getfChargedate());
                if (warehouseBills.getfBsdate() != null && !warehouseBills.getfBsdate().equals("")) {
                    wbCr.setfBsdate(warehouseBills.getfBsdate());
                }
                tWarehousebillsfeesMapper.insertTWarehousebillsfees(wbCr);
            }
        }
        if (StringUtils.isNotNull(tWarehousebillsfeesDr) && !"[]".equals(tWarehousebillsfeesDr)) {
            JSONArray jsonCrArray = JSONArray.parseArray(tWarehousebillsfeesDr);
            List<TWarehousebillsfees> warehousebillsfeesDrList = JSONObject.parseArray(jsonCrArray.toJSONString(), TWarehousebillsfees.class);
            for (TWarehousebillsfees wbDr : warehousebillsfeesDrList) {
                wbDr.setfPid(fPid);
                wbDr.setfDc("D");
                if (Objects.isNull(wbDr.getfReviewDate())) {
                    wbDr.setfBillstatus(4L);
                }
                wbDr.setfBilltype(billsType);
                wbDr.setCreateTime(new Date());
                wbDr.setSrcBillNo(warehouseBills.getfBillno());
                wbDr.setCreateBy(loginUser.getUser().getUserName());
                wbDr.setfChargedate(warehouseBills.getfChargedate());
                wbDr.setfBillingDeadline(warehouseBills.getfChargedate());
                if (warehouseBills.getfBsdate() != null && !warehouseBills.getfBsdate().equals("")) {
                    wbDr.setfBsdate(warehouseBills.getfBsdate());
                }
                tWarehousebillsfeesMapper.insertTWarehousebillsfees(wbDr);
            }
        }
        if (StringUtils.isNotNull(tEnclosure) && !"[]".equals(tEnclosure)) {
            JSONArray jsonEnclosureArray = JSONArray.parseArray(tEnclosure);
            List<TEnclosure> enclosuresList = JSONObject.parseArray(jsonEnclosureArray.toJSONString(), TEnclosure.class);
            long lineNo = 0L;
            for (TEnclosure enclosure : enclosuresList) {
                lineNo++;
                enclosure.setfPid(fPid);
                enclosure.setfLineno(lineNo);
                enclosure.setCreateTime(new Date());
                enclosure.setCreateBy(loginUser.getUser().getUserName());
                tEnclosureMapper.insertTEnclosure(enclosure);
            }
        }
        // 这里加个判断取系统参数来确定是否需要启用审批流
        if (isApprove) {
            AuditItems auditItems = new AuditItems();
            auditItems.setLevelId(0L);
            auditItems.setBillId(fPid);
            auditItems.setActId(actId);
            auditItems.setIffinalItem("F");
            auditItems.setBillNo(warehouseBills.getfBillno());
            // 存储委托方（货权方）
            auditItems.setRefno1(warehouseBills.getfCorpid() + "");
            // 存储业务类型（业务类型）
            auditItems.setRefno2(warehouseBills.getfBilltype());
            // 存储提单号（提单号）
            auditItems.setRefno3(warehouseBills.getfMblno());
            auditItems.setSendUserId(loginUser.getUser().getUserId());
            auditItems.setSendName(loginUser.getUsername());
            auditItems.setSendTime(new Date());
            auditItems.setAuditUserId(loginUser.getUser().getUserId());
            auditItems.setAuditItem(new Date());
            auditItems.setAuditOpTime(new Date());
            auditItems.setAuditMsg("提交");
            auditItems.setAuditStatus("O");
            auditItems.setFidStatus("f_billstatus");
            auditItems.setTimes(warehouseBills.getfTimes());
            AjaxResult approvalFlow = auditItemsService.createApprovalFlow(auditItems);
//            Long code = Long.valueOf(String.valueOf(approvalFlow.get("code"))).longValue();
            String code = approvalFlow.get("code").toString();
//                Long code = Long.valueOf(String.valueOf(ajaxResult.get("code"))).longValue();
            if ("500".equals(code)) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
            return approvalFlow;
        } else {
            AjaxResult ajaxResult = warehouseFollow(fPid, 6L);
            String code = ajaxResult.get("code").toString();
            if ("500".equals(code)) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
            return ajaxResult;
        }
    }

    @Override
    public List<TWareHouseExcelItems> selectTWarehousebillsItemsList(Long fId) {
        return tWarehouseBillsMapper.selectTWarehousebillsItemsList(fId);
    }

    /**
     * 导出仓储明细
     */
    @Override
    public List<StorageDetail> selectStorageDetail(Long fId) {
        List<StorageDetail> storageDetails = new ArrayList<>();
        storageDetails.addAll(tWarehouseBillsMapper.selectInStockDetail(fId));
        storageDetails.addAll(tWarehouseBillsMapper.selectNotInStockDetail(fId, "HQZY"));
        storageDetails.addAll(tWarehouseBillsMapper.selectNotInStockDetail(fId, "SJCK"));
        storageDetails.addAll(tWarehouseBillsMapper.selectInventoryDetail(fId));
        return storageDetails;
    }

    @Override
    public List<Map<String, Object>> selectInventoryList(TWarehouseBills tWarehouseBills) {
        if (StringUtils.isNotNull(tWarehouseBills.getfWarehouseid())) {
            // 获取仓库信息
            TWarehouse tWarehouse = tWarehouseMapper.selectTWarehouseById(tWarehouseBills.getfWarehouseid());
            if (tWarehouse.getfLocation() == 1) {
                tWarehouseBills.setfLocation(1L);
            } else {
                tWarehouseBills.setfLocation(0L);
            }
        }
        if (tWarehouseBills.getfBilltype().equals("SJRK")) {
            return tWarehouseBillsMapper.selectInventorySJRKList(tWarehouseBills);
        } else {
            return tWarehouseBillsMapper.selectInventorySJCKList(tWarehouseBills);
        }
    }

    @Override
    public List<TWareHouseItemsExcel> selectTWarehousebillsItemsList(TWarehouseBills tWarehouseBills) {
        return tWarehouseBillsMapper.selectTWarehousebillsItemList(tWarehouseBills);
    }

    @Override
    public AjaxResult serialNumber(String billsType) {
        Map<String, Object> map = new HashMap<>();
        Date time = new Date();
        String serialNumber = null;
        // 查询流水号
        if ("SJRK".equals(billsType)) {
            serialNumber = billnoSerialServiceImpl.getFictitiousNumber("RK", time);
        } else if ("SJCK".equals(billsType)) {
            serialNumber = billnoSerialServiceImpl.getFictitiousNumber("CK", time);
        } else if (WarehouseTypeEnum.CKDB.getType().equals(billsType)) {
            serialNumber = billnoSerialServiceImpl.getFictitiousNumber("DB", time);
        }
        map.put("fSerialNumber", serialNumber);
        return AjaxResult.success("成功", map);
    }

    @Override
    public int derecognition(Long fId) {
        // 查询对账
        int reconciliation = tWarehousebillsfeesMapper.selectReconciliation(fId);
        // 查询收费
        int charge = tWarehousebillsfeesMapper.selectCharge(fId);
        // 查询付费
        int pay = tWarehousebillsfeesMapper.selectPay(fId);
        if (reconciliation > 0) {
            return 1;
        } else if (charge > 0) {
            return 2;
        } else if (pay > 0) {
            return 3;
        } else {
            return 4;
        }
    }

    @Override
    public List<Map<String, Object>> selectWareHouseNumber() {
        List<Map<String, Object>> map = new ArrayList<>();
        Map<String, Object> maps = new HashMap<>();
        // 入库待办数量
        maps.put("inStock", tWarehousebillsitemsMapper.inStock());
        // 出库待办数量
        maps.put("outStock", tWarehousebillsitemsMapper.outStock());

        List<String> timeInterval = new ArrayList<>();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        //获取当前月第一天：
        Calendar c = Calendar.getInstance();
        c.add(Calendar.MONTH, 0);
        c.set(Calendar.DAY_OF_MONTH, 1);//设置为1号,当前日期既为本月第一天
        timeInterval.add(format.format(c.getTime()));
        //获取前月的最后一天
        Calendar ca = Calendar.getInstance();
        ca.set(Calendar.DAY_OF_MONTH, ca.getActualMaximum(Calendar.DAY_OF_MONTH));
        timeInterval.add(format.format(ca.getTime()));
        maps.put("monthInStock", tWarehousebillsitemsMapper.monthInStock(timeInterval));
        // 当月出库待办数量
        maps.put("monthOutStock", tWarehousebillsitemsMapper.monthOutStock(timeInterval));
        map.add(maps);
        return map;
    }

    @Override
    @Transactional
    public AjaxResult waitWarehousingItems(TWarehousebillsitems tWarehousebillsitems) {
        // 先查询是否已经处理
        TWarehousebillsitems tWarehousebillsitems1 = tWarehousebillsitemsMapper.selectTWarehousebillsitemsById(tWarehousebillsitems.getfId());
        if (tWarehousebillsitems1.getfBillstatus().equals(30)) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("更新库存明细失败,该信息已操作,请重新加载");
        }
        tWarehousebillsitems.setfSerialNumber(tWarehousebillsitems1.getfSerialNumber());
        int num = tWarehousebillsitemsMapper.updateTWarehousebillsitems(tWarehousebillsitems);
        // 主表变更状态
        TWarehouseBills tWarehousebills = new TWarehouseBills();
        tWarehousebills.setfId(tWarehousebillsitems1.getfPid());
        Long timestamp = DateUtils.getTimestamp(new Date());
        tWarehousebills.setfDateChanged(timestamp.toString() + (int) (Math.random() * 900) + 100);
        tWarehousebills.setfItemsStatus(3L);
        TWarehousebillsitems itemInFo = tWarehousebillsitemsMapper.selectItemQtyByFPid(tWarehousebills.getfId());
        tWarehousebills.setfQty(itemInFo.getfQty());
        tWarehousebills.setfNetweight(itemInFo.getfNetweight());
        tWarehousebills.setfGrossweight(itemInFo.getfGrossweight());
        int num1 = tWarehouseBillsMapper.updateTWarehousebills(tWarehousebills);
        if (num <= 0 && num1 <= 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("更新库存明细失败");
        } else {
            return AjaxResult.success();
        }
    }

    /**
     * app仓储新行保存业务
     *
     * @param item    明细数据
     * @param attachs 附件数据
     * @return 结果
     */
    @Override
    public AjaxResult submitWarehouse(String item, String attachs) {
        TWarehousebillsitems tWarehousebillsitems = JSONArray.parseObject(item, TWarehousebillsitems.class);
        if (StringUtils.isNull(tWarehousebillsitems.getfPid())) {
            return AjaxResult.error("未找到主表id信息，请确认");
        }
        TWarehouseBills warehouseBills = tWarehouseBillsMapper.selectTWarehousebillsById(tWarehousebillsitems.getfPid());
        if (StringUtils.isNotNull(tWarehousebillsitems.getfGoodsid())) {
            TGoods goods = tGoodsMapper.selectTGoodsById(tWarehousebillsitems.getfGoodsid());
            if (!warehouseBills.getfProductName().contains(goods.getfName())) {
                warehouseBills.setfProductName(warehouseBills.getfProductName() + "/" + goods.getfName());
            }
        }
        if (StringUtils.isNotNull(warehouseBills.getfMarks())) {
            if (!warehouseBills.getfMarks().contains(tWarehousebillsitems.getfMarks())) {
                warehouseBills.setfMarks(warehouseBills.getfMarks() + "/" + tWarehousebillsitems.getfMarks());
            }
        }
        if (!"SJRK".equals(warehouseBills.getfBilltype())) {
            if (!warehouseBills.getfMblno().contains(tWarehousebillsitems.getfMblno())) {
                warehouseBills.setfMblno(warehouseBills.getfMblno() + "/" + tWarehousebillsitems.getfMblno());
            }
        }
        Long timestamp = DateUtils.getTimestamp(new Date());
        warehouseBills.setfDateChanged(timestamp.toString() + (int) (Math.random() * 900) + 100);
        warehouseBills.setUpdateTime(new Date());
        warehouseBills.setUpdateBy(SecurityUtils.getUsername());
        TWarehousebillsitems itemInFo = tWarehousebillsitemsMapper.selectItemQtyByFPid(warehouseBills.getfId());
        warehouseBills.setfQty(itemInFo.getfQty());
        warehouseBills.setfNetweight(itemInFo.getfNetweight());
        warehouseBills.setfGrossweight(itemInFo.getfGrossweight());
        tWarehouseBillsMapper.updateTWarehousebills(warehouseBills);
        if (StringUtils.isNull(tWarehousebillsitems.getfId())) {
            tWarehousebillsitems.setCreateTime(new Date());
            tWarehousebillsitems.setCreateBy(SecurityUtils.getUsername());
            tWarehousebillsitemsMapper.insertTWarehousebillsitems(tWarehousebillsitems);
        } else {
            TWarehousebillsitems warehousebillsitems = tWarehousebillsitemsMapper.selectTWarehousebillsitemsById(tWarehousebillsitems.getfId());
            if (StringUtils.isNull(warehousebillsitems)) {
                return AjaxResult.error("未找到明细信息，请确认该明细信息是否存在");
            }
            if (warehousebillsitems.getfBillstatus() != 30L) {
                return AjaxResult.error("该明细信息异常" + warehousebillsitems.getfBillstatus() + "，请确认");
            }
            tWarehousebillsitems.setUpdateTime(new Date());
            tWarehousebillsitems.setUpdateBy(SecurityUtils.getUsername());
            tWarehousebillsitemsMapper.updateTWarehousebillsitems(tWarehousebillsitems);
        }
        tEnclosureMapper.deleteByFPid(tWarehousebillsitems.getfPid());
        if (StringUtils.isNotEmpty(attachs) && !"[]".equals(attachs)) {
            //  附件添加
            JSONArray jsonDrArray = JSONArray.parseArray(attachs);
            List<TEnclosure> tEnclosureList = JSONObject.parseArray(jsonDrArray.toJSONString(), TEnclosure.class);
            for (TEnclosure enclosure : tEnclosureList) {
                enclosure.setfStatus("2");
                enclosure.setCreateTime(new Date());
                enclosure.setfPid(tWarehousebillsitems.getfPid());
                enclosure.setCreateBy(SecurityUtils.getUsername());
                tEnclosureMapper.insertTEnclosure(enclosure);
            }
        }
        return AjaxResult.success();
    }

    /**
     * 查看集港业务
     *
     * @param fId 集港id
     * @return
     */
    @Override
    public AjaxResult selectContainerPort(Long fId) {
        Map<String, Object> map = new HashMap<>();
        TWarehouseBills warehouseBills = tWarehouseBillsMapper.selectTWarehousebillsById(fId);
        if (StringUtils.isNull(warehouseBills)) {
            return AjaxResult.error("未找到主表信息，请确认该信息是否存在");
        }
        map.put("warehouseBills", warehouseBills);
        TWarehousebillsfees warehousebillsfees = new TWarehousebillsfees();
        warehousebillsfees.setfPid(fId);
        warehousebillsfees.setfDc("D");
        List<TWarehousebillsfees> feesDr = tWarehousebillsfeesMapper.selectTWarehousebillsfeesList(warehousebillsfees);
        List<TCorps> transportationList = new ArrayList<>();
        if (StringUtils.isNotEmpty(feesDr)) {
            for (TWarehousebillsfees dr : feesDr) {
                TCorps corp = tCorpsMapper.selectTCorpsById(dr.getfCorpid());
                if (StringUtils.isNotNull(corp)) {
                    transportationList.add(corp);
                }
            }
            transportationList = transportationList.stream().distinct().collect(toList());
        }
        map.put("feesDrList", feesDr);
        map.put("corpList", transportationList);
        List<TCorps> corpsList = new ArrayList<>();
        warehousebillsfees.setfDc("C");
        List<TWarehousebillsfees> feesCr = tWarehousebillsfeesMapper.selectTWarehousebillsfeesList(warehousebillsfees);
        if (StringUtils.isNotEmpty(feesCr)) {
            for (TWarehousebillsfees cr : feesCr) {
                TCorps corp = tCorpsMapper.selectTCorpsById(cr.getfCorpid());
                if (StringUtils.isNotNull(corp)) {
                    corpsList.add(corp);
                }
            }
            corpsList = corpsList.stream().distinct().collect(toList());
        }
        map.put("feesCrList", feesCr);
        map.put("transportationList", corpsList);
        return AjaxResult.success(map);
    }

    /**
     * 集港业务保存、提交接口
     *
     * @param tWarehouseBills 主表业务
     * @param feesCr          收费
     * @param feesDr          付费
     * @return
     */
    @Override
    @Transactional
    public AjaxResult saveContainerPort(String tWarehouseBills, String feesCr, String feesDr, String type) {
        TWarehouseBills warehouseBills = JSONArray.parseObject(tWarehouseBills, TWarehouseBills.class);
        warehouseBills.setfBilltype("CKJG");
        // 判断提单号是否存在
        if (StringUtils.isNull(warehouseBills.getfId()) && tWarehouseBillsMapper.selectContainMblno(warehouseBills) > 0) {
            return AjaxResult.error("该提单号已存在");
        }
        Long billStatus = 2L;
        if ("add".equals(type)) {
            billStatus = 6L;
            warehouseBills.setfReviewDate(warehouseBills.getfBsdate());
            warehouseBills.setfBillstatus(billStatus);
        } else {
            if (StringUtils.isNull(warehouseBills.getfBillstatus())) {
                warehouseBills.setfBillstatus(billStatus);
            }
        }
        if (StringUtils.isNull(warehouseBills.getfId())) {
            warehouseBills.setCreateTime(new Date());
            warehouseBills.setCreateBy(SecurityUtils.getUsername());
            warehouseBills.setfDeptid(SecurityUtils.getLoginUser().getUser().getDeptId());
            warehouseBills.setfBsdeptid(SecurityUtils.getLoginUser().getUser().getDeptId());
            tWarehouseBillsMapper.insertTWarehousebills(warehouseBills);
        } else {
            warehouseBills.setUpdateTime(new Date());
            warehouseBills.setUpdateBy(SecurityUtils.getUsername());
            tWarehouseBillsMapper.updateTWarehousebills(warehouseBills);
        }
        tWarehousebillsfeesMapper.deleteByFPid(warehouseBills.getfId());
        if (StringUtils.isNotEmpty(feesCr) && !"[]".equals(feesCr)) {
            JSONArray jsonDrArray = JSONArray.parseArray(feesCr);
            List<TWarehousebillsfees> warehousebillsfeesCr = JSONObject.parseArray(jsonDrArray.toJSONString(), TWarehousebillsfees.class);
            int line = 1;
            for (TWarehousebillsfees cr : warehousebillsfeesCr) {
                if (StringUtils.isNull(cr.getfCorpid()) || StringUtils.isNull(cr.getfFeeunitid()) || StringUtils.isNull(cr.getfInventoryDays())) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error("付款费用第" + line + "行，缺少必填信息");
                }
                cr.setfDc("C");
                cr.setfBillstatus(billStatus);
                cr.setCreateTime(new Date());
                cr.setfPid(warehouseBills.getfId());
                cr.setCreateBy(SecurityUtils.getUsername());
                tWarehousebillsfeesMapper.insertTWarehousebillsfees(cr);
                line++;
            }
        }
        if (StringUtils.isNotEmpty(feesDr) && !"[]".equals(feesDr)) {
            JSONArray jsonDrArray = JSONArray.parseArray(feesDr);
            List<TWarehousebillsfees> warehousebillsfeesDr = JSONObject.parseArray(jsonDrArray.toJSONString(), TWarehousebillsfees.class);
            int line = 1;
            for (TWarehousebillsfees dr : warehousebillsfeesDr) {
                if (StringUtils.isNull(dr.getfCorpid()) || StringUtils.isNull(dr.getfFeeunitid()) || StringUtils.isNull(dr.getfInventoryDays())) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error("收款费用第" + line + "行，缺少必填信息");
                }
                dr.setfDc("D");
                dr.setfBillstatus(billStatus);
                dr.setCreateTime(new Date());
                dr.setfPid(warehouseBills.getfId());
                dr.setCreateBy(SecurityUtils.getUsername());
                tWarehousebillsfeesMapper.insertTWarehousebillsfees(dr);
                line++;
            }
        }
        return AjaxResult.success();
    }

    /**
     * 查询集港业务基础资料
     *
     * @return
     */
    @Override
    public AjaxResult selectBasicInformation() {
        Map<String, Object> map = new HashMap<>();
        TCorps corps = new TCorps();
        String typeValue = "[\"1\"]";
        corps.setfTypeid(typeValue);
        corps.setfStatus("0");
        // 应收 取客户
        map.put("corpList", tCorpsMapper.selectTCorpsListLimit200(corps));
        // 应付 取陆运公司
        TCorps transportation = new TCorps();
        typeValue = "[\"2\"]";
        transportation.setfTypeid(typeValue);
        transportation.setfStatus("0");
        map.put("transportationList", tCorpsMapper.selectTCorpsListLimit200(transportation));
        // 查询箱信息
        TCntr tCntr = new TCntr();
        tCntr.setfStatus("T");
        map.put("cntrList", tCntrMapper.selectRcntrName(tCntr));
        map.put("pierList", sysDictDataMapper.selectDictDataByType("pier"));
        TFees tFees = tFeesMapper.selectTFeesByFName("集港费");
        if (StringUtils.isNull(tFees)) {
            map.put("fees", tFees);
            return AjaxResult.success("未找到集港费用信息，请添加", map);
        }
        List<TFees> feesList = new ArrayList<>();
        feesList.add(tFees);
        map.put("fees", feesList);
        return AjaxResult.success(map);
    }

    /**
     * 集港业务撤销
     *
     * @param fId  主表id
     * @param type
     * @return
     */
    @Override
    @Transactional
    public AjaxResult revokeContainerPort(Long fId, String type) {
        TWarehouseBills warehouseBills = tWarehouseBillsMapper.selectTWarehousebillsById(fId);
        if (StringUtils.isNull(warehouseBills)) {
            return AjaxResult.error("未找到主表信息，请确认是否存在");
        }
        TWarehousebillsfees warehousebillsfees = new TWarehousebillsfees();
        warehousebillsfees.setfPid(fId);
        List<TWarehousebillsfees> warehousebillsfeesList = tWarehousebillsfeesMapper.selectTWarehousebillsfeesList(warehousebillsfees);
        if (StringUtils.isEmpty(warehousebillsfeesList)) {
            return AjaxResult.error("未找到费用信息，请确认是否存在");
        }
        for (TWarehousebillsfees fee : warehousebillsfeesList) {
            if (StringUtils.isNotEmpty(fee.getfStatementNo()) || StringUtils.isNotEmpty(fee.getfStlamountNo())) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error("费用信息存在已对账或已收费付费操作，无法撤销");
            }
            if ("remove".equals(type)) {
                tWarehousebillsfeesMapper.deleteTWarehousebillsfeesById(fee.getfId());
            } else {
                fee.setfStatus("2");
                fee.setUpdateTime(new Date());
                fee.setUpdateBy(SecurityUtils.getUsername());
                tWarehousebillsfeesMapper.updateTWarehousebillsfees(fee);
            }
        }
        if ("remove".equals(type)) {
            if (warehouseBills.getfBillstatus() != 2L) {
                return AjaxResult.error("主表状态有误，请确认状态是否为暂存状态");
            }
            tWarehouseBillsMapper.deleteTWarehousebillsById(fId);
            return AjaxResult.success();
        } else {
            if (warehouseBills.getfBillstatus() != 6L) {
                return AjaxResult.error("主表状态有误，请确认状态是否已提交");
            }
        }
        warehouseBills.setfBillstatus(2L);
        warehouseBills.setUpdateTime(new Date());
        warehouseBills.setUpdateBy(SecurityUtils.getUsername());
        tWarehouseBillsMapper.updateTWarehousebills(warehouseBills);
        return AjaxResult.success();
    }

    @Override
    public AjaxResult importCreateCompanyMsg(MultipartFile file) throws Exception {
        List<TWarehousebillsCntritemsExcel> fleetCompanyMsgs = new ArrayList<>();
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
            String originalFilename = file.getOriginalFilename();
            Workbook workbook = null;
            if (originalFilename.endsWith("xls")) {
                workbook = WorkbookFactory.create(inputStream);
            } else if (originalFilename.endsWith("xlsx")) {
                workbook = new XSSFWorkbook(inputStream);
            }
            Sheet sheet = workbook.getSheetAt(0);
            int line = 0;
            for (Row rows : sheet) {
                line++;
                if (rows.getRowNum() == 0) {
                    continue;
                }
                TWarehousebillsCntritemsExcel companyMsg = new TWarehousebillsCntritemsExcel();
                for (int a = 0; a < rows.getPhysicalNumberOfCells(); a++) {
                    Cell cell = rows.getCell(a);
                    String value = filter(sheet.getRow(0), CellReference.convertNumToColString(cell.getColumnIndex()));
                    switch (value) {
                        case "箱号":
                            //设置单元格类型
                            cell.setCellType(CellType.STRING);
                            if (StringUtils.isEmpty(cell.getStringCellValue())) {
                                return AjaxResult.error("Excel箱信息数据第" + line + "行数据缺少箱号");
                            }
                            companyMsg.setfCntrno(cell.getStringCellValue());
                            break;
                        case "铅封号":
                            //设置单元格类型
                            cell.setCellType(CellType.STRING);
                            if (StringUtils.isEmpty(cell.getStringCellValue())) {
                                return AjaxResult.error("Excel箱信息数据第" + line + "行数据缺少封号");
                            }
                            companyMsg.setfSealno(cell.getStringCellValue());
                            break;
                        case "单箱重(不得超过40)":
                            //设置单元格类型
                            cell.setCellType(CellType.STRING);
                            if (StringUtils.isEmpty(cell.getStringCellValue())) {
                                return AjaxResult.error("Excel箱信息数据第" + line + "行数据缺少单箱重");
                            }
                            companyMsg.setfCntrweight(new BigDecimal(cell.getStringCellValue()));
                            break;
                        case "货名":
                            //设置单元格类型
                            cell.setCellType(CellType.STRING);
                            if (StringUtils.isEmpty(cell.getStringCellValue())) {
                                return AjaxResult.error("Excel箱信息数据第" + line + "行数据缺少货名");
                            }
                            companyMsg.setGoodsName(cell.getStringCellValue());
                            TGoods tGoods = tGoodsMapper.checkUFNnameUnique(companyMsg.getGoodsName());
                            if (tGoods != null && tGoods.getfId() != null) {
                                companyMsg.setfGoodsid(tGoods.getfId());
                            }
                            break;
                        case "包装类型":
                            //设置单元格类型
                            cell.setCellType(CellType.STRING);
                            if (StringUtils.isEmpty(cell.getStringCellValue())) {
                                return AjaxResult.error("Excel箱信息数据第" + line + "行数据缺少包装类型");
                            }
                            companyMsg.setPackageName(cell.getStringCellValue());
                            String fPackageid = sysDictDataMapper.selectDictValue("f_packageid", companyMsg.getPackageName());
                            if (StringUtils.isNotEmpty(fPackageid)) {
                                companyMsg.setfPackageid(fPackageid);
                            }
                            break;
                        case "箱型":
                            //设置单元格类型
                            cell.setCellType(CellType.STRING);
                            if (StringUtils.isEmpty(cell.getStringCellValue())) {
                                return AjaxResult.error("Excel箱信息数据第" + line + "行数据缺少箱型");
                            }
                            companyMsg.setCntrName(cell.getStringCellValue());
                            Long fId = tCntrMapper.selectRcntrFId(companyMsg.getCntrName());
                            if (fId != null) {
                                companyMsg.setfCntrid(fId);
                            }
                            break;
                    }
                }
                fleetCompanyMsgs.add(companyMsg);
            }
        } catch (IOException e) {
            return AjaxResult.error("上传文件失败,请检查文件是否损坏");
        }
        return AjaxResult.success("success", fleetCompanyMsgs);

    }

    @Override
    @Transactional
    public AjaxResult importCreateCompanyMsgNew(MultipartFile file, LoginUser loginUser, Long fId) throws Exception {
        //查询货物信息
        TWarehousebillsCntr tWarehousebillsCntr = tWarehousebillsCntrMapper.selectTWarehousebillsCntrById(fId);
        if (tWarehousebillsCntr == null) {
            return AjaxResult.success("error", "未找到货物信息");
        }
        //查询集装箱信息
        TCntr tCntr = tCntrMapper.selectTCntrById(tWarehousebillsCntr.getfCntrid());
        List<TTemporaryFile> fleetCompanyMsgs = new ArrayList<>();
        List<String> tCnTrNoList = new ArrayList<>();
        List<String> List = new ArrayList<>();
        InputStream inputStream = null;
        Map<String, Object> map = new HashMap<>();
        String originalFilename;//文件名
        try {
            inputStream = file.getInputStream();
            originalFilename = file.getOriginalFilename();
            Workbook workbook = null;
            if (originalFilename.endsWith("xls")) {
                workbook = WorkbookFactory.create(inputStream);
            } else if (originalFilename.endsWith("xlsx")) {
                workbook = new XSSFWorkbook(inputStream);
            }
            Sheet sheet = workbook.getSheetAt(0);
            int line = 0;
            //导入之前删除原表里的数据
            tTemporaryFileMapper.deleteTTemporaryFilefileName(originalFilename, loginUser.getUser().getUserName());
            for (Row rows : sheet) {
                line++;
                if (rows.getRowNum() == 0) {
                    continue;
                }
                TTemporaryFile companyMsg = new TTemporaryFile();
                companyMsg.setFileName(originalFilename);
                companyMsg.setCreateBy(loginUser.getUser().getUserName());
                companyMsg.setCreateTime(new Date());
                for (int a = 0; a < rows.getPhysicalNumberOfCells(); a++) {
                    Cell cell = rows.getCell(a);
                    if (cell == null) {
                        continue;
                    }
                    String value = filter(sheet.getRow(0), CellReference.convertNumToColString(cell.getColumnIndex()));
                    switch (value) {
                        case "箱号":
                            //设置单元格类型
                            cell.setCellType(CellType.STRING);
                            if (StringUtils.isEmpty(cell.getStringCellValue())) {
                                /*TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                                return AjaxResult.success("Excel箱信息数据第" + line + "行数据缺少箱号",500);*/
                                break;
                            }
                            companyMsg.setfCntrno(cell.getStringCellValue());
                            //判断箱号是否存在
                            TCntrno tCntrno = tCntrnoMapper.selectTCnTrNoByfNo(cell.getStringCellValue());
                            if (tCntrno == null) {
                                tCnTrNoList.add(cell.getStringCellValue());
                            } else {
                                if (tCntrno.getfTypeid() != null && !Objects.equals(tCntrno.getfTypeid(), tWarehousebillsCntr.getfCntrid())) {
                                    List.add(cell.getStringCellValue());
                                }
                            }
                            break;
                        case "铅封号":
                            //设置单元格类型
                            cell.setCellType(CellType.STRING);
                            if (StringUtils.isEmpty(cell.getStringCellValue())) {
                                /*TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                                return AjaxResult.success("Excel箱信息数据第" + line + "行数据缺少封号",500);*/
                                break;
                            }
                            companyMsg.setfSealno(cell.getStringCellValue());
                            break;
                        case "单箱重(不得超过40)":
                            //设置单元格类型
                            cell.setCellType(CellType.STRING);
                            if (StringUtils.isEmpty(cell.getStringCellValue())) {
                                /*TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                                return AjaxResult.success("Excel箱信息数据第" + line + "行数据缺少单箱重",500);*/
                                break;
                            }
                            companyMsg.setfCntrweight(new BigDecimal(cell.getStringCellValue()));
                            break;
                       /* case "货名":
                            //设置单元格类型
                            cell.setCellType(CellType.STRING);
                            if (StringUtils.isEmpty(cell.getStringCellValue())) {
                                *//*TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                                return AjaxResult.success("Excel箱信息数据第" + line + "行数据缺少货名",500);*//*
                                break;
                            }
                            companyMsg.setGoodsName(cell.getStringCellValue());
                            *//*TGoods tGoods = tGoodsMapper.checkUFNnameUnique(companyMsg.getGoodsName());
                            if (tGoods != null && tGoods.getfId() != null) {
                                companyMsg.setfGoodsid(tGoods.getfId());
                            }*//*
                            break;
                        case "包装类型":
                            //设置单元格类型
                            cell.setCellType(CellType.STRING);
                            if (StringUtils.isEmpty(cell.getStringCellValue())) {
                                *//*TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                                return AjaxResult.success("Excel箱信息数据第" + line + "行数据缺少包装类型",500);*//*
                                break;
                            }
                            companyMsg.setPackageName(cell.getStringCellValue());
                            *//*String fPackageid = sysDictDataMapper.selectDictValue("f_packageid", companyMsg.getPackageName());
                            if (StringUtils.isNotEmpty(fPackageid)) {
                                companyMsg.setfPackageid(fPackageid);
                            }*//*
                            break;
                        case "箱型":
                            //设置单元格类型
                            cell.setCellType(CellType.STRING);
                            if (StringUtils.isEmpty(cell.getStringCellValue())) {
                               *//* TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                                return AjaxResult.success("Excel箱信息数据第" + line + "行数据缺少箱型",500);*//*
                                break;
                            }
                            TCntrno cnTrNo = tCntrnoMapper.selectTCnTrNoByfNo(companyMsg.getfCntrno());
                            if (cnTrNo != null && cnTrNo.getTypeidName().equals(cell.getStringCellValue())) {
                                if (tCntr.getfNo().equals(cell.getStringCellValue())) {
                                    companyMsg.setCntrName(cell.getStringCellValue());
                                } else {
                                    List.add(companyMsg.getfCntrno());
                                    break;
                                }
                            } else if (cnTrNo != null && !cnTrNo.getTypeidName().equals(cell.getStringCellValue())) {
                                List.add(companyMsg.getfCntrno());
                                break;
                            }
                            *//*Long fId = tCntrMapper.selectRcntrFId(companyMsg.getCntrName());
                            if (fId != null) {
                                companyMsg.setfCntrid(fId);
                            }*//*
                            break;*/
                    }
                }
                if (StringUtils.isNotEmpty(companyMsg.getfCntrno())) {
                    tTemporaryFileMapper.insertTTemporaryFile(companyMsg);
                }
                fleetCompanyMsgs.add(companyMsg);
            }
        } catch (IOException e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("上传文件失败,请检查文件是否损坏");
        }
        if (CollectionUtils.isNotEmpty(tCnTrNoList) || CollectionUtils.isNotEmpty(List)) {
            tTemporaryFileMapper.deleteTTemporaryFilefileName(originalFilename, loginUser.getUser().getUserName());
            if (CollectionUtils.isNotEmpty(tCnTrNoList)) {
                StringBuffer stringBuffer = new StringBuffer("箱号不存在的有:" + "\n");
                stringBuffer.append(org.apache.commons.lang.StringUtils.join(tCnTrNoList.toArray(), ","));
                map.put("tCnTrNoList", stringBuffer.toString());
            }
            if (CollectionUtils.isNotEmpty(tCnTrNoList) && CollectionUtils.isNotEmpty(List)) {
                StringBuffer stringBuffer = new StringBuffer("箱型应为:" + tCntr.getfNo() + ",不一致的有" + "\n");
                stringBuffer.append(org.apache.commons.lang.StringUtils.join(List.toArray(), ","));
                map.put("List", stringBuffer.toString());
            } else if (CollectionUtils.isEmpty(tCnTrNoList) && CollectionUtils.isNotEmpty(List)) {
                StringBuffer stringBuffer = new StringBuffer("箱型应为:" + tCntr.getfNo() + ",不一致的有" + "\n");
                stringBuffer.append(org.apache.commons.lang.StringUtils.join(List.toArray(), ","));
                map.put("List", stringBuffer.toString());
            }
            return AjaxResult.success("error", map);
        } else {
            map.put("total", fleetCompanyMsgs.size());
            map.put("fileName", originalFilename);
            return AjaxResult.success("success", map);
        }
    }

    /**
     * 提交仓库主表审批
     *
     * @param tWarehouseBills       主表信息
     * @param tWarehousebillsfeesCr 付款信息
     * @param tWarehousebillsfeesDr 收款信息
     * @param tWarehousebillsitems  仓储明细
     * @param tEnclosure            附件信息
     * @param tCntr                 箱型箱量
     * @param billsType             类型
     * @return 结果
     */
    @Override
    @Transactional
    public AjaxResult submitWarehousingApproval(String tWarehouseBills, String tWarehousebillsfeesCr, String tWarehousebillsfeesDr,
                                                String tWarehousebillsitems, String tEnclosure, String tCntr, String billsType) {
        Long fPid = null;
        boolean isApprove = false;
        SysUser user = SecurityUtils.getLoginUser().getUser();
        Long actId = queryWarehouseActId(billsType);
        if ("SJRK".equals(billsType) || "SJCK".equals(billsType)) {
            SysConfig sysConfig = queryWarehouseConfig(billsType);
            if (StringUtils.isNull(sysConfig)) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error("系统参数异常，未找到开启审批流参数");
            }
            if ("0".equals(sysConfig.getConfigValue())) {
                isApprove = true;
            }
        }
        TWarehouseBills warehouseBills = JSONArray.parseObject(tWarehouseBills, TWarehouseBills.class);
        if (isApprove) {
            warehouseBills.setWarehouseStatus(4L);
        } else {
            warehouseBills.setWarehouseStatus(6L);
        }
        Long timestamp = DateUtils.getTimestamp(new Date());
        warehouseBills.setfDateChanged(timestamp.toString() + (int) (Math.random() * 900) + 100);
        TWarehousebillsitems itemInFo = tWarehousebillsitemsMapper.selectItemQtyByFPid(warehouseBills.getfId());
        warehouseBills.setfQty(itemInFo.getfQty());
        warehouseBills.setfNetweight(itemInFo.getfNetweight());
        warehouseBills.setfGrossweight(itemInFo.getfGrossweight());
        // 仓库主表
        if (StringUtils.isNull(warehouseBills.getfId())) {
            return AjaxResult.error("请确认仓库信息是否保存");
        }
        fPid = warehouseBills.getfId();
        if (!"SJRK".equals(billsType)) {
            warehouseBills.setfChargedate(warehouseBills.getfBsdate());
        }
        warehouseBills.setfTimes(warehouseBills.getfTimes() + 1);
        warehouseBills.setUpdateTime(new Date());
        warehouseBills.setUpdateBy(user.getUserName());
        tEnclosureMapper.deleteByFPid(fPid);
        tWarehousebillsfeesMapper.deleteByFPid(fPid);
        tWarehousebillsitemsMapper.deleteByFPid(fPid);
        tWarehouseBillsMapper.updateTWarehousebills(warehouseBills);
        tWarehousebillsCntrMapper.deleteTWarehousebillsCntrfPid(fPid);
        // 仓储明细
        if (StringUtils.isNotEmpty(tWarehousebillsitems) && !"[]".equals(tWarehousebillsitems)) {
            JSONArray warehouseJSON = JSONArray.parseArray(tWarehousebillsitems);
            List<TWarehousebillsitems> warehousebillsitemsList = JSONObject.parseArray(warehouseJSON.toJSONString(), TWarehousebillsitems.class);
            int line = 0;
            for (TWarehousebillsitems wbItem : warehousebillsitemsList) {
                line++;
                if ("SJRK".equals(billsType) || "SJCK".equals(billsType) || WarehouseTypeEnum.CKDB.getType().equals(billsType) || WarehouseTypeEnum.HWTG.getType().equals(billsType)) {
                    // 除了入库其他模块不需要更新主表的 仓储费计费日期到明细表，其他模块 应从库存总账把仓储费计费日期 赋给明细表
                    if ("SJRK".equals(billsType)) {
                        wbItem.setfMblno(warehouseBills.getfMblno());
                        wbItem.setfBillingway(warehouseBills.getfBillingway());
                        wbItem.setfChargedate(warehouseBills.getfChargedate());
                        wbItem.setfOriginalbilldate(warehouseBills.getfBsdate());
                        wbItem.setfMblno(warehouseBills.getfMblno());// 入库更新库存前执行update更新明细的提单号等于主表的提单号
                    }
                }
                if (StringUtils.isNull(wbItem.getfChargedate())) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error("库存明细第" + line + "行未找到仓储费计费日期，请确认");
                }
                if (StringUtils.isNull(wbItem.getfBillingway())) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error("库存明细第" + line + "行未找到计费方式，请确认");
                }
                if (StringUtils.isNull(wbItem.getfOriginalbilldate())) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error("库存明细第" + line + "行未找到原始入库日期，请确认");
                }
                wbItem.setfPid(fPid);
                wbItem.setfBilltype(billsType);
                wbItem.setCreateTime(new Date());
                wbItem.setfBillno(warehouseBills.getfBillno());
                wbItem.setCreateBy(user.getUserName());
                tWarehousebillsitemsMapper.insertTWarehousebillsitems(wbItem);
            }
        }
        //  箱型数据
        if (StringUtils.isNotNull(tCntr) && !"[]".equals(tCntr)) {
            JSONArray jsonDrArray = JSONArray.parseArray(tCntr);
            List<TWarehousebillsCntr> tWarehousebillsCntrs = JSONObject.parseArray(jsonDrArray.toJSONString(), TWarehousebillsCntr.class);
            int cntrLine = 0;
            for (TWarehousebillsCntr cntr : tWarehousebillsCntrs) {
                cntrLine++;
                if (StringUtils.isNull(cntr.getfCntrid()) || StringUtils.isNull(cntr.getfCntrcount()) || cntr.getfCntrcount() == 0) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error("箱型数据第" + cntrLine + "行数据缺少必填数据");
                }
                cntr.setfPid(fPid);
                cntr.setfGoodsid(0L);
                cntr.setfPackageid("0");
                cntr.setCreateTime(new Date());
                cntr.setCreateBy(user.getUserName());
                cntr.setfCntrweight(new BigDecimal(0));
                tWarehousebillsCntrMapper.insertTWarehousebillsCntr(cntr);
            }
        }
        if (StringUtils.isNotNull(tWarehousebillsfeesCr) && !"[]".equals(tWarehousebillsfeesCr)) {
            JSONArray jsonCrArray = JSONArray.parseArray(tWarehousebillsfeesCr);
            List<TWarehousebillsfees> warehousebillsfeesCrList = JSONObject.parseArray(jsonCrArray.toJSONString(), TWarehousebillsfees.class);
            for (TWarehousebillsfees wbCr : warehousebillsfeesCrList) {
                wbCr.setfPid(fPid);
                wbCr.setfDc("C");
                wbCr.setfBilltype(billsType);
                wbCr.setCreateTime(new Date());
                wbCr.setSrcBillNo(warehouseBills.getfBillno());
                wbCr.setCreateBy(user.getUserName());
                wbCr.setfChargedate(warehouseBills.getfChargedate());
                wbCr.setfBillingDeadline(warehouseBills.getfChargedate());
                if (StringUtils.isNotNull(warehouseBills.getfBsdate())) {
                    wbCr.setfBsdate(warehouseBills.getfBsdate());
                }
                tWarehousebillsfeesMapper.insertTWarehousebillsfees(wbCr);
            }
        }
        if (StringUtils.isNotNull(tWarehousebillsfeesDr) && !"[]".equals(tWarehousebillsfeesDr)) {
            JSONArray jsonCrArray = JSONArray.parseArray(tWarehousebillsfeesDr);
            List<TWarehousebillsfees> warehousebillsfeesDrList = JSONObject.parseArray(jsonCrArray.toJSONString(), TWarehousebillsfees.class);
            for (TWarehousebillsfees wbDr : warehousebillsfeesDrList) {
                wbDr.setfPid(fPid);
                wbDr.setfDc("D");
                wbDr.setfBillstatus(4L);
                wbDr.setfBilltype(billsType);
                wbDr.setCreateTime(new Date());
                wbDr.setSrcBillNo(warehouseBills.getfBillno());
                wbDr.setCreateBy(user.getUserName());
                wbDr.setfChargedate(warehouseBills.getfChargedate());
                wbDr.setfBillingDeadline(warehouseBills.getfChargedate());
                if (StringUtils.isNotNull(warehouseBills.getfBsdate())) {
                    wbDr.setfBsdate(warehouseBills.getfBsdate());
                }
                tWarehousebillsfeesMapper.insertTWarehousebillsfees(wbDr);
            }
        }
        if (StringUtils.isNotNull(tEnclosure) && !"[]".equals(tEnclosure)) {
            JSONArray jsonEnclosureArray = JSONArray.parseArray(tEnclosure);
            List<TEnclosure> enclosuresList = JSONObject.parseArray(jsonEnclosureArray.toJSONString(), TEnclosure.class);
            long lineNo = 0L;
            for (TEnclosure enclosure : enclosuresList) {
                lineNo++;
                enclosure.setfPid(fPid);
                enclosure.setfLineno(lineNo);
                enclosure.setCreateTime(new Date());
                enclosure.setCreateBy(user.getUserName());
                tEnclosureMapper.insertTEnclosure(enclosure);
            }
        }
        // 这里加个判断取系统参数来确定是否需要启用审批流
        if (isApprove) {
            AuditItems auditItems = new AuditItems();
            auditItems.setLevelId(0L);
            auditItems.setBillId(fPid);
            auditItems.setActId(actId);
            auditItems.setIffinalItem("F");
            auditItems.setBillNo(warehouseBills.getfBillno());
            // 存储委托方（货权方）
            auditItems.setRefno1(warehouseBills.getfCorpid() + "");
            // 存储业务类型（业务类型）
            auditItems.setRefno2(warehouseBills.getfBilltype());
            // 存储提单号（提单号）
            auditItems.setRefno3(warehouseBills.getfMblno());
            auditItems.setSendUserId(user.getUserId());
            auditItems.setSendName(user.getUserName());
            auditItems.setSendTime(new Date());
            auditItems.setAuditUserId(user.getUserId());
            auditItems.setAuditItem(new Date());
            auditItems.setAuditOpTime(new Date());
            auditItems.setAuditMsg("提交");
            auditItems.setAuditStatus("O");
            auditItems.setFidStatus("warehouse_status");
            auditItems.setTimes(warehouseBills.getfTimes());
            AjaxResult approvalFlow = auditItemsService.createApprovalFlow(auditItems);
            String code = approvalFlow.get("code").toString();
            if ("500".equals(code)) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
            return approvalFlow;
        }
        return AjaxResult.success();
    }

    /**
     * app仓储新行提交业务
     *
     * @param item    仓库明细数据
     * @param attachs 附件
     * @return 结果
     */
    @Override
    @Transactional
    public AjaxResult saveWarehouse(String item, String attachs) {
        TWarehousebillsitems warehousebillsitems = JSONArray.parseObject(item, TWarehousebillsitems.class);
        if (StringUtils.isNull(warehousebillsitems.getfPid())) {
            return AjaxResult.error("未找到主表id信息，请确认");
        }
        TWarehouseBills warehouseBills = tWarehouseBillsMapper.selectTWarehousebillsById(warehousebillsitems.getfPid());
        if (StringUtils.isNotNull(warehousebillsitems.getfGoodsid())) {
            TGoods goods = tGoodsMapper.selectTGoodsById(warehousebillsitems.getfGoodsid());
            if (!warehouseBills.getfProductName().contains(goods.getfName())) {
                warehouseBills.setfProductName(warehouseBills.getfProductName() + "/" + goods.getfName());
            }
        }
        if (StringUtils.isNotNull(warehouseBills.getfMarks())) {
            if (!warehouseBills.getfMarks().contains(warehousebillsitems.getfMarks())) {
                warehouseBills.setfMarks(warehouseBills.getfMarks() + "/" + warehousebillsitems.getfMarks());
            }
        }
        if (!"SJRK".equals(warehouseBills.getfBilltype())) {
            if (!warehouseBills.getfMblno().contains(warehousebillsitems.getfMblno())) {
                warehouseBills.setfMblno(warehouseBills.getfMblno() + "/" + warehousebillsitems.getfMblno());
            }
        }
        Long timestamp = DateUtils.getTimestamp(new Date());
        warehouseBills.setfDateChanged(timestamp.toString() + (int) (Math.random() * 900) + 100);
        warehouseBills.setfItemsStatus(1L);
        warehouseBills.setUpdateTime(new Date());
        warehouseBills.setUpdateBy(SecurityUtils.getUsername());
        TWarehousebillsitems itemInFo = tWarehousebillsitemsMapper.selectItemQtyByFPid(warehouseBills.getfId());
        warehouseBills.setfQty(itemInFo.getfQty());
        warehouseBills.setfNetweight(itemInFo.getfNetweight());
        warehouseBills.setfGrossweight(itemInFo.getfGrossweight());
        tWarehouseBillsMapper.updateTWarehousebills(warehouseBills);
        warehousebillsitems.setfBillstatus(10L);
        warehousebillsitems.setCreateTime(new Date());
        warehousebillsitems.setCreateBy(SecurityUtils.getUsername());
        tWarehousebillsitemsMapper.insertTWarehousebillsitems(warehousebillsitems);
        tEnclosureMapper.deleteByFPid(warehousebillsitems.getfPid());
        if (StringUtils.isNotEmpty(attachs) && !"[]".equals(attachs)) {
            //  附件添加
            if (StringUtils.isNotEmpty(attachs) && !"[]".equals(attachs)) {
                JSONArray jsonDrArray = JSONArray.parseArray(attachs);
                List<TEnclosure> tEnclosureList = JSONObject.parseArray(jsonDrArray.toJSONString(), TEnclosure.class);
                for (TEnclosure enclosure : tEnclosureList) {
                    enclosure.setfStatus("2");
                    enclosure.setCreateTime(new Date());
                    enclosure.setfPid(warehousebillsitems.getfPid());
                    enclosure.setCreateBy(SecurityUtils.getUsername());
                    tEnclosureMapper.insertTEnclosure(enclosure);
                }
            }
        }
        return AjaxResult.success();
    }

    /**
     * 查询提单号是否在一天当中出现多次
     *
     * @param tWarehouseBills 仓库数据
     * @return 结果
     */
    @Override
    public AjaxResult selectContainMblno(String tWarehouseBills, String billsType) {
        TWarehouseBills warehouseBills = JSONArray.parseObject(tWarehouseBills, TWarehouseBills.class);
        warehouseBills.setfBilltype(billsType);
        String mblno = warehouseBills.getfMblno();
        Date bsdate = warehouseBills.getfBsdate();
        int count = tWarehouseBillsMapper.selectContainMblno(warehouseBills);
        if (count > 1) {
            return AjaxResult.success("提单号：" + mblno + ",日期：" + DateUtils.dateTime(bsdate) + ",出现" + count + "次", false);
        }
        return AjaxResult.success(true);
    }

    @Override
    public List<TWarehouseBills> webVersionOrder(TWarehouseBills tWarehouseBills) {
        List<TWarehouseBills> warehouseBills = tWarehouseBillsMapper.webVersionOrderList(tWarehouseBills);
        if (CollectionUtils.isNotEmpty(warehouseBills)) {
            for (TWarehouseBills warehouseBill : warehouseBills) {
                //货物信息
                TWarehousebillsCntr warehousebillsCntr = new TWarehousebillsCntr();
                warehousebillsCntr.setfPid(warehouseBill.getfId());
                List<TWarehousebillsCntr> tWarehousebillsCntrs = tWarehousebillsCntrMapper.selectTWarehousebillsCntrList(warehousebillsCntr);
                if (CollectionUtils.isNotEmpty(tWarehousebillsCntrs)) {
                    warehouseBill.settWarehousebillsCntrList(tWarehousebillsCntrs);
                }
                //箱信息
                TWarehousebillsCntritems warehousebillsCntritems = new TWarehousebillsCntritems();
                warehousebillsCntritems.setfPid(warehouseBill.getfId());
                List<TWarehousebillsCntritems> tWarehousebillsCntritems = tWarehousebillsCntritemsMapper.selectTWarehousebillsCntritemsList(warehousebillsCntritems);
                if (CollectionUtils.isNotEmpty(tWarehousebillsCntritems)) {
                    warehouseBill.settWarehousebillsCntritemsList(tWarehousebillsCntritems);
                }
                //航线信息
                TVoyage tVoyage = tVoyageMapper.selectTVoyageById(warehouseBill.getfVoyid());
                warehouseBill.settVoyageL(tVoyage);
                //应收信息
                List<TWarehousebillsfees> tWarehousebillsfeesDr = tWarehousebillsfeesMapper.selectFeesByPId(warehouseBill.getfId(), "D");
                if (CollectionUtils.isNotEmpty(tWarehousebillsfeesDr)) {
                    warehouseBill.settWarehousebillsfeesDr(tWarehousebillsfeesDr);
                }
            }
        }
        return warehouseBills;
    }

    @Override
    public List<TWarehouseBills> webVersionOrderMessage(TWarehouseBills tWarehouseBills) {
        return tWarehouseBillsMapper.webVersionOrderList(tWarehouseBills);
    }

    @Override
    public List<Map<String, Object>> ruoYiVersionOrderList(LoginUser loginUser, TWarehouseBills tWarehouseBills) {
        //tWarehouseBills.setCreateBy(loginUser.getUser().getUserName());
        return tWarehouseBillsMapper.ruoYiVersionOrderList(tWarehouseBills);
    }

    @Override
    public List<Map<String, Object>> webVersionOrderMessage(LoginUser loginUser, TWarehouseBills tWarehouseBills) {
        TWarehouseBills warehouseBills = new TWarehouseBills();
        if (tWarehouseBills != null) {
            BeanUtil.copyProperties(tWarehouseBills, warehouseBills);
            warehouseBills.setCreateBy(loginUser.getUser().getUserName());
        } else {
            warehouseBills.setCreateBy(loginUser.getUser().getUserName());
        }
        return tWarehouseBillsMapper.ruoYiVersionOrderList1(warehouseBills);
    }

    @Override
    public List<TWarehouseBills> webVersionOrderDetails(TWarehouseBills tWarehouseBills) {
        List<TWarehouseBills> warehouseBills = tWarehouseBillsMapper.webVersionOrderById(tWarehouseBills);
        if (CollectionUtils.isNotEmpty(warehouseBills)) {
            for (TWarehouseBills warehouseBill : warehouseBills) {
                //货物信息
                TWarehousebillsCntr warehousebillsCntr = new TWarehousebillsCntr();
                warehousebillsCntr.setfPid(warehouseBill.getfId());
                List<TWarehousebillsCntr> tWarehousebillsCntrs = tWarehousebillsCntrMapper.selectTWarehousebillsCntrList(warehousebillsCntr);
                if (CollectionUtils.isNotEmpty(tWarehousebillsCntrs)) {
                    warehouseBill.settWarehousebillsCntrList(tWarehousebillsCntrs);
                }
                //配箱信息
                TWarehousebillsCntritems warehousebillsCntritems = new TWarehousebillsCntritems();
                warehousebillsCntritems.setfPid(warehouseBill.getfId());
                List<TWarehousebillsCntritems> tWarehousebillsCntritems = tWarehousebillsCntritemsMapper.selectTWarehousebillsCntritemsList(warehousebillsCntritems);
                if (CollectionUtils.isNotEmpty(tWarehousebillsCntritems)) {
                    warehouseBill.settWarehousebillsCntritemsList(tWarehousebillsCntritems);
                }
                //航次信息
                TVoyage tVoyage = tVoyageMapper.selectTVoyageById(warehouseBill.getfVoyid());
                warehouseBill.settVoyageL(tVoyage);
                //应收信息
                List<TWarehousebillsfees> tWarehousebillsfeesDr = tWarehousebillsfeesMapper.selectFeesByPId(warehouseBill.getfId(), "D");
                warehouseBill.settWarehousebillsfeesDr(tWarehousebillsfeesDr);
                //应付信息
                List<TWarehousebillsfees> warehousebillsfeesCr = tWarehousebillsfeesMapper.selectFeesByPId(warehouseBill.getfId(), "C");
                warehouseBill.setWarehousebillsfeesCr(warehousebillsfeesCr);
                if (CollectionUtils.isNotEmpty(tWarehousebillsfeesDr)) {
                    warehouseBill.setMoneyStatus(tWarehousebillsfeesDr.get(0).getfBillstatus());
                } else if (CollectionUtils.isNotEmpty(warehousebillsfeesCr)) {
                    warehouseBill.setMoneyStatus(warehousebillsfeesCr.get(0).getfBillstatus());
                }
            }
        }
        return warehouseBills;
    }

    @Override
    @Transactional
    public AjaxResult ruoYiUpdateOrderMessage(String tWarehousebills, String tWarehousebillsCntr, String tWarehousebillsCntritems, String tWarehousebillsfeesCr,
                                              String tWarehousebillsfeesDr, LoginUser loginUser, String billsType) {
        TWarehouseBills warehouseBills = JSONArray.parseObject(tWarehousebills, TWarehouseBills.class);
        Map<String, Object> map = new HashMap<>();
        if (StringUtils.isEmpty(warehouseBills.getfMblno())) {
            return AjaxResult.error("提单号不能为空");
        }
        TWarehouseBills mblno = tWarehouseBillsMapper.selectTWarehousebillsfMblno(warehouseBills);
        if (StringUtils.isNotNull(mblno) && !mblno.getfId().equals(warehouseBills.getfId())) {
            return AjaxResult.error("提单号已存在，请重新提交");
        }
        TWarehouseBills tWarehouseBills = tWarehouseBillsMapper.selectTWarehousebillsById(warehouseBills.getfId());
       /* if (tWarehouseBills.getfBillstatus() != 11L) {
            return AjaxResult.error("订单未审核完成，暂不支持维护提单号");
        }*/
        TWarehouseBills bills = new TWarehouseBills();
        /*bills.setfId(warehouseBills.getfId());
        bills.setfMblno(warehouseBills.getfMblno());*/
        Integer integer = tWarehouseBillsMapper.updateTWarehousebills(warehouseBills);
        if (integer <= 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("维护提单号失败,请联系管理员");
        }
        List<TWarehouseBills> warehouseBillsList = tWarehouseBillsMapper.webVersionOrderById(warehouseBills);
        map.put("tWarehouseBills", warehouseBillsList.get(0));
        int cntritemsfPid = tWarehousebillsCntritemsMapper.deleteTWarehousebillsCntritemsfPid(warehouseBills.getfId());
        if (StringUtils.isNotEmpty(tWarehousebillsCntritems)) {
            JSONArray jsonCrArray = JSONArray.parseArray(tWarehousebillsCntritems);
            List<TWarehousebillsCntritems> tWarehousebillsCntritemsList = JSONObject.parseArray(jsonCrArray.toJSONString(), TWarehousebillsCntritems.class);
            //获取货物信息
            TWarehousebillsCntr warehousebillsCntr = tWarehousebillsCntrMapper.selectTWarehousebillsCntrByPId(warehouseBills.getfId());
            if (warehousebillsCntr.getfCntrcount() < tWarehousebillsCntritemsList.size()) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error("箱信息中的箱量大于货物信息中的箱量");
            }
            if (CollectionUtils.isNotEmpty(tWarehousebillsCntritemsList)) {
                for (TWarehousebillsCntritems warehousebillsCntritems : tWarehousebillsCntritemsList) {
                    AjaxResult ajaxResult = this.judgeBoxPile(warehousebillsCntritems, warehousebillsCntr.getfCntrid());
                    String code = ajaxResult.get("code").toString();
                    if ("500".equals(code)) {
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return ajaxResult;
                    }
                    //先查箱号是否在对应的订单中存在存在不保存
                    TWarehousebillsCntritems cntritems = new TWarehousebillsCntritems();
                    cntritems.setfPid(warehouseBills.getfId());
                    cntritems.setfCntrno(warehousebillsCntritems.getfCntrno());
                    List<TWarehousebillsCntritems> list = tWarehousebillsCntritemsMapper.selectTWarehousebillsCntritemsList(cntritems);
                    if (CollectionUtils.isNotEmpty(list)) {
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return AjaxResult.error("箱号" + warehousebillsCntritems.getfCntrno() + "重复,请修改");
                    }
                    warehousebillsCntritems.setfPid(warehouseBills.getfId());
                    warehousebillsCntritems.setCreateTime(DateUtils.getNowDate());
                    warehousebillsCntritems.setCreateBy(SecurityUtils.getUsername());
                    int cntr = tWarehousebillsCntritemsMapper.insertTWarehousebillsCntritems(warehousebillsCntritems);
                }
            }
            map.put("tWarehousebillsCntritemsList", tWarehousebillsCntritemsList);
        }
        TWarehousebillsfees warehousebillsfees = new TWarehousebillsfees();
        warehousebillsfees.setfPid(warehouseBills.getfId());
        List<TWarehousebillsfees> tWarehousebillsfees = tWarehousebillsfeesMapper.selectTWarehousebillsfeesList(warehousebillsfees);
        if (CollectionUtils.isNotEmpty(tWarehousebillsfees)) {
            Long aLong = tWarehousebillsfees.get(0).getfBillstatus();
            if (aLong == 4L || aLong == 5L) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error("订单费用审核中，不支持修改");
            }
            if (aLong == 6L) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error("订单费用审核通过，不支持修改");
            }
        }
        int c = tWarehousebillsfeesMapper.deleteFessByFPid(warehouseBills.getfId(), "C");
        if (StringUtils.isNotNull(tWarehousebillsfeesCr) && !"[]".equals(tWarehousebillsfeesCr)) {
            JSONArray jsonCrArray = JSONArray.parseArray(tWarehousebillsfeesCr);
            List<TWarehousebillsfees> warehousebillsfeesCrList = JSONObject.parseArray(jsonCrArray.toJSONString(), TWarehousebillsfees.class);
            for (TWarehousebillsfees wbCr : warehousebillsfeesCrList) {
                wbCr.setfPid(warehouseBills.getfId());
                wbCr.setfDc("C");
                wbCr.setfBilltype(billsType);
                wbCr.setCreateTime(new Date());
                wbCr.setSrcBillNo(tWarehouseBills.getfBillno());
                wbCr.setCreateBy(loginUser.getUser().getUserName());
                //wbCr.setfChargedate(warehouseBills.getfChargedate());
                //wbCr.setfBillingDeadline(warehouseBills.getfChargedate());
                if (warehouseBills.getfBsdate() != null && !warehouseBills.getfBsdate().equals("")) {
                    wbCr.setfBsdate(warehouseBills.getfBsdate());
                }
                tWarehousebillsfeesMapper.insertTWarehousebillsfees(wbCr);
            }
            map.put("warehousebillsfeesCrList", warehousebillsfeesCrList);
        }
        int d = tWarehousebillsfeesMapper.deleteFessByFPid(warehouseBills.getfId(), "D");
        if (StringUtils.isNotNull(tWarehousebillsfeesDr) && !"[]".equals(tWarehousebillsfeesDr)) {
            JSONArray jsonCrArray = JSONArray.parseArray(tWarehousebillsfeesDr);
            List<TWarehousebillsfees> warehousebillsfeesDrList = JSONObject.parseArray(jsonCrArray.toJSONString(), TWarehousebillsfees.class);
            for (TWarehousebillsfees wbDr : warehousebillsfeesDrList) {
                wbDr.setfPid(warehouseBills.getfId());
                wbDr.setfDc("D");
                wbDr.setfBilltype(billsType);
                wbDr.setCreateTime(new Date());
                wbDr.setSrcBillNo(tWarehouseBills.getfBillno());
                wbDr.setCreateBy(loginUser.getUser().getUserName());
                //wbDr.setfChargedate(warehouseBills.getfChargedate());
                //wbDr.setfBillingDeadline(warehouseBills.getfChargedate());
                if (warehouseBills.getfBsdate() != null && !warehouseBills.getfBsdate().equals("")) {
                    wbDr.setfBsdate(warehouseBills.getfBsdate());
                }
                tWarehousebillsfeesMapper.insertTWarehousebillsfees(wbDr);
            }
            map.put("warehousebillsfeesDrList", warehousebillsfeesDrList);
        }
        int i = tWarehousebillsCntrMapper.deleteTWarehousebillsCntrfPid(warehouseBills.getfId());
        if (StringUtils.isNotEmpty(tWarehousebillsCntr) && !"[]".equals(tWarehousebillsCntr)) {
            JSONArray jsonCrArray = JSONArray.parseArray(tWarehousebillsCntr);
            List<TWarehousebillsCntr> tWarehousebillsCntrList = JSONObject.parseArray(jsonCrArray.toJSONString(), TWarehousebillsCntr.class);
            if (CollectionUtils.isNotEmpty(tWarehousebillsCntrList)) {
                for (TWarehousebillsCntr warehousebillsCntr : tWarehousebillsCntrList) {
                    warehousebillsCntr.setfPid(warehouseBills.getfId());
                    warehousebillsCntr.setCreateTime(DateUtils.getNowDate());
                    warehousebillsCntr.setCreateBy(SecurityUtils.getUsername());
                    int cntr = tWarehousebillsCntrMapper.insertTWarehousebillsCntr(warehousebillsCntr);
                }
            }
            map.put("tWarehousebillsCntrList", tWarehousebillsCntrList);
        }
        return AjaxResult.success("success", map);
    }

    @Override
    @Transactional
    public AjaxResult ruoYiSubmitMessage(String tWarehousebills, String tWarehousebillsCntr, String tWarehousebillsCntritems, String tWarehousebillsfeesCr,
                                         String tWarehousebillsfeesDr, LoginUser loginUser, String billsType) {
        boolean isApprove = false;
        String key = "";
        long actId = 0L;
        Long billStatus = null;
        if ("KHDD".equals(billsType)) {
            actId = 460L;
            key = "warehouse.khSubmitMoney.ApprovalFlow";
        }
        SysConfig sysConfig = sysConfigMapper.checkConfigKeyUnique(key);
        if (StringUtils.isNull(sysConfig)) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("系统参数异常，未找到开启审批流参数");
        }
        if ("0".equals(sysConfig.getConfigValue())) {
            isApprove = true;
        }
        if (isApprove) {
            billStatus = 4L;
        } else {
            billStatus = 6L;
        }
        TWarehouseBills warehouseBills = JSONArray.parseObject(tWarehousebills, TWarehouseBills.class);
        Map<String, Object> map = new HashMap<>();
        if (StringUtils.isEmpty(warehouseBills.getfMblno())) {
            return AjaxResult.error("提单号不能为空");
        }
        TWarehouseBills mblno = tWarehouseBillsMapper.selectTWarehousebillsfMblno(warehouseBills);
        if (StringUtils.isNotNull(mblno) && !mblno.getfId().equals(warehouseBills.getfId())) {
            return AjaxResult.error("提单号已存在，请重新提交");
        }
        AjaxResult ajaxResult = this.changeFees(warehouseBills.getfId());
        String codeMessage = ajaxResult.get("code").toString();
        if ("500".equals(codeMessage)) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ajaxResult;
        }
        TWarehouseBills tWarehouseBills = tWarehouseBillsMapper.selectTWarehousebillsById(warehouseBills.getfId());
        if (tWarehouseBills.getfBillstatus() != 11L) {
            return AjaxResult.error("订单未审核完成，暂不支持维护提单号");
        }
        warehouseBills.setfTimes(tWarehouseBills.getfTimes() + 1);
        /*TWarehouseBills bills = new TWarehouseBills();
        bills.setfId(warehouseBills.getfId());
        bills.setfMblno(warehouseBills.getfMblno());*/
        Integer integer = tWarehouseBillsMapper.updateTWarehousebills(warehouseBills);
        map.put("tWarehouseBills", tWarehouseBills);
        if (StringUtils.isNotEmpty(tWarehousebillsCntritems)) {
            JSONArray jsonCrArray = JSONArray.parseArray(tWarehousebillsCntritems);
            List<TWarehousebillsCntritems> tWarehousebillsCntritemsList = JSONObject.parseArray(jsonCrArray.toJSONString(), TWarehousebillsCntritems.class);
            if (CollectionUtils.isNotEmpty(tWarehousebillsCntritemsList)) {
                int cntritemsfPid = tWarehousebillsCntritemsMapper.deleteTWarehousebillsCntritemsfPid(warehouseBills.getfId());
                for (TWarehousebillsCntritems warehousebillsCntritems : tWarehousebillsCntritemsList) {
                    warehousebillsCntritems.setfPid(warehouseBills.getfId());
                    warehousebillsCntritems.setCreateTime(DateUtils.getNowDate());
                    warehousebillsCntritems.setCreateBy(SecurityUtils.getUsername());
                    int cntr = tWarehousebillsCntritemsMapper.insertTWarehousebillsCntritems(warehousebillsCntritems);

                }
            }
            map.put("tWarehousebillsCntritemsList", tWarehousebillsCntritemsList);
        }
        int c = tWarehousebillsfeesMapper.deleteFessByFPid(warehouseBills.getfId(), "C");
        if (StringUtils.isNotNull(tWarehousebillsfeesCr) && !"[]".equals(tWarehousebillsfeesCr)) {
            JSONArray jsonCrArray = JSONArray.parseArray(tWarehousebillsfeesCr);
            List<TWarehousebillsfees> warehousebillsfeesCrList = JSONObject.parseArray(jsonCrArray.toJSONString(), TWarehousebillsfees.class);
            for (TWarehousebillsfees wbCr : warehousebillsfeesCrList) {
                wbCr.setfPid(warehouseBills.getfId());
                wbCr.setfDc("C");
                wbCr.setfBilltype(billsType);
                wbCr.setfBillstatus(billStatus);
                wbCr.setCreateTime(new Date());
                wbCr.setSrcBillNo(tWarehouseBills.getfBillno());
                wbCr.setCreateBy(loginUser.getUser().getUserName());
                //wbCr.setfChargedate(warehouseBills.getfChargedate());
                //wbCr.setfBillingDeadline(warehouseBills.getfChargedate());
                if (warehouseBills.getfBsdate() != null && !warehouseBills.getfBsdate().equals("")) {
                    wbCr.setfBsdate(warehouseBills.getfBsdate());
                }
                tWarehousebillsfeesMapper.insertTWarehousebillsfees(wbCr);
            }
            map.put("warehousebillsfeesCrList", warehousebillsfeesCrList);
        }
        int d = tWarehousebillsfeesMapper.deleteFessByFPid(warehouseBills.getfId(), "D");
        if (StringUtils.isNotNull(tWarehousebillsfeesDr) && !"[]".equals(tWarehousebillsfeesDr)) {
            JSONArray jsonCrArray = JSONArray.parseArray(tWarehousebillsfeesDr);
            List<TWarehousebillsfees> warehousebillsfeesDrList = JSONObject.parseArray(jsonCrArray.toJSONString(), TWarehousebillsfees.class);
            for (TWarehousebillsfees wbDr : warehousebillsfeesDrList) {
                wbDr.setfPid(warehouseBills.getfId());
                wbDr.setfDc("D");
                wbDr.setfBillstatus(billStatus);
                wbDr.setfBilltype(billsType);
                wbDr.setCreateTime(new Date());
                wbDr.setSrcBillNo(tWarehouseBills.getfBillno());
                wbDr.setCreateBy(loginUser.getUser().getUserName());
                //wbDr.setfChargedate(warehouseBills.getfChargedate());
                //wbDr.setfBillingDeadline(warehouseBills.getfChargedate());
                if (warehouseBills.getfBsdate() != null && !warehouseBills.getfBsdate().equals("")) {
                    wbDr.setfBsdate(warehouseBills.getfBsdate());
                }
                tWarehousebillsfeesMapper.insertTWarehousebillsfees(wbDr);
            }
            map.put("warehousebillsfeesDrList", warehousebillsfeesDrList);
        }
        if (StringUtils.isNotEmpty(tWarehousebillsCntr) && !"[]".equals(tWarehousebillsCntr)) {
            JSONArray jsonCrArray = JSONArray.parseArray(tWarehousebillsCntr);
            List<TWarehousebillsCntr> tWarehousebillsCntrList = JSONObject.parseArray(jsonCrArray.toJSONString(), TWarehousebillsCntr.class);
            if (CollectionUtils.isNotEmpty(tWarehousebillsCntrList)) {
                int i = tWarehousebillsCntrMapper.deleteTWarehousebillsCntrfPid(warehouseBills.getfId());
                for (TWarehousebillsCntr warehousebillsCntr : tWarehousebillsCntrList) {
                    warehousebillsCntr.setfPid(warehouseBills.getfId());
                    warehousebillsCntr.setCreateTime(DateUtils.getNowDate());
                    warehousebillsCntr.setCreateBy(SecurityUtils.getUsername());
                    int cntr = tWarehousebillsCntrMapper.insertTWarehousebillsCntr(warehousebillsCntr);
                }
            }
            map.put("tWarehousebillsCntrList", tWarehousebillsCntrList);
        }
        if (isApprove) {
            AuditItems auditItems = new AuditItems();
            auditItems.setLevelId(0L);
            auditItems.setBillId(warehouseBills.getfId());
            auditItems.setActId(actId);
            auditItems.setIffinalItem("F");
            auditItems.setBillNo(tWarehouseBills.getfBillno());
            // 存储委托方（货权方）
            auditItems.setRefno1(tWarehouseBills.getfCorpid() + "");
            // 存储业务类型（业务类型）
            auditItems.setRefno2(tWarehouseBills.getfBilltype());
            // 存储提单号（提单号）
            auditItems.setRefno3(tWarehouseBills.getfMblno());
            auditItems.setSendUserId(loginUser.getUser().getUserId());
            auditItems.setSendName(SecurityUtils.getUsername());
            auditItems.setSendTime(new Date());
            auditItems.setAuditUserId(loginUser.getUser().getUserId());
            auditItems.setAuditItem(new Date());
            auditItems.setAuditOpTime(new Date());
            auditItems.setAuditMsg("提交");
            auditItems.setAuditStatus("O");
            auditItems.setFidStatus("f_billstatus");
            auditItems.setTimes(1L);
            AjaxResult approvalFlow = auditItemsService.createApprovalFlow(auditItems);
//            Long code = Long.valueOf(String.valueOf(approvalFlow.get("code"))).longValue();
            String code = approvalFlow.get("code").toString();
//                Long code = Long.valueOf(String.valueOf(ajaxResult.get("code"))).longValue();
            if ("500".equals(code)) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
            return approvalFlow;
        }
        return AjaxResult.success("success", map);
    }

    @Override
    public AjaxResult updateOrderMessage(TWarehouseBills tWarehouseBills) {
        TWarehouseBills mblno = tWarehouseBillsMapper.selectTWarehousebillsfMblno(tWarehouseBills);
        if (StringUtils.isNotNull(mblno) && !mblno.getfId().equals(tWarehouseBills.getfId())) {
            return AjaxResult.error("提单号已存在，请重新提交");
        }
        TWarehouseBills warehouseBills = tWarehouseBillsMapper.selectTWarehousebillsById(tWarehouseBills.getfId());
        if (warehouseBills.getfBillstatus() != 6L) {
            return AjaxResult.error("下单未审核完成，暂不支持维护提单号");
        }
        int i = tWarehouseBillsMapper.updateTWarehousebills(tWarehouseBills);
        if (i <= 0) {
            return AjaxResult.error("更新提单号出错,请找管理员");
        }
        return AjaxResult.success();
    }

    /**
     * app 查询业务主表信息
     *
     * @param warehouseBills
     * @return
     */
    @Override
    public List<Map<String, Object>> selectAppStockList(TWarehouseBills warehouseBills) {
        return tWarehouseBillsMapper.selectAppStockList(warehouseBills);
    }

    /**
     * app 根据主表id查询主表对应明细列表数据
     *
     * @param warehouseBills
     * @return
     */
    @Override
    public List<Map<String, Object>> warehouseItemById(TWarehouseBills warehouseBills) {
        return tWarehouseBillsMapper.selectWarehouseItemListById(warehouseBills);
    }

    /**
     * app 根据明细id查询对应明细表数据
     *
     * @param fId
     * @return
     */
    @Override
    public AjaxResult selectWarehouseItemDataById(Long fId) {
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> itemMap = tWarehousebillsitemsMapper.selectWarehouseItemsByPId(fId);
        if (StringUtils.isNull(itemMap) || !itemMap.containsKey("fPid")) {
            return AjaxResult.error("未找到库存明细数据，请确认该明细是否存在");
        }
        map.put("item", itemMap);
        if (itemMap.containsKey("fPid") && StringUtils.isNotNull(itemMap.get("fPid"))) {
            long fPid = Long.valueOf(String.valueOf(itemMap.get("fPid")));
            TWarehouseBills tWarehouseBills = tWarehouseBillsMapper.selectTWarehousebillsById(fPid);
            map.put("warehouseBills", tWarehouseBills);
            // 查询附件
            map.put("enclosure", tEnclosureMapper.selectTEnclosureByPId(tWarehouseBills.getfId()));
        }
        return AjaxResult.success(map);
    }

    /**
     * 查询app 添加新行 必要的基础资料
     *
     * @param fId
     * @return
     */
    @Override
    public AjaxResult getAppBasicInformation(Long fId) {
        Map<String, Object> map = new HashMap<>();
        TWarehouseBills tWarehouseBills = tWarehouseBillsMapper.selectTWarehousebillsById(fId);
        map.put("warehouseBills", tWarehouseBills);
        if (StringUtils.isNotNull(tWarehouseBills.getfLabour())) {
            TCorps corps = tCorpsMapper.selectTCorpsById(tWarehouseBills.getfLabour());
            if (StringUtils.isNotNull(corps)) {
                map.put("labourName", corps.getfName());
            }
        }
        if (StringUtils.isNotNull(tWarehouseBills.getfFleet())) {
            TCorps corps = tCorpsMapper.selectTCorpsById(tWarehouseBills.getfFleet());
            if (StringUtils.isNotNull(corps)) {
                map.put("fleetName", corps.getfName());
            }
        }
        if (StringUtils.isNotNull(tWarehouseBills.getfGoodsid())) {
            TGoods goods = tGoodsMapper.selectTGoodsById(tWarehouseBills.getfGoodsid());
            if (StringUtils.isNotNull(goods)) {
                map.put("goodsName", goods.getfName());
            }
        }
        // 查询劳务公司
        TCorps corps = new TCorps();
        corps.setfTypeid("\"6\"");
        corps.setfStatus("0");
        map.put("corpsList", tCorpsMapper.selectTCorpsList(corps));
        // 查询车队
        TCorps fleetCorp = new TCorps();
        corps.setfTypeid("\"2\"");
        fleetCorp.setfStatus("0");
        map.put("feelCorpList", tCorpsMapper.selectTCorpsList(fleetCorp));
        // 查询商品品名
        TGoods goods = new TGoods();
        goods.setfStatus("0");
        map.put("goodsList", tGoodsMapper.selectTGoodsList(goods));
        // 查询库区
        TWarehouse tWarehouse = new TWarehouse();
        tWarehouse.setAncestors(tWarehouseBills.getfWarehouseid() + "");
        List<TWarehouse> warehouses = tWarehouseMapper.selectTWarehouseList(tWarehouse);
        if (StringUtils.isNotEmpty(warehouses)) {
            map.put("warehouse", warehouseServiceImpl.buildDeptTreeSelect(warehouses));
        }
        map.put("attributes", sysDictDataMapper.selectDictDataByType("storage_type"));
        // 查询箱型数据
        TCntr tCntr = new TCntr();
        tCntr.setfStatus("T");
        map.put("cntrList", tCntrMapper.selectTCntrList(tCntr));
        return AjaxResult.success(map);
    }

    /**
     * app确认入库、出库、货转
     *
     * @param item    明细数据
     * @param attachs 附件数据
     * @return 结果
     */
    @Override
    @Transactional
    public AjaxResult warehouseOperationConfirmation(String item, String attachs) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        TWarehousebillsitems tWarehousebillsitems = JSONArray.parseObject(item, TWarehousebillsitems.class);
        if (StringUtils.isNull(tWarehousebillsitems.getfId()) || StringUtils.isNull(tWarehousebillsitems.getfPid())) {
            return AjaxResult.error("未找到仓库明细id，或未找到上级id，请确认");
        }
        // 查询主表
        TWarehouseBills warehouseBills = tWarehouseBillsMapper.selectTWarehousebillsById(tWarehousebillsitems.getfPid());
        if (StringUtils.isNull(warehouseBills.getfBsdate())) {
            return AjaxResult.error("库存明细请检查日期，操作终止");
        }
        if (StringUtils.isNull(warehouseBills.getfCorpid())) {
            return AjaxResult.error("库存明细请检查客户信息，操作终止");
        }
        warehouseBills.setfItemsStatus(4L);
        warehouseBills.setUpdateTime(new Date());
        warehouseBills.setUpdateBy(SecurityUtils.getUsername());
        Long timestamp = DateUtils.getTimestamp(new Date());
        warehouseBills.setfDateChanged(timestamp.toString() + (int) (Math.random() * 900) + 100);
        // 查询最新明细表
        TWarehousebillsitems warehousebillsitems = tWarehousebillsitemsMapper.selectTWarehousebillsitemsById(tWarehousebillsitems.getfId());
        String billsType = warehousebillsitems.getfBilltype();
        if ("SJRK".equals(billsType) && "0".equals(warehouseBills.getfChargetype()) && tWarehousebillsitems.getBsdate() != null) {
            boolean fchargedate = this.getFchargedate(warehousebillsitems.getfPid(), tWarehousebillsitems.getBsdate());
            if (!fchargedate) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error("入库日期不能小于最小仓储费计算日期");
            }
        }
        Date time = new Date();
        if (StringUtils.isNotEmpty(warehouseBills.getfChargetype()) && "0".equals(warehouseBills.getfChargetype())) {
            time = tWarehousebillsitemsMapper.selecMinBsDateByFPid(tWarehousebillsitems.getfPid());
            if (tWarehousebillsitems.getBsdate() != null) {
                tWarehousebillsitems.setfBsdate(tWarehousebillsitems.getBsdate());
            }
        } else if (StringUtils.isNotEmpty(warehouseBills.getfChargetype()) && "1".equals(warehouseBills.getfChargetype())) {
            if (tWarehousebillsitems.getBsdate() != null) {
                time = tWarehousebillsitems.getBsdate();
                tWarehousebillsitems.setfBsdate(tWarehousebillsitems.getBsdate());
            } else {
                time = warehousebillsitems.getfBsdate();
            }
        }
        tWarehousebillsitems.setfChargedate(time);//仓储费计算日期
        if (StringUtils.isNull(warehousebillsitems) || warehousebillsitems.getfBillstatus() != 30L) {
            return AjaxResult.error("请确认是该明细数据是否存在，或该明细数据状态异常");
        }
        TGoods goods = tGoodsMapper.selectTGoodsById(warehousebillsitems.getfGoodsid());
        if ("1".equals(goods.getIfCntrno()) && StringUtils.isNull(warehousebillsitems.getfCntrno())) {
            return AjaxResult.error("仓库明细第未找到箱号");
        }
        if ("SJRK".equals(billsType)) {
            tWarehousebillsitems.setfOriginalbilldate(warehousebillsitems.getfBsdate());//入库时间
            warehousebillsitems.setfOriginalbilldate(warehousebillsitems.getfBsdate());
            // 查询库容量  是否可入库
            int m = calculation(warehouseBills.getfWarehouseid(), warehousebillsitems.getfGrossweight());
            if (m == 0) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error("更新库存总账失败-->入库毛重大于库容");
            }
            TWhgenleg tWhgenle = queryTWhgenleg(warehouseBills, warehousebillsitems, goods.getIfCntrno());
            if (StringUtils.isNotNull(tWhgenle)) {
                int i = updateTWhgenlegData(tWarehousebillsitems, tWhgenle.getfId(), billsType);
                if (i <= 0) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error("更新库存总账失败");
                }
            } else {
                warehousebillsitems.setfQty(tWarehousebillsitems.getfQty());
                warehousebillsitems.setfGrossweight(tWarehousebillsitems.getfGrossweight());
                warehousebillsitems.setfNetweight(tWarehousebillsitems.getfNetweight());
                warehousebillsitems.setfStevedore(tWarehousebillsitems.getfStevedore());
                warehousebillsitems.setRemark(tWarehousebillsitems.getRemark());
                warehousebillsitems.setfWarehouselocid(tWarehousebillsitems.getfWarehouselocid());
                instalTWhgenleg(warehouseBills, warehousebillsitems);
            }
            tWarehousebillsitems.setfIsInventory(0L);
            tWarehousebillsitems.setfSerialNumber(warehousebillsitems.getfSerialNumber());
            if (StringUtils.isNotNull(tWarehousebillsitems.getfId())) {
                tWarehousebillsitems.setfBillstatus(40L);
                tWarehousebillsitems.setUpdateTime(new Date());
                tWarehousebillsitems.setUpdateBy(SecurityUtils.getUsername());
                tWarehousebillsitemsMapper.updateTWarehousebillsitems(tWarehousebillsitems);
                // 添加状态log
                insertTWarehousebillsLog(tWarehousebillsitems, 40L);
            }
        } else if ("SJCK".equals(billsType)) {
            // 查询总账是否存在
            TWhgenleg tWhgenle = queryTWhgenleg(warehouseBills, warehousebillsitems, goods.getIfCntrno());
            if (StringUtils.isNull(tWhgenle)) { // 为空 提示没有库存
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error("库存明细库存为空");
            }
            //  库存 <  出库件数
            if (tWhgenle.getfQtyblc() < tWarehousebillsitems.getfQty()) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error("库存明细库存不足");
            }
            tWarehousebillsitems.setfVolumn(warehousebillsitems.getfVolumn());
            // 跟新库存总账
            updateTWhgenlegData(tWarehousebillsitems, tWhgenle.getfId(), billsType);
            tWarehousebillsitems.setfBillstatus(40L);
            tWarehousebillsitems.setUpdateTime(new Date());
            tWarehousebillsitems.setfPid(warehouseBills.getfId());
            if (tWarehousebillsitems.getBsdate() != null) {
                tWarehousebillsitems.setfBsdate(tWarehousebillsitems.getBsdate());
            } else {
                tWarehousebillsitems.setfBsdate(warehouseBills.getfBsdate());
            }
            tWarehousebillsitems.setfBillno(warehouseBills.getfBillno());
            tWarehousebillsitems.setUpdateBy(loginUser.getUser().getUserName());
            tWarehousebillsitems.setfSerialNumber(warehousebillsitems.getfSerialNumber());
            tWarehousebillsitemsMapper.updateTWarehousebillsitems(tWarehousebillsitems);
            // 添加状态log
            insertTWarehousebillsLog(tWarehousebillsitems, 40L);
        }
        tEnclosureMapper.deleteByFPid(warehouseBills.getfId());
        //  附件添加
        if (StringUtils.isNotEmpty(attachs) && !"[]".equals(attachs)) {
            JSONArray jsonDrArray = JSONArray.parseArray(attachs);
            List<TEnclosure> tEnclosureList = JSONObject.parseArray(jsonDrArray.toJSONString(), TEnclosure.class);
            for (TEnclosure enclosure : tEnclosureList) {
                enclosure.setfStatus("6");
                enclosure.setCreateTime(new Date());
                enclosure.setfPid(warehouseBills.getfId());
                enclosure.setCreateBy(loginUser.getUser().getUserName());
                tEnclosureMapper.insertTEnclosure(enclosure);
            }
        }
        TWarehousebillsitems itemInFo = tWarehousebillsitemsMapper.selectItemQtyByFPid(warehouseBills.getfId());
        warehouseBills.setfQty(itemInFo.getfQty());
        warehouseBills.setfNetweight(itemInFo.getfNetweight());
        warehouseBills.setfGrossweight(itemInFo.getfGrossweight());
        tWarehouseBillsMapper.updateTWarehousebills(warehouseBills);
        return AjaxResult.success();
    }

    /**
     * app查询入库数量
     */
    @Override
    public List<Map<String, Object>> selectWarehouseBusinessInStockList(TWarehousebillsitems tWarehousebillsitems) {
        List<Map<String, Object>> mapList = null;
        if (tWarehousebillsitems.getfBilltype().equals("SJRK")) {
            mapList = tWarehousebillsitemsMapper.selectWarehouseBusinesInList(tWarehousebillsitems);
        } else {
            mapList = tWarehousebillsitemsMapper.selectWarehouseBusinesOutList(tWarehousebillsitems);
        }
        if (StringUtils.isNotEmpty(mapList)) {
            for (Map<String, Object> map : mapList) {
                Long fId = Long.valueOf(String.valueOf(map.get("fPid")));
                TEnclosure enclosure = new TEnclosure();
                enclosure.setfPid(fId);
                map.put("enclosure", tEnclosureMapper.selectWarehouseAccessoriesList(enclosure));
            }
        }
        return mapList;
    }

    /**
     * 叫车进场
     *
     * @param item    明细数据
     * @param attachs 附件
     * @return 结果
     */
    @Override
    @Transactional
    public AjaxResult addCreditItems(String item, String attachs) {
        TWarehousebillsitems tWarehousebillsitems = JSONArray.parseObject(item, TWarehousebillsitems.class);
        if (StringUtils.isNull(tWarehousebillsitems.getfId())) {
            return AjaxResult.error("未找到仓库明细id，请确认");
        }
        TWarehousebillsitems warehousebillsitems = tWarehousebillsitemsMapper.selectTWarehousebillsitemsById(tWarehousebillsitems.getfId());
        if (StringUtils.isNull(warehousebillsitems)) {
            return AjaxResult.error("未找到该条明细数据，请确认明细数据是否存在");
        }
        if (StringUtils.isNull(warehousebillsitems.getfBillstatus())) {
            return AjaxResult.error("未找到仓库明细状态信息，请确认");
        }
        if (warehousebillsitems.getfBillstatus() > 20L) {
            return AjaxResult.error("该仓库明细状态异常，请确认状态信息");
        }
        TWarehouseBills bills = tWarehouseBillsMapper.selectTWarehousebillsById(warehousebillsitems.getfPid());
        if (tWarehousebillsitems.getBsdate() != null && "0".equals(bills.getfChargetype())) {
            boolean fchargedate = this.getFchargedate(warehousebillsitems.getfPid(), tWarehousebillsitems.getBsdate());
            if (fchargedate == false) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error("入库日期不能小于最小仓储费计算日期");
            }
        }
        Date time = new Date();
        if (StringUtils.isNotEmpty(bills.getfChargetype()) && "0".equals(bills.getfChargetype())) {
            time = tWarehousebillsitemsMapper.selecMinBsDateByFPid(tWarehousebillsitems.getfPid());
            tWarehousebillsitems.setfChargedate(time);
            if (tWarehousebillsitems.getBsdate() != null) {
                tWarehousebillsitems.setfBsdate(tWarehousebillsitems.getBsdate());
            }
        } else if (StringUtils.isNotEmpty(bills.getfChargetype()) && "1".equals(bills.getfChargetype())) {
            if (tWarehousebillsitems.getBsdate() != null) {
                time = tWarehousebillsitems.getBsdate();
                tWarehousebillsitems.setfBsdate(tWarehousebillsitems.getBsdate());
            } else {
                time = warehousebillsitems.getfBsdate();
            }
            tWarehousebillsitems.setfChargedate(time);
        }
        tWarehousebillsitems.setfBillstatus(30L);
        tWarehousebillsitems.setUpdateTime(new Date());
        tWarehousebillsitems.setUpdateBy(SecurityUtils.getUsername());
        tWarehousebillsitemsMapper.updateTWarehousebillsitems(tWarehousebillsitems);
        // 更新主表明细状态
        TWarehouseBills warehouseBills = tWarehouseBillsMapper.selectTWarehousebillsById(warehousebillsitems.getfPid());
        if (StringUtils.isNotNull(warehousebillsitems.getfGoodsid())) {
            TGoods goods = tGoodsMapper.selectTGoodsById(warehousebillsitems.getfGoodsid());
            if (!warehouseBills.getfProductName().contains(goods.getfName())) {
                warehouseBills.setfProductName(warehouseBills.getfProductName() + "/" + goods.getfName());
            }
        }
        if (StringUtils.isNotNull(warehouseBills.getfMarks())) {
            if (!warehouseBills.getfMarks().contains(warehousebillsitems.getfMarks())) {
                warehouseBills.setfMarks(warehouseBills.getfMarks() + "/" + warehousebillsitems.getfMarks());
            }
        }
        if (!"SJRK".equals(warehouseBills.getfBilltype())) {
            if (!warehouseBills.getfMblno().contains(warehousebillsitems.getfMblno())) {
                warehouseBills.setfMblno(warehouseBills.getfMblno() + "/" + warehousebillsitems.getfMblno());
            }
        }
        warehouseBills.setfItemsStatus(3L);
        warehouseBills.setUpdateTime(new Date());
        Long timestamp = DateUtils.getTimestamp(new Date());
        warehouseBills.setfDateChanged(timestamp.toString() + (int) (Math.random() * 900) + 100);
        warehouseBills.setUpdateBy(SecurityUtils.getUsername());
        TWarehousebillsitems itemInFo = tWarehousebillsitemsMapper.selectItemQtyByFPid(warehouseBills.getfId());
        warehouseBills.setfQty(itemInFo.getfQty());
        warehouseBills.setfNetweight(itemInFo.getfNetweight());
        warehouseBills.setfGrossweight(itemInFo.getfGrossweight());
        tWarehouseBillsMapper.updateTWarehousebills(warehouseBills);
        tEnclosureMapper.deleteByFPid(warehouseBills.getfId());
        //  附件添加
        if (StringUtils.isNotEmpty(attachs) && !"[]".equals(attachs)) {
            JSONArray jsonDrArray = JSONArray.parseArray(attachs);
            List<TEnclosure> tEnclosureList = JSONObject.parseArray(jsonDrArray.toJSONString(), TEnclosure.class);
            for (TEnclosure enclosure : tEnclosureList) {
                enclosure.setfStatus("6");
                enclosure.setCreateTime(new Date());
                enclosure.setfPid(warehouseBills.getfId());
                enclosure.setCreateBy(SecurityUtils.getUsername());
                tEnclosureMapper.insertTEnclosure(enclosure);
            }
        }
        return AjaxResult.success();
    }

    @Override
    public List<InStock> inStockExport(TWarehouseBills tWarehousebills) throws Exception {
        List<Map<String, Object>> list = tWarehouseBillsMapper.selectWarehouseBusinessList(tWarehousebills);
        List<InStock> list1 = ListMapToBeanUtils.castMapToBean(list, InStock.class);
        return list1;
    }

    @Override
    public List<OutStock> outStockExport(TWarehouseBills tWarehousebills) throws Exception {
        List<Map<String, Object>> list = tWarehouseBillsMapper.selectWarehouseBusinessList(tWarehousebills);
        List<OutStock> list1 = ListMapToBeanUtils.castMapToBean(list, OutStock.class);
        return list1;
    }

    @Override
    public List<StockTransfer> stockTransferExport(TWarehouseBills tWarehousebills) throws Exception {
        List<Map<String, Object>> list = tWarehouseBillsMapper.selectWarehouseBusinessList(tWarehousebills);
        List<StockTransfer> list1 = ListMapToBeanUtils.castMapToBean(list, StockTransfer.class);
        return list1;
    }

    @Override
    public List<GoodsTransfer> goodsTransferExport(TWarehouseBills tWarehousebills) throws Exception {
        List<Map<String, Object>> list = tWarehouseBillsMapper.selectWarehouseBusinessList1(tWarehousebills);
        List<GoodsTransfer> list1 = ListMapToBeanUtils.castMapToBean(list, GoodsTransfer.class);
        return list1;
    }

    @Override
    public List<StorageFee> storageFeeExport(TWarehouseBills tWarehousebills) throws Exception {
        List<Map<String, Object>> list = tWarehouseBillsMapper.selectWarehouseBusinessList1(tWarehousebills);
        List<StorageFee> list1 = ListMapToBeanUtils.castMapToBean(list, StorageFee.class);
        return list1;
    }

    /**
     * 根据仓库主表id 更新对应明细表状态
     *
     * @param fPid 仓库主表id
     * @return 结果
     */
    @Transactional
    public AjaxResult warehouseFollow(Long fPid, long fettle) {
        if (StringUtils.isNull(fPid)) {
            return AjaxResult.error("仓库更新状态未找到主表信息，请与管理员联系");
        }
        try {
            tWarehouseBillsMapper.warehouseFollowUpdate(fPid, fettle, new Date());
            tWarehousebillsfeesMapper.warehouseFeesFollowUpdate(fPid, fettle, new Date());
            TWarehouseBills tWarehouseBills = tWarehouseBillsMapper.selectTWarehousebillsById(fPid);
            if ("SJRK".equals(tWarehouseBills.getfBilltype()) || "SJCK".equals(tWarehouseBills.getfBilltype())) {
                fettle = 40L;
            }
            tWarehousebillsitemsMapper.warehouseItemFollowUpdate(fPid, fettle);
        } catch (Exception e) {
            return AjaxResult.error("更新库存费用状态失败，请联系管理员");
        }
        return AjaxResult.success();
    }

    /**
     * 入库确认
     *
     * @param warehouseBills      主表
     * @param warehousebillsitems 明细
     * @param loginUser           当前登录人
     * @param billsType           状态
     * @return 结果
     */
    @Override
    @Transactional
    public AjaxResult addCredit(String warehouseBills, String warehousebillsitems, String tEnclosure, String warehousebillsfeesCr,
                                String warehousebillsfeesDr, LoginUser loginUser, String tCntr, String billsType) {
        Map<String, Object> map = new HashMap<>();
        if (StringUtils.isNull(warehouseBills) || "[]".equals(warehouseBills)) {
            return AjaxResult.error("未找到主表信息");
        }
        if (StringUtils.isNull(warehousebillsitems) || "[]".equals(warehousebillsitems)) {
            return AjaxResult.error("未找到入账信息");
        }
        TWarehouseBills tWarehouseBills = JSONArray.parseObject(warehouseBills, TWarehouseBills.class);
        tEnclosureMapper.deleteByFPid(tWarehouseBills.getfId());
        tWarehousebillsfeesMapper.deleteByFPid(tWarehouseBills.getfId());
        tWarehousebillsCntrMapper.deleteTWarehousebillsCntrfPid(tWarehouseBills.getfId());
        boolean businessStatus = "场地直装".equals(tWarehouseBills.getfBusinessType());
        JSONArray warehouseJSON = JSONArray.parseArray(warehousebillsitems);
        List<TWarehousebillsitems> warehousebillsitemsList = JSONObject.parseArray(warehouseJSON.toJSONString(), TWarehousebillsitems.class);
        Date time = new Date();
        if ("0".equals(tWarehouseBills.getfChargetype())) {
            time = tWarehousebillsitemsMapper.selecMinBsDateByFPid(tWarehouseBills.getfId());
        }
        int i = 1;
        for (TWarehousebillsitems item : warehousebillsitemsList) {
            // 如果业务时间超出当前时间则不允许
            if (item.getfBsdate().after(new Date())) {
                throw new WarehouseException("业务日期不得超出当前日期");
            }
            // 查询是否可以修改
            TWarehousebillsitems tWarehousebillsitems = tWarehousebillsitemsMapper.selectTWarehousebillsitemsById(item.getfId());
            if (tWarehousebillsitems.getfBillstatus() == 40) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error("更新库存明细第" + i + "行失败，已处理，请刷新网页");
            }
            if (StringUtils.isNull(item.getfWarehouselocid())) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error("库存明细第" + i + "行未找到库区");
            }
            if (!businessStatus) {
                // 查询库容量  是否可入库
                if (calculation(tWarehouseBills.getfWarehouseid(), item.getfGrossweight()) <= 0) {
                    throw new WarehouseException("更新库存总账失败-->入库毛重大于库容");
                }

                item.setfOriginalbilldate(item.getfBsdate());
                item.setfBillingway(tWarehouseBills.getfBillingway());
                if ("1".equals(tWarehouseBills.getfChargetype())) {
                    time = item.getfBsdate();
                }
                item.setfChargedate(time);
                TGoods goods = tGoodsMapper.selectTGoodsById(item.getfGoodsid());
                if ("1".equals(goods.getIfCntrno()) && StringUtils.isNull(item.getfCntrno())) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error("仓库明细第" + i + "行未找到箱号");
                }
                // 查询库存总帐
                TWhgenleg tWhgenle = queryWhgenlegService.stockWhgenleg(tWarehouseBills, item, goods.getIfCntrno(), WarehouseTypeEnum.CONFIRM_OPERATION.getType());
                //复制报关单号和备注
                if ("SJRK".equals(billsType)) {
                    if (StringUtils.isNotEmpty(tWarehouseBills.getfCustomno())) {
                        item.setfCustomno(tWarehouseBills.getfCustomno());
                    }
                    if (StringUtils.isNotEmpty(tWarehouseBills.getRemark())) {
                        item.setRemark(tWarehouseBills.getRemark());
                    }
                }
                if (StringUtils.isNotNull(tWhgenle)) {
                    updateTWhgenlegData(item, tWhgenle.getfId(), billsType);
                    item.setfSrcid(tWhgenle.getfId());
                } else {
                    Long whgenlegId = instalTWhgenleg(tWarehouseBills, item);
                    item.setfSrcid(whgenlegId);
                }
                item.setfIsInventory(0L);
            } else {
                item.setfIsInventory(1L);
            }
            int num = 0;
            if (StringUtils.isNotNull(item.getfId())) {
                item.setfBillstatus(40L);
                item.setUpdateBy(loginUser.getUser().getUserName());
                item.setUpdateTime(new Date());
                if ("SJRK".equals(billsType)) {
                    item.setfMblno(tWarehouseBills.getfMblno());// 入库更新库存前执行update更新明细的提单号等于主表的提单号
                }
                num = tWarehousebillsitemsMapper.updateTWarehousebillsitems(item);
                // 添加状态log
                insertTWarehousebillsLog(item, 40L);
            }
            if (num <= 0) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error("新增库存明细失败");
            }
            i++;
        }
        //  箱型数据
        if (StringUtils.isNotNull(tCntr) && !"[]".equals(tCntr)) {
            JSONArray jsonDrArray = JSONArray.parseArray(tCntr);
            List<TWarehousebillsCntr> tWarehousebillsCntrs = JSONObject.parseArray(jsonDrArray.toJSONString(), TWarehousebillsCntr.class);
            int line = 0;
            for (TWarehousebillsCntr cntr : tWarehousebillsCntrs) {
                line++;
                if (StringUtils.isNull(cntr.getfCntrid()) || StringUtils.isNull(cntr.getfCntrcount()) || cntr.getfCntrcount() == 0) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error("箱型数据第" + line + "行数据缺少必填数据");
                }
                cntr.setfPid(tWarehouseBills.getfId());
                cntr.setfGoodsid(0L);
                cntr.setfPackageid("0");
                cntr.setfCntrweight(new BigDecimal(0));
                cntr.setCreateBy(loginUser.getUser().getUserName());
                cntr.setCreateTime(new Date());
                tWarehousebillsCntrMapper.insertTWarehousebillsCntr(cntr);
            }
        }
        //  附件添加
        if (StringUtils.isNotEmpty(tEnclosure) && !"[]".equals(tEnclosure)) {
            JSONArray jsonDrArray = JSONArray.parseArray(tEnclosure);
            List<TEnclosure> tEnclosureList = JSONObject.parseArray(jsonDrArray.toJSONString(), TEnclosure.class);
            for (TEnclosure enclosure : tEnclosureList) {
                enclosure.setfPid(tWarehouseBills.getfId());
                enclosure.setCreateBy(loginUser.getUser().getUserName());
                enclosure.setCreateTime(new Date());
                tEnclosureMapper.insertTEnclosure(enclosure);
            }
        }
        // 收款明细添加
        if (StringUtils.isNotEmpty(warehousebillsfeesDr) && !"[]".equals(warehousebillsfeesDr)) {
            JSONArray jsonDrArray = JSONArray.parseArray(warehousebillsfeesDr);
            List<TWarehousebillsfees> warehousebillsfeesDrList = JSONObject.parseArray(jsonDrArray.toJSONString(), TWarehousebillsfees.class);
            for (TWarehousebillsfees wbDr : warehousebillsfeesDrList) {
                wbDr.setfPid(tWarehouseBills.getfId());
                wbDr.setfDc("D");
                wbDr.setCreateBy(loginUser.getUser().getUserName());
                wbDr.setCreateTime(new Date());
                if (tWarehouseBills.getfBsdate() != null && !tWarehouseBills.getfBsdate().equals("")) {
                    wbDr.setfBsdate(tWarehouseBills.getfBsdate());
                }
                tWarehousebillsfeesMapper.insertTWarehousebillsfees(wbDr);
            }
        }
        // 付款明细添加
        if (StringUtils.isNotNull(warehousebillsfeesCr) && !"[]".equals(warehousebillsfeesCr)) {
            JSONArray jsonCrArray = JSONArray.parseArray(warehousebillsfeesCr);
            List<TWarehousebillsfees> warehousebillsfeesCrList = JSONObject.parseArray(jsonCrArray.toJSONString(), TWarehousebillsfees.class);
            for (TWarehousebillsfees wbCr : warehousebillsfeesCrList) {
                wbCr.setfPid(tWarehouseBills.getfId());
                wbCr.setfDc("C");
                wbCr.setCreateBy(loginUser.getUser().getUserName());
                wbCr.setCreateTime(new Date());
                if (tWarehouseBills.getfBsdate() != null && !tWarehouseBills.getfBsdate().equals("")) {
                    wbCr.setfBsdate(tWarehouseBills.getfBsdate());
                }
                tWarehousebillsfeesMapper.insertTWarehousebillsfees(wbCr);
            }
        }
        //最后更新仓库主表
        tWarehouseBills.setfItemsStatus(4L);
        tWarehouseBills.setfBilltype(billsType);
        tWarehouseBills.setUpdateBy(loginUser.getUser().getUserName());
        tWarehouseBills.setUpdateTime(new Date());
        Long timestamp = DateUtils.getTimestamp(new Date());
        tWarehouseBills.setfDateChanged(timestamp.toString() + (int) (Math.random() * 900) + 100);
        TWarehousebillsitems itemInFo = tWarehousebillsitemsMapper.selectItemQtyByFPid(tWarehouseBills.getfId());
        tWarehouseBills.setfQty(itemInFo.getfQty());
        tWarehouseBills.setfNetweight(itemInFo.getfNetweight());
        tWarehouseBills.setfGrossweight(itemInFo.getfGrossweight());
        tWarehouseBillsMapper.updateTWarehousebills(tWarehouseBills);
        map.put("fDateChanged", tWarehouseBills.getfDateChanged());
        map.put("warehousebills", tWarehouseBills);
        map.put("warehousebillsitems", warehousebillsitemsList);
        return AjaxResult.success("成功", map);
    }

    /**
     * 入库明细提交审批确认
     * <p>
     * 待完善！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！
     */
    @Override
    @Transactional
    public AjaxResult addDetails(Long fId, String billsType, LoginUser loginUser) {
        TWarehouseBills tWarehouseBills = tWarehouseBillsMapper.selectTWarehousebillsById(fId);
        if (StringUtils.isNull(tWarehouseBills)) {
            return AjaxResult.error("未找到仓储信息，请确认是否存在");
        }
        List<TWarehousebillsitems> warehousebillsitemsList = tWarehousebillsitemsMapper.selectItemsStatusByPid(fId);
        if (StringUtils.isEmpty(warehousebillsitemsList)) {
            return AjaxResult.error("未找到仓储库存明细信息，请确认是否存在");
        }
        if (tWarehouseBills.getfItemstatus().longValue() == 4L
                || tWarehouseBills.getfItemstatus().longValue() == 5L
                || tWarehouseBills.getfItemstatus().longValue() == 6L) {
            return AjaxResult.error("该单明细已提交审核,请勿重复提交");
        }
        for (TWarehousebillsitems item : warehousebillsitemsList) {
            if (item.getfBillstatus() != 40L || item.getfBillstatus() == 50L) {
                return AjaxResult.error("库存明细中存在审核中数据，无法再次提交请核");
            }
        }
        boolean isApprove;
        long itemStatus = 6L;
        Long actId = 0L;
        String key = null;
        if (billsType.equals("SJRKITEM")) {
            actId = 170L;
        } else if (billsType.equals("SJCKITEM")) {
            actId = 180L;
        }

        SysConfig sysConfig = queryWarehouseConfig(billsType);
        if (StringUtils.isNull(sysConfig)) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("系统参数异常，未找到开启审批流参数");
        }
        if ("0".equals(sysConfig.getConfigValue())) {
            isApprove = true;
            itemStatus = 4L;
            tWarehouseBills.setfItemstatus(itemStatus);
            tWarehouseBills.setUpdateTime(new Date());
            tWarehouseBills.setUpdateBy(SecurityUtils.getUsername());
        } else {
            tWarehouseBills.setfItemstatus(itemStatus);
            tWarehouseBills.setUpdateTime(new Date());
            tWarehouseBills.setUpdateBy(SecurityUtils.getUsername());
        }
        tWarehouseBillsMapper.updateTWarehousebills(tWarehouseBills);
        for (TWarehousebillsitems item : warehousebillsitemsList) {
            item.setUpdateTime(new Date());
            item.setUpdateBy(SecurityUtils.getUsername());
            item.setfItemstatus(itemStatus);
            tWarehousebillsitemsMapper.updateTWarehousebillsitems(item);
        }
        if ("0".equals(sysConfig.getConfigValue())) {
            AuditItems auditItems = new AuditItems();
            auditItems.setLevelId(0L);
            auditItems.setBillId(tWarehouseBills.getfId());
            auditItems.setActId(actId);//暂定
            auditItems.setIffinalItem("F");
            auditItems.setBillNo(tWarehouseBills.getfBillno());
            // 存储委托方（货权方）
            auditItems.setRefno1(tWarehouseBills.getfCorpid() + "");
            // 存储业务类型（业务类型）
            auditItems.setRefno2(billsType);
            // 存储提单号（提单号）
            auditItems.setRefno3(tWarehouseBills.getfMblno());
            auditItems.setSendUserId(loginUser.getUser().getUserId());
            auditItems.setSendName(SecurityUtils.getUsername());
            auditItems.setSendTime(new Date());
            auditItems.setAuditUserId(loginUser.getUser().getUserId());
            auditItems.setAuditItem(new Date());
            auditItems.setAuditOpTime(new Date());
            auditItems.setAuditMsg("提交");
            auditItems.setAuditStatus("O");
            auditItems.setFidStatus("f_itemstatus");
            auditItems.setTimes(tWarehouseBills.getfTimes());
            AjaxResult approvalFlow = auditItemsService.createApprovalFlow(auditItems);
//            Long code = Long.valueOf(String.valueOf(approvalFlow.get("code"))).longValue();
            String code = approvalFlow.get("code").toString();
//                Long code = Long.valueOf(String.valueOf(ajaxResult.get("code"))).longValue();
            if ("500".equals(code)) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
            return approvalFlow;
        }
        return AjaxResult.success();
    }

    /**
     * 出库确认、调拨确认、货转确认
     *
     * @param warehouseBills
     * @param warehousebillsitems
     * @param loginUser
     * @param billsType
     * @return
     */
    @Override
    @Transactional
    public AjaxResult updateCredit(String warehouseBills, String warehousebillsitems, String tEnclosure, String warehousebillsfeesCr,
                                   String warehousebillsfeesDr, LoginUser loginUser, String tCntr, String billsType) {
        Long fPid = null;
        Map<String, Object> map = new HashMap<>();
        TWarehouseBills tWarehouseBills = JSONArray.parseObject(warehouseBills, TWarehouseBills.class);
        tWarehouseBills.setfItemsStatus(4L);
        Long timestamp = DateUtils.getTimestamp(new Date());
        tWarehouseBills.setfDateChanged(timestamp.toString() + (int) (Math.random() * 900) + 100);
        tWarehouseBills.setUpdateBy(loginUser.getUser().getUserName());
        tWarehouseBills.setUpdateTime(new Date());
        fPid = tWarehouseBills.getfId();
        tEnclosureMapper.deleteByFPid(fPid);
        tWarehousebillsfeesMapper.deleteByFPid(fPid);
        tWarehousebillsCntrMapper.deleteTWarehousebillsCntrfPid(fPid);
        JSONArray warehouseJSON = JSONArray.parseArray(warehousebillsitems);
        List<TWarehousebillsitems> warehousebillsitemsList = JSONObject.parseArray(warehouseJSON.toJSONString(), TWarehousebillsitems.class);
        int i = 1;
        List<TFees> feesList = new ArrayList<>();
        List<TWarehousebillsfees> warehousebillsfees = new ArrayList<>();
        // 判断原贸易与新贸易是否一致，如果一致则抛出异常
        if (Objects.equals(tWarehouseBills.getfTrademodeid(), tWarehouseBills.getfNewTrademodeid())) {
            throw new WarehouseException("贸易方式不得与原贸易方式一致");
        }
        for (TWarehousebillsitems wbItem : warehousebillsitemsList) {
            // 如果业务时间超出当前时间则不允许
            if (wbItem.getfBsdate().after(new Date())) {
                throw new WarehouseException("业务日期不得超出当前日期");
            }
            // 查询是否可以修改
            TWarehousebillsitems tWarehousebillsitems = tWarehousebillsitemsMapper.selectTWarehousebillsitemsById(wbItem.getfId());
            if (tWarehousebillsitems.getfBillstatus() == 40) {
                throw new WarehouseException("更新库存明细第" + i + "行失败，已处理，请刷新网页");
            }
            if (StringUtils.isNull(wbItem.getfWarehouselocid())) {
                throw new WarehouseException("库存明细第" + i + "行,未找到仓库信息");
            }
            TGoods goods = tGoodsMapper.selectTGoodsById(wbItem.getfGoodsid());
            // 如果需要判断箱号则需要校验必填
            if (WarehouseTypeEnum.JUDGE_BOX.getType().equals(goods.getIfCntrno()) && StringUtils.isNull(wbItem.getfCntrno())) {
                throw new WarehouseException("仓库明细第" + i + "行未找到箱号");
            }
            wbItem.setfBilltype(billsType);
            // 查询总账是否存在
            TWhgenleg tWhgenle = queryWhgenlegService.stockWhgenleg(tWarehouseBills, wbItem, goods.getIfCntrno(), WarehouseTypeEnum.CONFIRM_OPERATION.getType());
            // 查询总账是否存在
            if (Objects.isNull(tWhgenle)) {
                throw new WarehouseException("库存明细第" + i + "行找不到库存信息");
            }
            if (wbItem.getfBsdate().before(tWhgenle.getfChargedate())) {
                throw new WarehouseException("业务日期不得超出库存总帐日期");
            }
            //  入库数特殊不判断入账
            if (WarehouseTypeEnum.SJCK.getType().equals(billsType)) { // 出库 查询
                if (StringUtils.isNull(tWarehouseBills.getfBsdate()) || StringUtils.isNull(wbItem.getfChargedate())) {
                    throw new WarehouseException("库存明细第" + i + "行请检查日期，操作终止");
                }
                if (StringUtils.isNull(tWarehouseBills.getfCorpid())) {
                    throw new WarehouseException("库存明细第" + i + "行请检查客户信息，操作终止");
                }
                //校验计费日期是等于库存总帐计费日，如果不相等则报错
                checkWhgenleg(wbItem, tWhgenle);
                //  1、  库存 <  调拨件数  提示库存不足
                judgeItemQty(tWhgenle, wbItem, i);
                // 更新库存总账
                updateTWhgenlegData(wbItem, tWhgenle.getfId(), billsType);
                wbItem.setfBillstatus(40L);
            } else if (WarehouseTypeEnum.CKDB.getType().equals(billsType) || WarehouseTypeEnum.HWTG.getType().equals(billsType)) { // 调拨查询
                //校验计费日期是等于库存总帐计费日，如果不相等则报错
                checkWhgenleg(wbItem, tWhgenle);
                if (!Objects.equals(wbItem.getfWarehouselocid(), wbItem.getfTransferWarehouselocid())) {
                    //  1、  库存 <  调拨件数  提示库存不足
                    judgeItemQty(tWhgenle, wbItem, i);
                    // 2、 库存足够 先 进行出库操作
                    updateTWhgenlegData(wbItem, tWhgenle.getfId(), WarehouseTypeEnum.SJCK.getType());
                    // 3、 进行入库操作 查询是否存在库存
                    TWhgenleg tWhgenle1 = queryWhgenlegService.secondStockWhgenleg(tWarehouseBills, wbItem, goods.getIfCntrno(), WarehouseTypeEnum.NOT_JUDGE_BOX.getType());
                    if (StringUtils.isNull(tWhgenle1)) {   // 5、 不存在 进行新增库存
                        instalTWhgenleg(tWarehouseBills, wbItem);
                    } else { // 4、 存在 进行跟新库存
                        updateTWhgenlegData(wbItem, tWhgenle1.getfId(), WarehouseTypeEnum.SJRK.getType());
                    }
                }
                wbItem.setfBillstatus(40L);
            } else if (WarehouseTypeEnum.HQZY.getType().equals(billsType)) { // 货转
                wbItem.setfBillstatus(6L);
                wbItem.setfBillingway(tWarehouseBills.getfBillingway());
                //校验计费日期是等于库存总帐计费日，如果不相等则报错
                checkWhgenleg(wbItem, tWhgenle);
                //  1、  库存 <  调拨件数  提示库存不足
                judgeItemQty(tWhgenle, wbItem, i);
                updateTWhgenlegData(wbItem, tWhgenle.getfId(), WarehouseTypeEnum.SJCK.getType());
                long corpId = tWarehouseBills.getfCorpid();
                tWarehouseBills.setfCorpid(tWarehouseBills.getfTocorpid());
                // 3、 进行入库操作 查询是否存在库存
                TWhgenleg tWhgenle1 = queryWhgenlegService.secondStockWhgenleg(tWarehouseBills, wbItem, goods.getIfCntrno(), WarehouseTypeEnum.NOT_JUDGE_BOX.getType());
                if (StringUtils.isNull(tWhgenle1)) {   // 5、 不存在 进行新增库存
                    instalTWhgenleg(tWarehouseBills, wbItem);
                } else { // 4、 存在 进行跟新库存
                    updateTWhgenlegData(wbItem, tWhgenle1.getfId(), WarehouseTypeEnum.SJRK.getType());
                }
                tWarehouseBills.setfCorpid(corpId);
            }
            i++;
            int num = 0;
            wbItem.setfPid(fPid);
            wbItem.setfBillno(tWarehouseBills.getfBillno());
            if (StringUtils.isNotNull(wbItem.getfId())) {
                wbItem.setUpdateBy(loginUser.getUser().getUserName());
                wbItem.setUpdateTime(new Date());
                num = tWarehousebillsitemsMapper.updateTWarehousebillsitems(wbItem);
                if (WarehouseTypeEnum.SJCK.getType().equals(billsType)) {
                    // 添加状态log
                    insertTWarehousebillsLog(wbItem, 40L);
                }
            } else {
                wbItem.setCreateTime(new Date());
                wbItem.setCreateBy(loginUser.getUsername());
                num = tWarehousebillsitemsMapper.insertTWarehousebillsitems(wbItem);
            }
            if (num <= 0) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error("库存明细更新失败");
            }
        }
        //  箱型数据
        if (StringUtils.isNotNull(tCntr) && !"[]".equals(tCntr)) {
            JSONArray jsonDrArray = JSONArray.parseArray(tCntr);
            List<TWarehousebillsCntr> tWarehousebillsCntrs = JSONObject.parseArray(jsonDrArray.toJSONString(), TWarehousebillsCntr.class);
            int line = 0;
            for (TWarehousebillsCntr cntr : tWarehousebillsCntrs) {
                line++;
                if (StringUtils.isNull(cntr.getfCntrid()) || StringUtils.isNull(cntr.getfCntrcount()) || cntr.getfCntrcount() == 0) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error("箱型数据第" + line + "行数据缺少必填数据");
                }
                cntr.setfPid(tWarehouseBills.getfId());
                cntr.setfGoodsid(0L);
                cntr.setfPackageid("0");
                cntr.setfCntrweight(new BigDecimal(0));
                cntr.setCreateBy(loginUser.getUser().getUserName());
                cntr.setCreateTime(new Date());
                tWarehousebillsCntrMapper.insertTWarehousebillsCntr(cntr);
            }
        }
        //  附件添加
        if (StringUtils.isNotEmpty(tEnclosure) && !"[]".equals(tEnclosure)) {
            JSONArray jsonDrArray = JSONArray.parseArray(tEnclosure);
            List<TEnclosure> tEnclosureList = JSONObject.parseArray(jsonDrArray.toJSONString(), TEnclosure.class);
            for (TEnclosure enclosure : tEnclosureList) {
                enclosure.setfPid(tWarehouseBills.getfId());
                enclosure.setCreateBy(loginUser.getUser().getUserName());
                enclosure.setCreateTime(new Date());
                tEnclosureMapper.insertTEnclosure(enclosure);
            }
        }
        // 收款明细添加
        if (StringUtils.isNotEmpty(warehousebillsfeesDr) && !"[]".equals(warehousebillsfeesDr)) {
            JSONArray jsonDrArray = JSONArray.parseArray(warehousebillsfeesDr);
            List<TWarehousebillsfees> warehousebillsfeesDrList = JSONObject.parseArray(jsonDrArray.toJSONString(), TWarehousebillsfees.class);
            for (TWarehousebillsfees wbDr : warehousebillsfeesDrList) {
                wbDr.setfPid(tWarehouseBills.getfId());
                wbDr.setfDc("D");
                wbDr.setCreateBy(loginUser.getUser().getUserName());
                wbDr.setCreateTime(new Date());
                tWarehousebillsfeesMapper.insertTWarehousebillsfees(wbDr);
            }
        }
        // 付款明细添加
        if (StringUtils.isNotNull(warehousebillsfeesCr) && !"[]".equals(warehousebillsfeesCr)) {
            JSONArray jsonCrArray = JSONArray.parseArray(warehousebillsfeesCr);
            List<TWarehousebillsfees> warehousebillsfeesCrList = JSONObject.parseArray(jsonCrArray.toJSONString(), TWarehousebillsfees.class);
            for (TWarehousebillsfees wbCr : warehousebillsfeesCrList) {
                wbCr.setfPid(tWarehouseBills.getfId());
                wbCr.setfDc("C");
                wbCr.setCreateBy(loginUser.getUser().getUserName());
                wbCr.setCreateTime(new Date());
                tWarehousebillsfeesMapper.insertTWarehousebillsfees(wbCr);
            }
        }
        //从表更新完再查从表信息更新主表
        TWarehousebillsitems itemInFo = tWarehousebillsitemsMapper.selectItemQtyByFPid(tWarehouseBills.getfId());
        tWarehouseBills.setfQty(itemInFo.getfQty());
        tWarehouseBills.setfNetweight(itemInFo.getfNetweight());
        tWarehouseBills.setfGrossweight(itemInFo.getfGrossweight());
        tWarehouseBillsMapper.updateTWarehousebills(tWarehouseBills);
        map.put("fPid", fPid);
        map.put("warehouse", tWarehouseBills);
        map.put("warehouseItem", warehousebillsitemsList);
        map.put("fees", feesList);
        map.put("warehousebillsfees", warehousebillsfees);
        // 添加成功 主键返回 前台
        return AjaxResult.success("成功", map);
    }

    /**
     * 判断数量、毛重、净重是否超出库存总帐
     *
     * @param whgenleg 库存总账
     * @param wbItem   明细
     * @param line     行号
     */
    private void judgeItemQty(TWhgenleg whgenleg, TWarehousebillsitems wbItem, int line) {
        //  库存 <  出库件数
        if (whgenleg.getfQtyblc() < wbItem.getfQty()) {
            throw new WarehouseException("库存明细第" + line + "行库存数量不足");
        }
        //  库存 <  出库净重
        if (whgenleg.getfNetweightblc().compareTo(wbItem.getfNetweight()) < 0) {
            throw new WarehouseException("库存明细第" + line + "行库存净重不足");
        }
        //  库存 <  出库毛重
        if (whgenleg.getfGrossweightblc().compareTo(wbItem.getfGrossweight()) < 0) {
            throw new WarehouseException("库存明细第" + line + "行库存毛重不足");
        }
    }

    /**
     * 校验计费日期是等于库存总帐计费日，如果不相等则报错
     *
     * @param wbItem
     * @param tWhgenle
     */
    private void checkWhgenleg(TWarehousebillsitems wbItem, TWhgenleg tWhgenle) {
        // 如果仓储费计费日期超出 库存总帐的计费日期不相等则报异常
        if (wbItem.getfChargedate().before(tWhgenle.getfChargedate())) {
            throw new WarehouseException("仓储费计费日期与库存总帐计费日期不相符");
        }
    }

    /**
     * 打印作业单
     *
     * @param warehouseBills
     * @param warehousebillsitems
     * @param tEnclosure
     * @param tWarehousebillsfeesCr
     * @param tWarehousebillsfeesDr
     * @param loginUser
     * @param status
     * @param billtystatus
     * @return
     */
    @Override
    @Transactional
    public AjaxResult waitWarehousing(String warehouseBills, String warehousebillsitems,
                                      String tEnclosure, String tWarehousebillsfeesCr, String tWarehousebillsfeesDr,
                                      LoginUser loginUser, String tCntr, Long status, String billtystatus) {
        Map<String, Object> map = new HashMap<>();
        List<TWarehousebillsitems> mapList = new ArrayList<>();
        if (StringUtils.isNull(warehouseBills) || "[]".equals(warehouseBills)) {
            return AjaxResult.error("未找到主表信息");
        }
        if (StringUtils.isNull(warehousebillsitems) || "[]".equals(warehousebillsitems)) {
            return AjaxResult.error("未找到入账信息");
        }
        TWarehouseBills tWarehouseBills = JSONArray.parseObject(warehouseBills, TWarehouseBills.class);
        if (status == 20) {
            tWarehouseBills.setfItemsStatus(2L);
        } else if (status == 30) {
            tWarehouseBills.setfItemsStatus(3L);
        }
        Long timestamp = DateUtils.getTimestamp(new Date());
        tWarehouseBills.setfDateChanged(timestamp.toString() + (int) (Math.random() * 900) + 100);
        tWarehouseBills.setUpdateBy(loginUser.getUser().getUserName());
        tWarehouseBills.setUpdateTime(new Date());
        TWarehousebillsitems itemInFo = tWarehousebillsitemsMapper.selectItemQtyByFPid(tWarehouseBills.getfId());
        tWarehouseBills.setfQty(itemInFo.getfQty());
        tWarehouseBills.setfNetweight(itemInFo.getfNetweight());
        tWarehouseBills.setfGrossweight(itemInFo.getfGrossweight());
        tWarehouseBillsMapper.updateTWarehousebills(tWarehouseBills);
        tEnclosureMapper.deleteByFPid(tWarehouseBills.getfId());
        tWarehousebillsfeesMapper.deleteByFPid(tWarehouseBills.getfId());
        tWarehousebillsCntrMapper.deleteTWarehousebillsCntrfPid(tWarehouseBills.getfId());
        JSONArray warehouseJSON = JSONArray.parseArray(warehousebillsitems);
        List<TWarehousebillsitems> warehousebillsitemsList = JSONObject.parseArray(warehouseJSON.toJSONString(), TWarehousebillsitems.class);
        /**
         * 1、 查询回收表是否有可用数据
         * 2、 流水号生成 --> 打印一次 只记录一个号
         */
        Date time = new Date();
        String serialNumber = null;
        if (status == 20) {
            if ("RK".equals(billtystatus)) {
                serialNumber = billnoSerialServiceImpl.getSerialNumber("RK", time);
            } else if ("CK".equals(billtystatus)) { //生成 出库 流水号
                serialNumber = billnoSerialServiceImpl.getSerialNumber("CK", time);
            } else if ("DB".equals(billtystatus)) { //生成 出库 流水号
                serialNumber = billnoSerialServiceImpl.getSerialNumber("DB", time);
            } else if ("TG".equals(billtystatus)) { //生成 出库 流水号
                serialNumber = billnoSerialServiceImpl.getSerialNumber("TG", time);
            }
        }
        int i = 1;
        for (TWarehousebillsitems item : warehousebillsitemsList) {
            // 查询是否可以修改
            TWarehousebillsitems tWarehousebillsitems = tWarehousebillsitemsMapper.selectTWarehousebillsitemsById(item.getfId());
            if (tWarehousebillsitems.getfBillstatus() == 30) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error("更新库存明细第" + i + "行失败，已处理，请刷新网页");
            }
            if (item.getfBillstatus() < 30L) {
                if (item.getfSerialNumber() == null || item.getfSerialNumber().equals("")) {
                    item.setfSerialNumber(serialNumber);
                }
                item.setfBillstatus(status);
                item.setUpdateTime(new Date());
                item.setUpdateBy(loginUser.getUser().getUserName());
                int num = tWarehousebillsitemsMapper.updateTWarehousebillsitems(item);
                // 添加状态log
                insertTWarehousebillsLog(item, status);
                if (num <= 0) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error("更新库存明细失败");
                }
            }
            mapList.add(item);
            i++;
        }
        //  箱型数据
        if (StringUtils.isNotNull(tCntr) && !"[]".equals(tCntr)) {
            JSONArray jsonDrArray = JSONArray.parseArray(tCntr);
            List<TWarehousebillsCntr> tWarehousebillsCntrs = JSONObject.parseArray(jsonDrArray.toJSONString(), TWarehousebillsCntr.class);
            int line = 0;
            for (TWarehousebillsCntr cntr : tWarehousebillsCntrs) {
                line++;
                if (StringUtils.isNull(cntr.getfCntrid()) || StringUtils.isNull(cntr.getfCntrcount()) || cntr.getfCntrcount() == 0) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error("箱型数据第" + line + "行数据缺少必填数据");
                }
                cntr.setfPid(tWarehouseBills.getfId());
                cntr.setfGoodsid(0L);
                cntr.setfPackageid("0");
                cntr.setfCntrweight(new BigDecimal(0));
                cntr.setCreateBy(loginUser.getUser().getUserName());
                cntr.setCreateTime(new Date());
                tWarehousebillsCntrMapper.insertTWarehousebillsCntr(cntr);
            }
        }
        //  附件添加
        if (StringUtils.isNotEmpty(tEnclosure) && !"[]".equals(tEnclosure)) {
            JSONArray jsonDrArray = JSONArray.parseArray(tEnclosure);
            List<TEnclosure> tEnclosureList = JSONObject.parseArray(jsonDrArray.toJSONString(), TEnclosure.class);
            for (TEnclosure enclosure : tEnclosureList) {
                enclosure.setfPid(tWarehouseBills.getfId());
                enclosure.setCreateBy(loginUser.getUser().getUserName());
                enclosure.setCreateTime(new Date());
                tEnclosureMapper.insertTEnclosure(enclosure);
            }
        }
        // 收款明细添加
        if (StringUtils.isNotEmpty(tWarehousebillsfeesDr) && !"[]".equals(tWarehousebillsfeesDr)) {
            JSONArray jsonDrArray = JSONArray.parseArray(tWarehousebillsfeesDr);
            List<TWarehousebillsfees> warehousebillsfeesDrList = JSONObject.parseArray(jsonDrArray.toJSONString(), TWarehousebillsfees.class);
            for (TWarehousebillsfees wbDr : warehousebillsfeesDrList) {
                wbDr.setfPid(tWarehouseBills.getfId());
                wbDr.setfDc("D");
                wbDr.setCreateBy(loginUser.getUser().getUserName());
                wbDr.setCreateTime(new Date());
                if (tWarehouseBills.getfBsdate() != null && !tWarehouseBills.getfBsdate().equals("")) {
                    wbDr.setfBsdate(tWarehouseBills.getfBsdate());
                }
                tWarehousebillsfeesMapper.insertTWarehousebillsfees(wbDr);
            }
        }
        // 付款明细添加
        if (StringUtils.isNotNull(tWarehousebillsfeesCr) && !"[]".equals(tWarehousebillsfeesCr)) {
            JSONArray jsonCrArray = JSONArray.parseArray(tWarehousebillsfeesCr);
            List<TWarehousebillsfees> warehousebillsfeesCrList = JSONObject.parseArray(jsonCrArray.toJSONString(), TWarehousebillsfees.class);
            for (TWarehousebillsfees wbCr : warehousebillsfeesCrList) {
                wbCr.setfPid(tWarehouseBills.getfId());
                wbCr.setfDc("C");
                wbCr.setCreateBy(loginUser.getUser().getUserName());
                wbCr.setCreateTime(new Date());
                if (tWarehouseBills.getfBsdate() != null && !tWarehouseBills.getfBsdate().equals("")) {
                    wbCr.setfBsdate(tWarehouseBills.getfBsdate());
                }
                tWarehousebillsfeesMapper.insertTWarehousebillsfees(wbCr);
            }
        }
        // 添加成功 返回 前台
        TWarehousebillsitems tWarehousebillsitems = new TWarehousebillsitems();
        tWarehousebillsitems.setfPid(tWarehouseBills.getfId());
        List<TWarehousebillsitems> mapList1 = tWarehousebillsitemsMapper.selectTWarehousebillsitemsList(tWarehousebillsitems);
        map.put("fDateChanged", tWarehouseBills.getfDateChanged());
        map.put("warehousebillsitems", mapList);
        map.put("warehousebillsitems1", mapList1);
        return AjaxResult.success("成功", map);
    }

    /**
     * 生成计算仓储费信息
     *
     * @param warehouseBills
     * @param loginUser
     * @param cangKey
     * @return
     */
    public StorageFeeCalculationResultVO getWarehouseItems(TWarehouseBills warehouseBills, List<CalculateStorageFeesInfoVO> feesInfoVOList, LoginUser loginUser, String cangKey) {
        StorageFeeCalculationResultVO resultVO = new StorageFeeCalculationResultVO();

        BigDecimal sumAmt = BigDecimal.ZERO;
        List<TWarehousebillsfees> itemsList = new ArrayList<>();
        // 获取税率
        List<SysDictData> taxRate = sysDictDataMapper.selectDictDataByType("tax_rate");

        for (CalculateStorageFeesInfoVO item : feesInfoVOList) {
            // 交以计算明细计费方式必填
            if (StringUtils.isNull(item.getFBillingway())) {
                throw new WarehouseException("单号：" + item.getFBillno() + ",业务日期:" + item.getFBsdate() + "未找到库存总账的计费单位，请确认");
            }
            CalculateStorageFeesDTO storageFeesDto = new CalculateStorageFeesDTO();
            storageFeesDto.setfCorpid(warehouseBills.getfCorpid());
            storageFeesDto.setCangKey(cangKey);
            storageFeesDto.setWarehouseId(Long.parseLong(String.valueOf(item.getWarehouse())));
            // 把商品类型添加“”方便后续查询
            String goodsTypeids = item.getFTypeid();
            if (StringUtils.isNotEmpty(goodsTypeids)) {
                goodsTypeids = "\"" + goodsTypeids + "\"";
            }
            storageFeesDto.setfGoodsid(goodsTypeids);

            long fId = item.getFId();
            // 累计计费天数 如果计费日期与原始入库日期一直代表没有计算过
            if (Objects.equals(item.getFChargedate().getTime(), item.getFOriginalbilldate().getTime())) {
                storageFeesDto.setEarlySumDays(0L);
            } else {
                storageFeesDto.setEarlySumDays(DateUtils.getDateDay(item.getFChargedate(), item.getFOriginalbilldate()));
            }
            // 库存天数
            long fInventoryDays;
            // 要计费天数
            long fBillingDays;
            if (WarehouseTypeEnum.SJCK.getType().equals(item.getFBilltype())) {
                // 出库在库天数：业务日期-计费日期
                // 出库计费天数：出库在库天数
                fInventoryDays = DateUtils.getDateDay(item.getFBsdate(), item.getFChargedate());
                fBillingDays = fInventoryDays;
                storageFeesDto.setStartTime(item.getFOriginalbilldate());
                storageFeesDto.setEndTime(item.getFBsdate());
            } else if (WarehouseTypeEnum.HQZY.getType().equals(item.getFBilltype())) {
                // 货转在库天数：业务日期-计费日期
                // 货转计费天数：出库在库天数
                fInventoryDays = DateUtils.getDateDay(item.getFBsdate(), item.getFChargedate());
                fBillingDays = fInventoryDays;
                storageFeesDto.setStartTime(item.getFBsdate());
                storageFeesDto.setEndTime(item.getFOriginalbilldate());
            } else {
                // 库存总帐在库天数：计费截止日期-原始入库日期
                // 库存总帐计费天数：计费截止日期-计费日期
                fInventoryDays = DateUtils.getDateDay(warehouseBills.getfBillingDeadline(), item.getFOriginalbilldate());
                fBillingDays = DateUtils.getDateDay(warehouseBills.getfBillingDeadline(), item.getFChargedate());
                storageFeesDto.setStartTime(item.getFChargedate());
                storageFeesDto.setEndTime(warehouseBills.getfBillingDeadline());
            }
            if (fBillingDays <= 0) {
                continue;
            }
            storageFeesDto.setDays(fBillingDays);
            storageFeesDto.setfMblno(item.getFMblno());
            // 赋值要计算的数量单位
            storageFeesDto.setfQty(new BigDecimal(item.getFQty()));
            storageFeesDto.setfVolumn(item.getFVolumn());
            storageFeesDto.setfNetweight(item.getFNetweight());
            storageFeesDto.setfGrossweight(item.getFGrossweight());
            // 仓储费协议计算
            StorageFeeCalculationResultVO feeCalculationResultVO = tWarehouseAgreementService.getCarryingCost(storageFeesDto);
            if (Objects.isNull(feeCalculationResultVO)) {
                continue;
            }
            String mblno = "";
            if (StringUtils.isNotNull(item.getFMblno())) {
                mblno = item.getFMblno();
            }
            resultVO.setFeeId(feeCalculationResultVO.getFeeId());
            sumAmt = sumAmt.add(feeCalculationResultVO.getAmt());
            TWarehousebillsfees fees = new TWarehousebillsfees();
            fees.setfFeeid(feeCalculationResultVO.getFeeId());
            fees.setfDc("D");
            fees.setfAmt(feeCalculationResultVO.getAmt());
            fees.setSrcId(fId);
            fees.setfMblno(mblno);
            fees.setRemark(feeCalculationResultVO.getRemark());
            fees.setfFeeunitid(2L);
            fees.setfAmount(feeCalculationResultVO.getAmt());
            fees.setfBillstatus(2L);
            fees.setfCurrency("RMB");
            fees.setfBsdate(item.getFBsdate());
            fees.setfBillingQty(feeCalculationResultVO.getQty());
            fees.setfUnitprice(feeCalculationResultVO.getAmt());
            fees.setfBilltype(item.getFBilltype());
            fees.setCreateTime(new Date());
            fees.setfBillingDays(fBillingDays);
            fees.setfQty(new BigDecimal(1));
            fees.setfPid(warehouseBills.getfId());
            fees.setfInventoryDays(fInventoryDays);
            fees.setfExrate(new BigDecimal(1));
            fees.setPriceDateRemarks(feeCalculationResultVO.getBillingInterval());
            fees.setfCorpid(warehouseBills.getfCorpid());
            fees.setfMarks(item.getFMarks());
            fees.setSrcBillNo(item.getFBillno());
            fees.setCreateBy(loginUser.getUser().getUserName());
            fees.setfWarehouseid(storageFeesDto.getWarehouseId());
            fees.setfProductName(item.getGoodsName());
            if (WarehouseTypeEnum.SJCK.getType().equals(item.getFBilltype()) ||
                    WarehouseTypeEnum.HQZY.getType().equals(item.getFBilltype())) {
                fees.setfBillingDeadline(item.getFBsdate());
            } else {
                fees.setfBillingDeadline(warehouseBills.getfBillingDeadline());
            }
            fees.setfChargedate(item.getFChargedate());
            fees.setfTaxrate(new BigDecimal(taxRate.get(0).getDictValue()));
            fees.setfOriginalbilldate(item.getFOriginalbilldate());

            fees.setfBillingway(feeCalculationResultVO.getUnit());

            tWarehousebillsfeesMapper.insertTWarehousebillsfees(fees);
            itemsList.add(fees);
        }
        resultVO.setAmt(sumAmt);
        resultVO.setItemFeesList(itemsList);
        return resultVO;
    }

    /**
     * 新增库存费计算
     *
     * @param tWarehouseBills 主表的查询条件
     * @param loginUser       登录用户
     * @param billsType       状态
     * @return 结果
     */
    @Override
    @Transactional
    public AjaxResult calculateStorageFees(TWarehouseBills tWarehouseBills, LoginUser loginUser, String billsType) {
        if (StringUtils.isNull(tWarehouseBills.getfCorpid())) {
            return AjaxResult.error("请选择客户信息");
        }
        tWarehouseBills.setfBillingDeadline(DateUtils.dateConversionMax(tWarehouseBills.getfBillingDeadline()));
        long fPid;
        if (StringUtils.isNull(tWarehouseBills.getfId())) {
            // 生成流水号
            Date time = new Date();
            String billNo = billnoSerialServiceImpl.getSerialNumber(WarehouseTypeEnum.JSCCF.getType(), time);
            tWarehouseBills.setfBillno(billNo);
            if (StringUtils.isNull(tWarehouseBills.getfBillstatus())) {
                tWarehouseBills.setfBillstatus(2L);
            }
            tWarehouseBills.setfBilltype(billsType);
            tWarehouseBills.setfBsdeptid(loginUser.getUser().getDeptId());
            tWarehouseBills.setCreateBy(loginUser.getUser().getUserName());
            tWarehouseBills.setCreateTime(new Date());
            tWarehouseBillsMapper.insertTWarehousebills(tWarehouseBills);
            fPid = tWarehouseBills.getfId();
        } else {
            tWarehousebillsfeesMapper.deleteByFPid(tWarehouseBills.getfId());
            tWarehousebillsitemsMapper.deleteByFPid(tWarehouseBills.getfId());
            tWarehouseBills.setUpdateBy(loginUser.getUser().getUserName());
            tWarehouseBills.setUpdateTime(new Date());
            tWarehouseBillsMapper.updateTWarehousebills(tWarehouseBills);
            fPid = tWarehouseBills.getfId();
        }
        // 计划物资明细
        List<TWarehousebillsfees> itemsList = new ArrayList<>();
        StorageFeeCalculationResultVO calculationResultVO = new StorageFeeCalculationResultVO();
        //调一次公共方法，获取字符类型的true或者false传
        String cangKey = sysConfigServiceImpl.selectConfigByKey("agreement.warehouse");
        // 查出所有仓库 给后续匹配仓库名字使用
        List<TWarehouse> warehouseList = tWarehouseMapper.selectTWarehouseList(new TWarehouse());
        // 查询 出库 货转的库存明细
        tWarehouseBills.setfId(null);
        List<CalculateStorageFeesInfoVO> feesInfoVOList = tWarehousebillsitemsMapper.selectStorageFeeItemList1(tWarehouseBills);
        tWarehouseBills.setfId(fPid);
        if (CollectionUtils.isNotEmpty(feesInfoVOList)) {
            StorageFeeCalculationResultVO resultVO = getWarehouseItems(tWarehouseBills, feesInfoVOList, loginUser, cangKey);
            if (CollectionUtils.isNotEmpty(resultVO.getItemFeesList())) {
                // 给仓库信息赋值
                resultVO.getItemFeesList().forEach(li -> {
                    TWarehouse tWarehouse = warehouseList.stream().filter(warehouse -> Objects.equals(warehouse.getfId(), li.getfWarehouseid()))
                            .findFirst().orElseThrow(() -> new WarehouseException("找不到仓库信息"));
                    li.setWarehouseName(tWarehouse.getfName());
                });
                itemsList = resultVO.getItemFeesList();
            }
        }
        List<CalculateStorageFeesInfoVO> whgenlegfeesInfoVOList = tWhgenlegMapper.selectStorageFeeItemList1(tWarehouseBills);
        if (CollectionUtils.isNotEmpty(whgenlegfeesInfoVOList)) {
            // 如果是计算之前日期的库存总帐则需要使用当时日期的准确数量
            if (!tWarehouseBills.getfBillingDeadline().after(new Date())) {
                updateWhgenlegs1(tWarehouseBills, whgenlegfeesInfoVOList);
            }
            StorageFeeCalculationResultVO resultVO = getWarehouseItems(tWarehouseBills, whgenlegfeesInfoVOList, loginUser, cangKey);
            if (CollectionUtils.isNotEmpty(resultVO.getItemFeesList())) {
                // 给仓库信息赋值
                for (TWarehousebillsfees li : resultVO.getItemFeesList()) {
                    TWarehouse tWarehouse = warehouseList.stream().filter(warehouse -> Objects.equals(warehouse.getfId(), li.getfWarehouseid()))
                            .findFirst().orElseThrow(() -> new WarehouseException("找不到仓库信息"));
                    li.setWarehouseName(tWarehouse.getfName());
                    itemsList.add(li);
                }
            }
        }
        TFees tFees = new TFees();
        tFees.setfStatus("2");
        tFees.setDelFlag("0");
        List<TFees> feesList = tFeesMapper.selectTFeesList(tFees);
        if (CollectionUtils.isEmpty(itemsList)) {
            throw new WarehouseException("未找到合适的库存明细");
        }
        calculationResultVO.setFeesList(feesList);
        calculationResultVO.setWarehouseBills(tWarehouseBills);
        calculationResultVO.setWarehouseItemList(itemsList);
        return AjaxResult.success(calculationResultVO);
    }

    /**
     * 更新库存总帐当日实际
     *
     * @param tWarehouseBills
     * @param tWhgenlegs
     * @return
     */
    private void updateWhgenlegs(TWarehouseBills tWarehouseBills, List<Map<String, Object>> tWhgenlegs) {
        // 获取区间时间
        tWarehouseBills.setItemBsDateList(timeConversion(tWarehouseBills.getfBillingDeadline(), new Date()));
        // 查询时间区间内的仓储业务明细信息
        List<TWarehousebillsitems> warehousebillsitemsList = tWarehousebillsitemsMapper.selectListByCorpId(tWarehouseBills);
        // 如果没有则直接结束此方法
        if (CollectionUtils.isEmpty(warehousebillsitemsList)) {
            return;
        }
        tWhgenlegs.forEach(whgenleg -> {
            // 判断是否计算箱号 0为 不计算 1为计算
            boolean ifCntrno = "1".equals(whgenleg.get("ifCntrno").toString());
            // 组合一个库存总帐类使用
            TWhgenleg tWhgenleg = new TWhgenleg();
            tWhgenleg.setfCorpid(tWarehouseBills.getfCorpid());
            tWhgenleg.setfQtyblc(Long.parseLong(whgenleg.get("fQty").toString()));
            tWhgenleg.setfMarks((String) whgenleg.get("fMarks"));
            tWhgenleg.setfMblno((String) whgenleg.get("fMblno"));
            tWhgenleg.setfCntrno((String) whgenleg.get("fCntrno"));
            tWhgenleg.setfOriginalbilldate((Date) whgenleg.get("fOriginalbilldate"));
            tWhgenleg.setfGoodsid(Long.parseLong(whgenleg.get("fGoodsid").toString()));
            tWhgenleg.setfNetweightblc(new BigDecimal(whgenleg.get("fNetweight").toString()));
            tWhgenleg.setfGrossweightblc(new BigDecimal(whgenleg.get("fGrossweight").toString()));
            tWhgenleg.setfWarehouseid(Long.parseLong(whgenleg.get("warehouseLocationid").toString()));

            log.info("每次yuan件数、毛重、净重、：{}, {}, {}, {}", tWhgenleg.getfQtyblc(), tWhgenleg.getfVolumnblc(), tWhgenleg.getfNetweightblc(),
                    tWhgenleg.getfGrossweightblc());

            List<TWarehousebillsitems> itemList = new ArrayList<>();
            for (TWarehousebillsitems li : warehousebillsitemsList) {
                if ((!Objects.equals(li.getfGoodsid(), tWhgenleg.getfGoodsid())) ||
                        (!Objects.equals(li.getfWarehouselocid(), tWhgenleg.getfWarehouseid()) || Objects.equals(li.getfTransferWarehouselocid(), tWhgenleg.getfWarehouseid())) ||
                        !li.getfMblno().equals(tWhgenleg.getfMblno()) ||
                        !Objects.equals(li.getfOriginalbilldate(), tWhgenleg.getfOriginalbilldate()) ||
                        (!li.getfMarks().equals(tWhgenleg.getfMarks())) ||
                        (ifCntrno && !li.getfCntrno().equals(tWhgenleg.getfCntrno()))
                ) {
                    continue;
                }
                itemList.add(li);
            }
            // 如果找不到符合条件的明细信息 直接结束此方法
            if (CollectionUtils.isNotEmpty(itemList)) {
                itemList.forEach(li -> updateWhgenlegCalculate(tWhgenleg, li));
            }
            log.info("每次的件数、毛重、净重、：{}, {}, {}, {}", tWhgenleg.getfQtyblc(), tWhgenleg.getfVolumnblc(), tWhgenleg.getfNetweightblc(),
                    tWhgenleg.getfGrossweightblc());
            // 覆盖数量、毛重、净重
            whgenleg.put("fQty", tWhgenleg.getfQtyblc());
            whgenleg.put("fNetweight", tWhgenleg.getfNetweightblc());
            whgenleg.put("fGrossweight", tWhgenleg.getfGrossweightblc());
        });
    }

    private void updateWhgenlegs1(TWarehouseBills tWarehouseBills, List<CalculateStorageFeesInfoVO> infoVOList) {
        // 获取区间时间
        tWarehouseBills.setItemBsDateList(timeConversion(tWarehouseBills.getfBillingDeadline(), new Date()));
        // 查询时间区间内的仓储业务明细信息
        List<TWarehousebillsitems> warehousebillsitemsList = tWarehousebillsitemsMapper.selectListByCorpId(tWarehouseBills);
        // 如果没有则直接结束此方法
        if (CollectionUtils.isEmpty(warehousebillsitemsList)) {
            return;
        }
        infoVOList.forEach(whgenleg -> {
            // 判断是否计算箱号 0为 不计算 1为计算
            boolean ifCntrno = "1".equals(whgenleg.getIfCntrno());
            // 组合一个库存总帐类使用
            TWhgenleg tWhgenleg = new TWhgenleg();
            tWhgenleg.setfCorpid(tWarehouseBills.getfCorpid());
            tWhgenleg.setfQtyblc(whgenleg.getFQty());
            tWhgenleg.setfMarks(whgenleg.getFMarks());
            tWhgenleg.setfMblno(whgenleg.getFMblno());
            tWhgenleg.setfCntrno(whgenleg.getFCntrno());
            tWhgenleg.setfGoodsid(whgenleg.getFGoodsid());
            tWhgenleg.setfNetweightblc(whgenleg.getFNetweight());
            tWhgenleg.setfGrossweightblc(whgenleg.getFGrossweight());
            tWhgenleg.setfWarehouseid(whgenleg.getWarehouseLocationid());
            tWhgenleg.setfOriginalbilldate(whgenleg.getFOriginalbilldate());

            log.info("每次yuan件数、毛重、净重、：{}, {}, {}, {}", tWhgenleg.getfQtyblc(), tWhgenleg.getfVolumnblc(), tWhgenleg.getfNetweightblc(),
                    tWhgenleg.getfGrossweightblc());

            List<TWarehousebillsitems> itemList = new ArrayList<>();
            for (TWarehousebillsitems li : warehousebillsitemsList) {
                if ((!Objects.equals(li.getfGoodsid(), tWhgenleg.getfGoodsid())) ||
                        (!Objects.equals(li.getfWarehouselocid(), tWhgenleg.getfWarehouseid()) ||
                                Objects.equals(li.getfTransferWarehouselocid(), tWhgenleg.getfWarehouseid())) ||
                        !li.getfMblno().equals(tWhgenleg.getfMblno()) ||
                        !Objects.equals(li.getfOriginalbilldate(), tWhgenleg.getfOriginalbilldate()) ||
                        (!li.getfMarks().equals(tWhgenleg.getfMarks())) ||
                        (ifCntrno && !li.getfCntrno().equals(tWhgenleg.getfCntrno()))
                ) {
                    continue;
                }
                itemList.add(li);
            }
            // 如果找不到符合条件的明细信息 直接结束此方法
            if (CollectionUtils.isNotEmpty(itemList)) {
                itemList.forEach(li -> updateWhgenlegCalculate(tWhgenleg, li));
            }
            log.info("每次的件数、毛重、净重、：{}, {}, {}, {}", tWhgenleg.getfQtyblc(), tWhgenleg.getfVolumnblc(), tWhgenleg.getfNetweightblc(),
                    tWhgenleg.getfGrossweightblc());
            // 覆盖数量、毛重、净重
            whgenleg.setFQty(tWhgenleg.getfQtyblc());
            whgenleg.setFNetweight(tWhgenleg.getfNetweightblc());
            whgenleg.setFGrossweight(tWhgenleg.getfGrossweightblc());
        });
    }

    /**
     * 根据仓储明细更新库存总帐数量、毛重、净重
     *
     * @param whgenleg
     * @param item
     * @return
     */
    private TWhgenleg updateWhgenlegCalculate(TWhgenleg whgenleg, TWarehousebillsitems item) {
        // 入库
        if (WarehouseTypeEnum.SJRK.getType().equals(item.getfBilltype())) {
            // 修改数量
            whgenleg.setfQtyblc(whgenleg.getfQtyblc() - item.getfQty());
            // 修改毛重
            BigDecimal grossweightblc = whgenleg.getfGrossweightblc().subtract(item.getfGrossweight()).setScale(2, RoundingMode.HALF_UP);
            whgenleg.setfGrossweightblc(grossweightblc);
            // 修改净重
            BigDecimal netweightcBlc = whgenleg.getfNetweightblc().subtract(item.getfNetweight()).setScale(2, RoundingMode.HALF_UP);
            whgenleg.setfNetweightc(netweightcBlc);
            return whgenleg;
        } else
            // 出库
            if (WarehouseTypeEnum.SJCK.getType().equals(item.getfBilltype())) {
                // 修改数量
                whgenleg.setfQtyblc(whgenleg.getfQtyblc() + item.getfQty());
                // 修改毛重
                BigDecimal grossweightblc = whgenleg.getfGrossweightblc().add(item.getfGrossweight());
                whgenleg.setfGrossweightblc(grossweightblc);
                // 修改净重
                BigDecimal netweightcBlc = whgenleg.getfNetweightblc().add(item.getfNetweight());
                whgenleg.setfNetweightc(netweightcBlc);
                return whgenleg;
            } else
                // 调拨
                if (WarehouseTypeEnum.CKDB.getType().equals(item.getfBilltype())) {
                    BigDecimal netweightcBlc;
                    BigDecimal grossweightblc;
                    if (Objects.equals(item.getfTransferWarehouselocid(), whgenleg.getfWarehouseid())) {
                        // 修改数量
                        whgenleg.setfQtyblc(whgenleg.getfQtyblc() - item.getfQty());
                        // 修改毛重
                        grossweightblc = whgenleg.getfGrossweightblc().subtract(item.getfGrossweight()).setScale(2, RoundingMode.HALF_UP);
                        // 修改净重
                        netweightcBlc = whgenleg.getfNetweightblc().subtract(item.getfNetweight()).setScale(2, RoundingMode.HALF_UP);
                    } else {
                        // 修改数量
                        whgenleg.setfQtyblc(whgenleg.getfQtyblc() + item.getfQty());
                        // 修改毛重
                        grossweightblc = whgenleg.getfGrossweightblc().add(item.getfGrossweight());
                        // 修改净重
                        netweightcBlc = whgenleg.getfNetweightblc().add(item.getfNetweight());
                    }
                    whgenleg.setfGrossweightblc(grossweightblc);
                    whgenleg.setfNetweightc(netweightcBlc);
                    return whgenleg;
                } else
                    // 货权转移
                    if (WarehouseTypeEnum.HQZY.getType().equals(item.getfBilltype())) {
                        BigDecimal netweightcBlc;
                        BigDecimal grossweightblc;

                        if (Objects.equals(item.getfTocorpid(), whgenleg.getfCorpid())) {
                            // 修改数量
                            whgenleg.setfQtyblc(whgenleg.getfQtyblc() - item.getfQty());
                            // 修改毛重
                            grossweightblc = whgenleg.getfGrossweightblc().subtract(item.getfGrossweight()).setScale(2, RoundingMode.HALF_UP);
                            // 修改净重
                            netweightcBlc = whgenleg.getfNetweightblc().subtract(item.getfNetweight()).setScale(2, RoundingMode.HALF_UP);
                        } else {
                            // 修改数量
                            whgenleg.setfQtyblc(whgenleg.getfQtyblc() + item.getfQty());
                            // 修改毛重
                            grossweightblc = whgenleg.getfGrossweightblc().add(item.getfGrossweight());
                            // 修改净重
                            netweightcBlc = whgenleg.getfNetweightblc().add(item.getfNetweight());
                        }
                        whgenleg.setfGrossweightblc(grossweightblc);
                        whgenleg.setfNetweightc(netweightcBlc);
                        return whgenleg;
                    }
        return whgenleg;
    }

    /**
     * 时间格式转换
     *
     * @param start
     * @param end
     * @return
     */
    private List<String> timeConversion(Date start, Date end) {
        List<String> timeList = new ArrayList();
        timeList.add(DateUtils.dateToString(DateUtils.dateConversionMax(start)));
        timeList.add(DateUtils.dateToString(DateUtils.dateConversionMax(end)));
        return timeList;
    }

    /**
     * 批量生成计算仓储费信息
     *
     * @param warehouseBills
     * @param mapItem
     * @param loginUser
     * @return
     */
    public Map<String, Object> getWarehouseItemsList(TWarehouseBills warehouseBills, List<Map<String, Object>> mapItem, LoginUser loginUser, String warehouse) {
        Map<String, Object> map = new HashMap<>();
        BigDecimal sumAmt = new BigDecimal(0);
        List<TWarehousebillsfees> itemsList = new ArrayList<>();
        List<SysDictData> taxRate = sysDictDataMapper.selectDictDataByType("tax_rate");
        for (Map<String, Object> item : mapItem) {
            if (StringUtils.isNull(item.get("fBillingway"))) {
                map.put("error", "单号：" + item.get("fBillno") + ",业务日期:" + item.get("fBsdate") + "未找到库存总账的计费单位，请确认");
                return map;
            }
            CalculateStorageFeesDTO storageFeesDto = new CalculateStorageFeesDTO();
            storageFeesDto.setfCorpid(warehouseBills.getfCorpid());
            storageFeesDto.setCangKey(warehouse);
            storageFeesDto.setWarehouseId(Long.parseLong(String.valueOf(item.get("warehouse"))));
            Date fBsdate = (Date) item.get("fBsdate");
            String fBilltype = (String) item.get("fBilltype");
            String fGoodsid = (String) item.get("fTypeid");
            if (StringUtils.isNotEmpty(fGoodsid)) {
                fGoodsid = "\"" + fGoodsid + "\"";
            }
            storageFeesDto.setfGoodsid(fGoodsid);
            long fId = Long.valueOf(String.valueOf(item.get("fId")));
            // 累计计费天数
            storageFeesDto.setEarlySumDays(DateUtils.getDateDay((Date) item.get("fChargedate"), (Date) item.get("fOriginalbilldate")));
            // 库存天数
            long fInventoryDays = 0L;
            // 要计费天数
            long fBillingDays = DateUtils.getDateDay(warehouseBills.getfBillingDeadline(), (Date) item.get("fOriginalbilldate"));
            if ("SJCK".equals(fBilltype)) {
                fInventoryDays = DateUtils.getDateDay(fBsdate, (Date) item.get("fChargedate"));
                fBillingDays = fInventoryDays;
                storageFeesDto.setStartTime((Date) item.get("fChargedate"));
                storageFeesDto.setEndTime(fBsdate);
            } else if (WarehouseTypeEnum.HQZY.getType().equals(fBilltype)) {
                fInventoryDays = DateUtils.getDateDay(warehouseBills.getfBillingDeadline(), fBsdate);
                storageFeesDto.setStartTime(fBsdate);
                storageFeesDto.setEndTime(warehouseBills.getfBillingDeadline());
            } else {
                storageFeesDto.setStartTime((Date) item.get("fOriginalbilldate"));
                storageFeesDto.setEndTime(warehouseBills.getfBillingDeadline());
                fBillingDays = DateUtils.getDateDay(warehouseBills.getfBillingDeadline(), (Date) item.get("fChargedate"));
                fInventoryDays = DateUtils.getDateDay(warehouseBills.getfBillingDeadline(), (Date) item.get("fOriginalbilldate"));
            }
            if (fBillingDays <= 0) {
                continue;
            }
            storageFeesDto.setDays(fBillingDays);
            storageFeesDto.setfMblno((String) item.get("fMblno"));
            // 赋值要计算的数量单位
            storageFeesDto.setfQty(new BigDecimal(String.valueOf(item.get("fQty"))));
            storageFeesDto.setfVolumn(new BigDecimal(String.valueOf(item.get("fQty"))));
            storageFeesDto.setfNetweight(new BigDecimal(String.valueOf(item.get("fNetweight"))));
            storageFeesDto.setfGrossweight(new BigDecimal(String.valueOf(item.get("fGrossweight"))));
            // 计算仓储费明细
            StorageFeeCalculationResultVO carryingCost = tWarehouseAgreementService.getCarryingCost(storageFeesDto);
            if (StringUtils.isNull(carryingCost)) {
                continue;
            }
            String mblno = "";
            if (StringUtils.isNotNull(item.get("fMblno"))) {
                mblno = item.get("fMblno").toString();
            }
            map.put("feeId", carryingCost.getFeeId());
            map.put("itemFeeId", carryingCost.getFeeId());
            sumAmt = sumAmt.add(carryingCost.getAmt()).setScale(2, RoundingMode.HALF_UP);
            TWarehousebillsfees fees = new TWarehousebillsfees();
            fees.setfFeeid(carryingCost.getFeeId());
            fees.setfDc("D");
            fees.setfAmt(carryingCost.getAmt());
            fees.setfQty(carryingCost.getQty());
            fees.setSrcId(fId);
            fees.setfMblno(mblno);
            fees.setRemark(carryingCost.getRemark());
            fees.setfFeeunitid(carryingCost.getUnit());
            fees.setfAmount(sumAmt);
            fees.setfBillstatus(2L);
            fees.setfCurrency("RMB");
            fees.setfBsdate(fBsdate);
            fees.setfBillingQty(carryingCost.getQty());
            fees.setfUnitprice(sumAmt);
            fees.setfBilltype(fBilltype);
            fees.setfBillingDays(fBillingDays);
            fees.setCreateTime(new Date());
            fees.setfWarehouseid(storageFeesDto.getWarehouseId());
            fees.setfPid(warehouseBills.getfId());
            fees.setfInventoryDays(fInventoryDays);
            fees.setfExrate(new BigDecimal(1));
            fees.setfCorpid(warehouseBills.getfCorpid());
            fees.setfMarks(item.get("fMarks").toString());
            fees.setSrcBillNo((String) item.get("fBillno"));
            fees.setfChargedate((Date) item.get("fChargedate"));
            fees.setCreateBy(loginUser.getUser().getUserName());
            fees.setfProductName(item.get("fGoodsids").toString());
            if ("SJCK".equals(fBilltype)) {
                fees.setfBillingDeadline(fBsdate);
            } else {
                fees.setfBillingDeadline(warehouseBills.getfBillingDeadline());
            }
            fees.setfTaxrate(new BigDecimal(taxRate.get(0).getDictValue()));
            fees.setfOriginalbilldate((Date) item.get("fOriginalbilldate"));
            fees.setfBillingway(Long.valueOf(String.valueOf(item.get("fBillingway"))));
            itemsList.add(fees);
        }
        map.put("sumAmt", sumAmt);
        map.put("itemsList", itemsList);
        return map;
    }

    /**
     * 出库明细计算仓储费
     *
     * @param tWarehouseBillsList
     * @param loginUser
     * @param billsType
     * @return
     */
    @Override
    @Transactional
    public AjaxResult calculateStorageFeesList(List<TWarehouseBills> tWarehouseBillsList, LoginUser loginUser, String billsType) {
        if (CollectionUtils.isEmpty(tWarehouseBillsList)) {
            return AjaxResult.error("请输入筛选条件,再计算仓储费");
        }
        // 取出明细id进行查询是否存在已计算仓储费的地方
        List<Long> ids = tWarehouseBillsList.stream().map(TWarehouseBills::getfId).distinct().collect(toList());
        // 判断是否存在仓库明细已被计算仓储费
        if (CollectionUtils.isNotEmpty(ids) && tWarehousebillsitemsMapper.selectIsCalculateStorageFeesByIdsOrType(ids, WarehouseTypeEnum.CALCULATE.getType()) > 0) {
            throw new WarehouseException("该出库已被计算仓储费");
        }
        List<TWarehousebillsfees> list = new ArrayList<>();
        for (TWarehouseBills tWarehouseBills : tWarehouseBillsList) {
            // 计划物资明细
            List<TWarehousebillsfees> itemsList = new ArrayList<>();
            // 查询 出库 货转的库存明细
            List<Map<String, Object>> warehousebillsitemsList = tWarehousebillsitemsMapper.selectStorageFeeItemList(tWarehouseBills);
            String cangKey = sysConfigServiceImpl.selectConfigByKey("agreement.warehouse");
            if (CollectionUtils.isNotEmpty(warehousebillsitemsList)) {
                Map<String, Object> mapItem = getWarehouseItemsList(tWarehouseBills, warehousebillsitemsList, loginUser, cangKey);
                if (mapItem.containsKey("error")) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error((String) mapItem.get("error"));
                }
                itemsList = (List<TWarehousebillsfees>) mapItem.get("itemsList");
            }
            if (CollectionUtils.isEmpty(itemsList)) {
                throw new WarehouseException("未找到合适的库存明细");
            }
            list.addAll(itemsList);
        }
        return AjaxResult.success(list);
    }

    /**
     * 计算出库仓储费
     * 待完成！！！！！！！！！
     *
     * @param fId
     * @return
     */
    @Override
    public AjaxResult calculateOutStockFee(Long fId) {
        TWarehouseBills tWarehouseBills = tWarehouseBillsMapper.selectTWarehousebillsById(fId);
        if (StringUtils.isNull(tWarehouseBills)) {
            return AjaxResult.error("未找到出库信息，请确认是否存在出库");
        }


        return null;
    }

    /**
     * 查询仓储仓管员角色用户
     */
    @Override
    public AjaxResult queryClerkRoleList() {
        return AjaxResult.success(sysUserMapper.selectUserByRole("库管"));
    }

    /**
     * 仓储费计算提交以及暂存
     *
     * @param warehouseBills
     * @param warehouseItems
     * @param warehouseFees
     * @param loginUser
     * @param billsType
     * @return
     */
    @Override
    @Transactional
    public AjaxResult insertStorageFee(String warehouseBills, String warehouseItems, String warehouseFees, LoginUser loginUser, String billsType) {
        TWarehouseBills tWarehousebills = JSON.parseObject(warehouseBills, TWarehouseBills.class);
        long fPid = 0L;
        boolean billstatus = tWarehousebills.getfBillstatus().equals(4L);
        if (billstatus && (StringUtils.isNull(warehouseItems) || "[]".equals(warehouseItems))) {
            return AjaxResult.error("未找到计费物资明细无法提交");
        }
        /*if (billstatus && (StringUtils.isNull(warehouseFees) || "[]".equals(warehouseFees))) {
            return AjaxResult.error("未找到应收款明细无法提交");
        }*/
        if (tWarehousebills.getfTimes() == null) {
            tWarehousebills.setfTimes(1L);
        } else {
            tWarehousebills.setfTimes(tWarehousebills.getfTimes() + 1);
        }
        if (StringUtils.isNotNull(tWarehousebills.getfId())) {
            fPid = tWarehousebills.getfId();
            tWarehousebills.setfBilltype(billsType);
            tWarehousebills.setUpdateTime(new Date());
            tWarehousebills.setUpdateBy(loginUser.getUser().getUserName());
            tWarehouseBillsMapper.updateTWarehousebills(tWarehousebills);
            tWarehousebillsfeesMapper.deleteByFPid(fPid);
            tWarehousebillsitemsMapper.deleteByFPid(fPid);
        } else {
            // 生成流水号
            Date time = new Date();
            String billNo = billnoSerialServiceImpl.getSerialNumber(WarehouseTypeEnum.JSCCF.getType(), time);
            tWarehousebills.setfBillno(billNo);
            tWarehousebills.setfDeptid(loginUser.getUser().getDeptId());
            tWarehousebills.setfBsdeptid(loginUser.getUser().getDeptId());
            tWarehousebills.setCreateBy(loginUser.getUser().getUserName());
            tWarehousebills.setCreateTime(new Date());
            tWarehousebills.setfBilltype(billsType);
            tWarehouseBillsMapper.insertTWarehousebills(tWarehousebills);
            fPid = tWarehousebills.getfId();
        }
        JSONArray warehouseJSON = JSONArray.parseArray(warehouseItems);
        List<TWarehousebillsfees> itemsList = JSONObject.parseArray(warehouseJSON.toJSONString(), TWarehousebillsfees.class);
        for (TWarehousebillsfees item : itemsList) {
            item.setSrcBillNo(tWarehousebills.getfBillno());
            item.setfPid(fPid);
            item.setfBillstatus(tWarehousebills.getfBillstatus());
            tWarehousebillsfeesMapper.insertTWarehousebillsfees(item);
        }
        if (StringUtils.isNotNull(warehouseFees) && !"[]".equals(warehouseFees)) {
            JSONArray feesJSON = JSON.parseArray(warehouseFees);
            List<TWarehousebillsfees> warehousebillsfeesList = JSON.parseArray(feesJSON.toJSONString(), TWarehousebillsfees.class);
            for (TWarehousebillsfees fees : warehousebillsfeesList) {
                fees.setfPid(fPid);
                fees.setfDc("D");
                fees.setfBilltype(WarehouseTypeEnum.JSCCF.getType());
                fees.setSrcBillNo(tWarehousebills.getfBillno());
                fees.setfBillstatus(tWarehousebills.getfBillstatus());
                tWarehousebillsfeesMapper.insertTWarehousebillsfees(fees);
            }
        }
        // 计算仓库状态
        calculationWarehouseService.calculationBillStatus(tWarehousebills);
        tWarehouseBillsMapper.updateTWarehousebills(tWarehousebills);
        if (billstatus) {
            String key = "warehouse.storageFeeCalculation.ApprovalFlow";
            SysConfig sysConfig = sysConfigMapper.checkConfigKeyUnique(key);
            if (StringUtils.isNull(sysConfig)) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error("系统参数异常，未找到开启审批流参数");
            }
            if ("0".equals(sysConfig.getConfigValue())) {
                AuditItems auditItems = new AuditItems();
                auditItems.setLevelId(0L);
                auditItems.setBillId(fPid);
                auditItems.setActId(150L);
                auditItems.setIffinalItem("F");
                auditItems.setBillNo(tWarehousebills.getfBillno());
                // 存储委托方（货权方）
                auditItems.setRefno1(tWarehousebills.getfCorpid() + "");
                // 存储业务类型（业务类型）
                auditItems.setRefno2(tWarehousebills.getfBilltype());
                // 存储提单号（提单号）
                auditItems.setRefno3(tWarehousebills.getfMblno());
                auditItems.setSendUserId(loginUser.getUser().getUserId());
                auditItems.setSendName(loginUser.getUsername());
                auditItems.setSendTime(new Date());
                auditItems.setAuditUserId(loginUser.getUser().getUserId());
                auditItems.setAuditItem(new Date());
                auditItems.setAuditOpTime(new Date());
                auditItems.setAuditMsg("提交");
                auditItems.setAuditStatus("O");
                auditItems.setFidStatus("f_billstatus");
                auditItems.setTimes(tWarehousebills.getfTimes());
                AjaxResult approvalFlow = auditItemsService.createApprovalFlow(auditItems);
                String code = approvalFlow.get("code").toString();
                if ("500".equals(code)) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                }
                return approvalFlow;
            } else {
                approvedStorageFee(fPid, 6L, new Date());
                return AjaxResult.success();
            }
        }
        return AjaxResult.success(tWarehousebills);
    }

    /**
     * 计算仓储费审核通过
     *
     * @param warehouseId 主表id
     * @param fettle      状态
     * @param date        审核时间
     */
    public void approvedStorageFee(Long warehouseId, Long fettle, Date date) {
        // 查出主表数据
        TWarehouseBills warehouseBills = tWarehouseBillsMapper.selectTWarehousebillsById(warehouseId);
        if (Objects.isNull(warehouseBills)) {
            throw new WarehouseException("未找到仓储信息");
        }
        List<TWarehousebillsfees> feesList = tWarehousebillsfeesMapper.selectWarehousebillsfeesByPId(warehouseBills.getfId());
        if (CollectionUtils.isEmpty(feesList)) {
            throw new WarehouseException("未找到需要更新的费用信息");
        }
        // 过滤出明细信息查询是否存在已计算仓储费
        List<Long> ids = feesList.stream().filter(li -> !li.getfBilltype().equals(WarehouseTypeEnum.KCZZ.getType()))
                .map(TWarehousebillsfees::getSrcId).distinct().collect(toList());
        if (CollectionUtils.isNotEmpty(ids) && tWarehousebillsitemsMapper.selectIsCalculateStorageFeesByIds(ids) > 0) {
            throw new WarehouseException("计算费用中存在已计算仓储费信息");
        }
        for (TWarehousebillsfees fees : feesList) {
            storageFeeUpdateItem(warehouseBills, fees);
        }
        warehouseBills.setfBillstatus(fettle);
        warehouseBills.setUpdateTime(new Date());
        tWarehouseBillsMapper.updateTWarehousebills(warehouseBills);
    }

    /**
     * 计算仓储费计算更新出库货转信息
     *
     * @param warehouseBills 主表信息
     * @param fees           仓储费信息
     */
    private void storageFeeUpdateItem(TWarehouseBills warehouseBills, TWarehousebillsfees fees) {
        Date chargeDate = DateUtils.addDays(fees.getfBillingDeadline(), 1);
        // 如果是库存总帐
        if (WarehouseTypeEnum.KCZZ.getType().equals(fees.getfBilltype())) {
            TWhgenleg whgenleg = new TWhgenleg();
            whgenleg.setfId(fees.getSrcId());
            whgenleg.setfChargedate(chargeDate);
            tWhgenlegMapper.updateTWhgenleg(whgenleg);
            // 如果计算之前信息
            if (!fees.getfBillingDeadline().after(warehouseBills.getUpdateTime())) {
                // 查询时间区间内的仓储业务明细信息
                List<String> timeList = new ArrayList<>();
                timeList.add(DateUtils.dateToString(DateUtils.dateConversionMin(fees.getfBillingDeadline())));
                timeList.add(DateUtils.dateToString(DateUtils.dateConversionMax(warehouseBills.getUpdateTime())));
                warehouseBills.setItemBsDateList(timeList);
                List<TWarehousebillsitems> warehousebillsitemsList = tWarehousebillsitemsMapper.selectListByCorpId(warehouseBills);
                // 过滤出出库、货转，更新对应仓储费计费日期
                List<TWarehousebillsitems> itemList = warehousebillsitemsList.stream().filter(li ->
                        li.getfBilltype().equals(WarehouseTypeEnum.SJCK.getType()) ||
                                li.getfBilltype().equals(WarehouseTypeEnum.HQZY.getType())).collect(toList());
                if (CollectionUtils.isNotEmpty(itemList)) {
                    itemList.forEach(li -> {
                        li.setfChargedate(chargeDate);
                        li.setUpdateTime(new Date());
                        tWarehousebillsitemsMapper.updateTWarehousebillsitems(li);
                    });
                }
            }
        } else {
            TWarehousebillsitems billsItem = new TWarehousebillsitems();
            billsItem.setfId(fees.getSrcId());
            billsItem.setfChargedate(chargeDate);
            if ("SJCK".equals(fees.getfBilltype())) {
                billsItem.setfStorageFeeDeadline(fees.getfBillingDeadline());
                billsItem.setIsCalculateStorageFees(WarehouseTypeEnum.CALCULATE.getType());
            }
            tWarehousebillsitemsMapper.updateTWarehousebillsitems(billsItem);
        }
    }

    @Override
    public AjaxResult insertStorageFeeList(List<StorageChargeInsert> storageChargeInsert, LoginUser loginUser, String billsType) {
        if (CollectionUtils.isEmpty(storageChargeInsert)) {
            return AjaxResult.error("请选择要保存的数据");
        }
        for (StorageChargeInsert chargeInsert : storageChargeInsert) {
            TWarehouseBills tWarehousebills = JSONArray.parseObject(chargeInsert.getWarehouseBills(), TWarehouseBills.class);
            long fPid = 0L;
            boolean billstatus = tWarehousebills.getfBillstatus().equals(4L);
            if (billstatus && (StringUtils.isNull(chargeInsert.getWarehouseItems()) || "[]".equals(chargeInsert.getWarehouseItems()))) {
                return AjaxResult.error("未找到计费物资明细无法提交");
            }
        /*if (billstatus && (StringUtils.isNull(warehouseFees) || "[]".equals(warehouseFees))) {
            return AjaxResult.error("未找到应收款明细无法提交");
        }*/
            if (tWarehousebills.getfTimes() == null) {
                tWarehousebills.setfTimes(1L);
            } else {
                tWarehousebills.setfTimes(tWarehousebills.getfTimes() + 1);
            }
            if (StringUtils.isNotNull(tWarehousebills.getfId())) {
                fPid = tWarehousebills.getfId();
                tWarehousebills.setUpdateTime(new Date());
                tWarehousebills.setUpdateBy(loginUser.getUser().getUserName());
                tWarehouseBillsMapper.updateTWarehousebills(tWarehousebills);
                tWarehousebillsfeesMapper.deleteByFPid(fPid);
                tWarehousebillsitemsMapper.deleteByFPid(fPid);
            } else {
                // 生成流水号
                Date time = new Date();
                String billNo = billnoSerialServiceImpl.getSerialNumber(WarehouseTypeEnum.JSCCF.getType(), time);
                tWarehousebills.setfBillno(billNo);
                tWarehousebills.setfDeptid(loginUser.getUser().getDeptId());
                tWarehousebills.setfBsdeptid(loginUser.getUser().getDeptId());
                tWarehousebills.setCreateBy(loginUser.getUser().getUserName());
                tWarehousebills.setCreateTime(new Date());
                tWarehousebills.setfBilltype(billsType);
                tWarehouseBillsMapper.insertTWarehousebills(tWarehousebills);
                fPid = tWarehousebills.getfId();
            }
            JSONArray warehouseJSON = JSONArray.parseArray(chargeInsert.getWarehouseItems());
            List<TWarehousebillsfees> itemsList = JSONObject.parseArray(warehouseJSON.toJSONString(), TWarehousebillsfees.class);
            for (TWarehousebillsfees item : itemsList) {
                item.setfId(null);
                item.setSrcBillNo(tWarehousebills.getfBillno());
                item.setfPid(fPid);
                item.setfBillstatus(tWarehousebills.getfBillstatus());
                tWarehousebillsfeesMapper.insertTWarehousebillsfees(item);
            }
            if (StringUtils.isNotNull(chargeInsert.getWarehouseFees()) && !"[]".equals(chargeInsert.getWarehouseFees())) {
                JSONArray feesJSON = JSONArray.parseArray(chargeInsert.getWarehouseFees());
                List<TWarehousebillsfees> warehousebillsfeesList = JSONObject.parseArray(feesJSON.toJSONString(), TWarehousebillsfees.class);
                for (TWarehousebillsfees fees : warehousebillsfeesList) {
                    fees.setfId(null);
                    fees.setfPid(fPid);
                    fees.setfDc("D");
                    fees.setfBilltype(WarehouseTypeEnum.JSCCF.getType());
                    fees.setSrcBillNo(tWarehousebills.getfBillno());
                    fees.setfBillstatus(tWarehousebills.getfBillstatus());
                    tWarehousebillsfeesMapper.insertTWarehousebillsfees(fees);
                }
            }
            if (billstatus) {
                String key = "warehouse.storageFeeCalculation.ApprovalFlow";
                SysConfig sysConfig = sysConfigMapper.checkConfigKeyUnique(key);
                if (StringUtils.isNull(sysConfig)) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error("系统参数异常，未找到开启审批流参数");
                }
                if ("0".equals(sysConfig.getConfigValue())) {
                    AuditItems auditItems = new AuditItems();
                    auditItems.setLevelId(0L);
                    auditItems.setBillId(fPid);
                    auditItems.setActId(150L);
                    auditItems.setIffinalItem("F");
                    auditItems.setBillNo(tWarehousebills.getfBillno());
                    // 存储委托方（货权方）
                    auditItems.setRefno1(tWarehousebills.getfCorpid() + "");
                    // 存储业务类型（业务类型）
                    auditItems.setRefno2(billsType);
                    // 存储提单号（提单号）
                    auditItems.setRefno3(tWarehousebills.getfMblno());
                    auditItems.setSendUserId(loginUser.getUser().getUserId());
                    auditItems.setSendName(loginUser.getUsername());
                    auditItems.setSendTime(new Date());
                    auditItems.setAuditUserId(loginUser.getUser().getUserId());
                    auditItems.setAuditItem(new Date());
                    auditItems.setAuditOpTime(new Date());
                    auditItems.setAuditMsg("提交");
                    auditItems.setAuditStatus("O");
                    auditItems.setFidStatus("f_billstatus");
                    auditItems.setTimes(tWarehousebills.getfTimes());
                    AjaxResult approvalFlow = auditItemsService.createApprovalFlow(auditItems);
                    String code = approvalFlow.get("code").toString();
//                Long code = Long.valueOf(String.valueOf(ajaxResult.get("code"))).longValue();
                    if ("500".equals(code)) {
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    }
                    return approvalFlow;
                } else {
                    approvedStorageFee(fPid, 6L, new Date());
                    return AjaxResult.success();
                }
            }
        }
        return AjaxResult.success();
    }

    /**
     * 根据id查询仓储费计算信息
     *
     * @param fId
     * @return
     */
    @Override
    public AjaxResult selectStorageFeeById(Long fId) {
        TWarehouseBills tWarehouseBills = tWarehouseBillsMapper.selectTWarehousebillsById(fId);
        if (StringUtils.isNull(tWarehouseBills)) {
            return AjaxResult.error("未找到信息，请刷新页面重试");
        }
        Map<String, Object> map = new HashMap<>();
        TWarehousebillsfees warehousebillsfees = new TWarehousebillsfees();
        warehousebillsfees.setfPid(fId);
        List<TWarehousebillsfees> warehouseFeesList = tWarehousebillsfeesMapper.selectTWarehousebillsfeesList(warehousebillsfees);

        List<TWarehousebillsfees> itemsList = warehouseFeesList.stream().filter(li -> StringUtils.isNotNull(li.getSrcId()))
                .collect(toList());
        List<TWarehousebillsfees> feesList = warehouseFeesList.stream().filter(li -> StringUtils.isNull(li.getSrcId()))
                .collect(toList());
        // 查出所有仓库 给后续匹配仓库名字使用
        List<TWarehouse> warehouseList = tWarehouseMapper.selectTWarehouseList(new TWarehouse());
        itemsList.forEach(li -> {
            Optional<TWarehouse> first = warehouseList.stream().filter(warehouse -> Objects.equals(warehouse.getfId(), li.getfWarehouseid()))
                    .findFirst();
            first.ifPresent(tWarehouse -> li.setWarehouseName(tWarehouse.getfName()));
        });
        TGoods tGoods = new TGoods();
        tGoods.setfStatus("0");
        tGoods.setDelFlag("0");
        List<TGoods> goods = tGoodsMapper.selectTGoodsList(tGoods);
        TFees tFees = new TFees();
        tFees.setfStatus("2");
        tFees.setDelFlag("0");
        List<TFees> feesLists = tFeesMapper.selectTFeesList(tFees);
        // 查询联系人
        List<SysUser> sysUserList = new ArrayList<>();
        SysUser sysUser = sysUserMapper.selectUserByUserName(tWarehouseBills.getCreateBy());
        if (StringUtils.isNotNull(sysUser)) {
            sysUserList.add(sysUser);
        }
        TCorps corps = tCorpsMapper.selectTCorpsById(tWarehouseBills.getfCorpid());
        map.put("corps", corps);
        map.put("goodsList", goods);
        map.put("feesList", feesLists);
        map.put("sysUser", sysUserList);
        map.put("warehouse", tWarehouseBills);
        map.put("warehouseFeesList", feesList);
        map.put("warehouseItemsList", itemsList);
        return AjaxResult.success(map);
    }

    // 入库 收费明细 校验
    public Long check(BigDecimal number, BigDecimal unitPrice) {
        BigDecimal result1 = number.multiply(unitPrice);
        // 保留两位小数且四舍五入
        result1 = result1.setScale(2, BigDecimal.ROUND_HALF_UP);
        // 转换去掉小数点
        String result = result1.toString().replace(".", "");
        return Long.valueOf(result);
    }

    /**
     * 修改详情主表
     *
     * @param tWarehousebills 详情主表
     * @return 结果
     */
    @Override
    public int updateTWarehousebills(TWarehouseBills tWarehousebills) {
        tWarehousebills.setUpdateTime(DateUtils.getNowDate());
        return tWarehouseBillsMapper.updateTWarehousebills(tWarehousebills);
    }

    /**
     * 批量删除详情主表
     *
     * @param fIds 需要删除的详情主表ID
     * @return 结果
     */
    @Override
    public AjaxResult deleteTWarehousebillsByIds(Long[] fIds) {
        // 取出业务编号、 放入 billno_del
        for (Long id : fIds) {
            // 1、查询主表信息
            TWarehouseBills tWarehousebills = tWarehouseBillsMapper.selectTWarehousebillsById(id);
            // 查询对应库存明细是否允许删除
            if (tWarehousebillsitemsMapper.selectItemFStatusByFPid(id) != 0) {
                return AjaxResult.error("删除失败，该单据库存明细已入账");
            }
            // 2、业务编号、客存编号 放入 billno_del
            BillnoDel billnoDel = new BillnoDel();
            billnoDel.setBillType(tWarehousebills.getfBilltype());
            billnoDel.setBillNo(tWarehousebills.getfBillno());
            billnoDelMapper.insertBillnoDel(billnoDel);
        }
        tWarehouseBillsMapper.deleteTWarehousebillsByIds(fIds);
        return AjaxResult.success();
    }

    @Override
    public int deleteTWarehousebills(Long[] fIds) {
        // 取出业务编号、 放入 billno_del
        for (Long id : fIds) {
            // 1、查询主表信息
            TWarehouseBills tWarehousebills = tWarehouseBillsMapper.selectTWarehousebillsById(id);
            // 2、业务编号、客存编号 放入 billno_del
            BillnoDel billnoDel = new BillnoDel();
            billnoDel.setBillType(tWarehousebills.getfBilltype());
            billnoDel.setBillNo(tWarehousebills.getfBillno());
            billnoDelMapper.insertBillnoDel(billnoDel);
        }
        return tWarehouseBillsMapper.deleteKHTWarehousebillsByIds(fIds);

    }

    @Override
    public AjaxResult queryRemove(Long fId) {
        // 查询主表明细
        TWarehouseBills tWarehousebills = tWarehouseBillsMapper.selectTWarehousebillsById(fId);

        // 查询仓库明细从表数据
        TWarehousebillsitems tWarehousebillsitems = new TWarehousebillsitems();
        tWarehousebillsitems.setfPid(tWarehousebills.getfId());
        List<Map<String, Object>> mapList = tWarehousebillsitemsMapper.selectGoodsTransferitemsList(tWarehousebillsitems);

        // 查询仓库费用明细表数据
        TWarehousebillsfees tWarehousebillsfees = new TWarehousebillsfees();
        tWarehousebillsfees.setfPid(tWarehousebills.getfId());
        List<TWarehousebillsfees> warehousebillsfees = tWarehousebillsfeesMapper.selectTWarehousebillsfeesList(tWarehousebillsfees);

        // 查询附件表数据
        TEnclosure enclosure = new TEnclosure();
        enclosure.setfPid(tWarehousebills.getfId());
        List<TEnclosure> enclosures = tEnclosureMapper.selectTEnclosureList(enclosure);
        if (StringUtils.isNull(tWarehousebills)) {
            return AjaxResult.success("0");
        } else if (StringUtils.isNotNull(tWarehousebills)
                && StringUtils.isEmpty(warehousebillsfees)
                && StringUtils.isEmpty(enclosures)
                && StringUtils.isEmpty(mapList)) {
            return AjaxResult.success("1");
        } else {
            return AjaxResult.success("2");
        }
    }

    /**
     * 删除详情主表信息
     *
     * @param fId 详情主表ID
     * @return 结果
     */
    @Override
    public int deleteTWarehousebillsById(Long fId) {
        return tWarehouseBillsMapper.deleteTWarehousebillsById(fId);
    }

    @Override
    public String getWarehouseOutStockBillsNo(TWarehouseBills tWarehouseBills) {
        return null;
    }

    /**
     * 撤销仓储费计费入库
     *
     * @param fId
     * @param loginUser
     * @param billsType
     * @return
     */
    @Override
    @Transactional
    public AjaxResult revokeTWarehousebillsById(Long fId, LoginUser loginUser, String billsType) {
        // 查询 仓库主表信息、库存明细信息
        TWarehouseBills tWarehousebills = tWarehouseBillsMapper.selectTWarehousebillsById(fId);
        // 修改主表信息
        tWarehousebills.setUpdateBy(loginUser.getUser().getUserName());
        tWarehousebills.setUpdateTime(new Date());
        tWarehousebills.setfBillstatus(2L); //撤销状态
        tWarehousebills.setfReviewDate(null);// 审核通过时间清空
        Long timestamp = DateUtils.getTimestamp(new Date());
        tWarehousebills.setfDateChanged(timestamp.toString() + (int) (Math.random() * 900) + 100);
        TWarehousebillsitems itemInFo = tWarehousebillsitemsMapper.selectItemQtyByFPid(tWarehousebills.getfId());
        tWarehousebills.setfQty(itemInFo.getfQty());
        tWarehousebills.setfNetweight(itemInFo.getfNetweight());
        tWarehousebills.setfGrossweight(itemInFo.getfGrossweight());
        tWarehousebillsfeesMapper.warehouseFeesFollowUpdate(tWarehousebills.getfId(), 2L, new Date());
        // 判断是否出库
        if (tWarehousebills.getfBilltype().equals(WarehouseTypeEnum.SJCK.getType())) {
            cancellationInStockFee(tWarehousebills);
        } else if (WarehouseTypeEnum.JSCCF.getType().equals(tWarehousebills.getfBilltype())) {
            List<TWarehousebillsfees> feesList = tWarehousebillsfeesMapper.selectWarehousebillsfeesByPId(fId);
            // 取出本次变更的日期
            Date chargedate = DateUtils.dateAdd(tWarehousebills.getfBillingDeadline(), 1);
            // 过滤出总帐信息id集合查询是否存在变更的
            List<Long> generalLedgerIds = feesList.stream().filter(li -> Objects.nonNull(li.getSrcId()) && Objects.equals(WarehouseTypeEnum.KCZZ.getType(), li.getfBilltype()))
                    .map(TWarehousebillsfees::getSrcId).collect(toList());
            // 判断库存总账是否存在二次计算
            if (!generalLedgerIds.isEmpty() && tWhgenlegMapper.queryChangedByFchargedate(generalLedgerIds, chargedate) > 0) {
                throw new WarehouseException("审批撤销失败，库存总账存在二次计算");
            }
            // 过滤货转库信息id集合查询是否存在变更的
            List<Long> forwardingIds = feesList.stream().filter(li -> Objects.nonNull(li.getSrcId()) && Objects.equals(WarehouseTypeEnum.HQZY.getType(), li.getfBilltype()))
                    .map(TWarehousebillsfees::getSrcId).collect(toList());
            // 判断货转是否存在二次计算
            if (!forwardingIds.isEmpty() && tWarehousebillsitemsMapper.queryChangedByFchargedate(forwardingIds, chargedate) > 0) {
                throw new WarehouseException("审批撤销失败，货转明细存在二次计算");
            }
            for (TWarehousebillsfees wareItem : feesList) {
                if (StringUtils.isNull(wareItem.getSrcId())) {
                    continue;
                }
                if ("KCZZ".equals(wareItem.getfBilltype())) {
                    TWhgenleg whgenleg = new TWhgenleg();
                    whgenleg.setfId(wareItem.getSrcId());
                    whgenleg.setfChargedate(wareItem.getfChargedate());
                    tWhgenlegMapper.updateTWhgenleg(whgenleg);
                    // 如果计算之前信息
                    if (!wareItem.getfBillingDeadline().after(tWarehousebills.getUpdateTime())) {
                        // 查询时间区间内的仓储业务明细信息
                        List<String> timeList = new ArrayList<>();
                        timeList.add(DateUtils.dateToString(DateUtils.dateConversionMin(wareItem.getfBillingDeadline())));
                        timeList.add(DateUtils.dateToString(DateUtils.dateConversionMax(tWarehousebills.getUpdateTime())));
                        tWarehousebills.setItemBsDateList(timeList);
                        List<TWarehousebillsitems> warehousebillsitemsList = tWarehousebillsitemsMapper.selectListByCorpId(tWarehousebills);
                        // 过滤出出库、货转，更新对应仓储费计费日期
                        List<TWarehousebillsitems> itemList = warehousebillsitemsList.stream().filter(li ->
                                li.getfBilltype().equals(WarehouseTypeEnum.SJCK.getType()) ||
                                        li.getfBilltype().equals(WarehouseTypeEnum.HQZY.getType())).collect(toList());
                        if (CollectionUtils.isNotEmpty(itemList)) {
                            itemList.forEach(li -> {
                                li.setfChargedate(wareItem.getfChargedate());
                                li.setUpdateTime(new Date());
                                tWarehousebillsitemsMapper.updateTWarehousebillsitems(li);
                            });
                        }
                    }
                } else {
                    TWarehousebillsitems billsItem = new TWarehousebillsitems();
                    billsItem.setfId(wareItem.getSrcId());
                    billsItem.setfId(wareItem.getSrcId());
                    if (!"SJCK".equals(wareItem.getfBilltype())) {
                        billsItem.setfChargedate(wareItem.getfBillingDeadline());
                        tWarehousebillsitemsMapper.updateTWarehousebillsitems(billsItem);
                    } else {
                        billsItem.setfChargedate(wareItem.getfChargedate());
                        billsItem.setIsCalculateStorageFees(WarehouseTypeEnum.NOT_CALCULATE.getType());
                        tWarehousebillsitemsMapper.agreementApprovalRejected(billsItem);
                    }
                }
            }
        }
        tWarehouseBillsMapper.updateTWarehousebills(tWarehousebills);
        return AjaxResult.success(tWarehousebills.getfDateChanged());
    }

    /**
     * 撤销入库费用信息，并更新子订单
     *
     * @param tWarehousebills 订单信息
     */
    private void cancellationInStockFee(TWarehouseBills tWarehousebills) {
        // 查询出库费用信息
        List<TWarehousebillsfees> feesList = tWarehousebillsfeesMapper.selectWarehousebillsfeesByPId(tWarehousebills.getfId());
        // 获取仓储费，并判断费用中是否存在仓储费
        TFees ccf = tFeesMapper.seletFeesByCCF();
        if (Objects.isNull(ccf)) {
            throw new WarehouseException("未找到仓储费费用信息");
        }
        // 过滤出费用类型等于仓储费并且有商机id，并取出来进行更新仓储费计费日期
        List<Long> itemIds = feesList.stream().filter(li -> Objects.equals(li.getfFeeid(), ccf.getfId()) && Objects.nonNull(li.getSrcId()))
                .map(TWarehousebillsfees::getSrcId).distinct().collect(toList());
        itemIds.forEach(id -> tWarehousebillsitemsMapper.updatefStorageFeeDeadlinefPid(id));
    }

    /**
     * 撤销已审核通过的接单入库信息
     *
     * @param fId
     * @return
     */
    @Override
    @Transactional
    public AjaxResult withdrawOrdersById(Long fId) {
        // 查询 仓库主表信息、库存明细信息
        TWarehouseBills tWarehousebills = tWarehouseBillsMapper.selectTWarehousebillsById(fId);
        if (tWarehousebills.getWarehouseStatus() != 6L) {
            return AjaxResult.error("主单据状态异常，请确认单据状态是否已审核通过");
        }
        tWarehousebills.setUpdateTime(new Date());
        tWarehousebills.setWarehouseStatus(2L); //撤销状态
        tWarehousebills.setUpdateBy(SecurityUtils.getUsername());
        Long timestamp = DateUtils.getTimestamp(new Date());
        tWarehousebills.setfDateChanged(timestamp.toString() + (int) (Math.random() * 900) + 100);
        TWarehousebillsitems itemInFo = tWarehousebillsitemsMapper.selectItemQtyByFPid(tWarehousebills.getfId());
        tWarehousebills.setfQty(itemInFo.getfQty());
        tWarehousebills.setfNetweight(itemInFo.getfNetweight());
        tWarehousebills.setfGrossweight(itemInFo.getfGrossweight());
        tWarehouseBillsMapper.updateTWarehousebills(tWarehousebills);
        return AjaxResult.success(tWarehousebills.getfDateChanged());
    }

    /**
     * 查询单据是否允许变更
     *
     * @param sysCheckCode
     * @return 结果
     */
    @Override
    public boolean checkCode(SysCheckCode sysCheckCode) {
        String dateChanged = "";
        switch (sysCheckCode.getfType()) {
            case "warehouse":
                // 查询仓储业务
                TWarehouseBills warehouseBills = tWarehouseBillsMapper.selectTWarehousebillsById(sysCheckCode.getfId());
                if (StringUtils.isNull(warehouseBills)) {
                    return false;
                }
                if (StringUtils.isNotNull(sysCheckCode.getfId()) && StringUtils.isEmpty(warehouseBills.getfDateChanged())) {
                    Long timestamp = DateUtils.getTimestamp(new Date());
                    warehouseBills.setUpdateTime(new Date());
                    warehouseBills.setUpdateBy(SecurityUtils.getUsername());
                    warehouseBills.setfDateChanged(timestamp.toString() + (int) (Math.random() * 900) + 100);
                    tWarehouseBillsMapper.updateTWarehousebills(warehouseBills);
                    return true;
                }
                dateChanged = warehouseBills.getfDateChanged();
                break;
            case "freight":
                // 查询运价维护业务
                TSeaprice seaprice = tSeapriceMapper.selectTSeapriceById(sysCheckCode.getfId());
                if (StringUtils.isNull(seaprice)) {
                    return false;
                }
                if (StringUtils.isNotNull(sysCheckCode.getfId()) && StringUtils.isEmpty(seaprice.getfDateChanged())) {
                    Long timestamp = DateUtils.getTimestamp(new Date());
                    seaprice.setUpdateTime(new Date());
                    seaprice.setUpdateBy(SecurityUtils.getUsername());
                    seaprice.setfDateChanged(timestamp.toString() + (int) (Math.random() * 900) + 100);
                    tSeapriceMapper.updateTSeaprice(seaprice);
                    return true;
                }
                dateChanged = seaprice.getfDateChanged();
                break;
        }
        if (StringUtils.isEmpty(sysCheckCode.getCodeVal()) && StringUtils.isNotEmpty(dateChanged)) {
            return false;
        }
        // 是否符合数据库编码
        if (sysCheckCode.getCodeVal().equals(dateChanged)) {
            return true;
        }
        return false;
    }

    /**
     * 导入【入库明细箱信息】Excel
     *
     * @param file 文件
     * @return
     */
    @Override
    public AjaxResult importLibraryInformation(MultipartFile file) {
        List<TWarehousebillsitems> itemList = new ArrayList<>();
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
            String originalFilename = file.getOriginalFilename();
            Workbook workbook = null;
            if (originalFilename.endsWith("xls")) {
                workbook = WorkbookFactory.create(inputStream);
            } else if (originalFilename.endsWith("xlsx")) {
                workbook = new XSSFWorkbook(inputStream);
            } else {
                return AjaxResult.error("文件后缀异常");
            }
            Sheet sheet = workbook.getSheetAt(0);
            int line = 0;
            for (Row rows : sheet) {
                line++;
                if (rows.getRowNum() == 0) {
                    continue;
                }
                TWarehousebillsitems warehousebillsitems = new TWarehousebillsitems();
                for (int a = 0; a < rows.getPhysicalNumberOfCells(); a++) {
                    if (StringUtils.isNull(rows.getCell(a))) {
                        continue;
                    }
                    Cell cell = rows.getCell(a);
                    String value = filter(sheet.getRow(0), CellReference.convertNumToColString(cell.getColumnIndex()));
                    switch (value) {
                        case "箱号":
                            //设置单元格类型
                            cell.setCellType(CellType.STRING);
                            if (StringUtils.isNotEmpty(cell.getStringCellValue())) {
                                warehousebillsitems.setfCntrno(cell.getStringCellValue());
                            }
                            break;
                        case "铅封号":
                            //设置单元格类型
                            cell.setCellType(CellType.STRING);
                            if (StringUtils.isNotEmpty(cell.getStringCellValue())) {
                                warehousebillsitems.setfSealno(cell.getStringCellValue());
                            }
                            break;
                        case "预计件数":
                            //设置单元格类型
                            cell.setCellType(CellType.STRING);
                            if (StringUtils.isNotEmpty(cell.getStringCellValue())) {
                                warehousebillsitems.setfPlanqty(Long.valueOf(cell.getStringCellValue()));
                            }
                            break;
                        case "预计毛重":
                            //设置单元格类型
                            cell.setCellType(CellType.STRING);
                            if (StringUtils.isNotEmpty(cell.getStringCellValue())) {
                                warehousebillsitems.setfPlangrossweight(new BigDecimal(cell.getStringCellValue()).setScale(2, BigDecimal.ROUND_HALF_UP));
                            }
                            break;
                        case "预计净重":
                            //设置单元格类型
                            cell.setCellType(CellType.STRING);
                            if (StringUtils.isNotEmpty(cell.getStringCellValue())) {
                                warehousebillsitems.setfPlannetweight(new BigDecimal(cell.getStringCellValue()).setScale(2, BigDecimal.ROUND_HALF_UP));
                            }
                            break;
                    }
                }
                if (StringUtils.isNotEmpty(warehousebillsitems.getfCntrno())) {
                    itemList.add(warehousebillsitems);
                }
            }
        } catch (IOException e) {
            return AjaxResult.error("上传文件失败,请检查文件是否损坏");
        }
        String errinfo = "";
        int line = 1;
        for (TWarehousebillsitems li : itemList) {
            if (StringUtils.isEmpty(li.getfCntrno())) {
                errinfo = errinfo + "第" + line + "行箱号为空，";
            }
            if (StringUtils.isNull(li.getfPlanqty())) {
                errinfo = errinfo + "第" + line + "行预计件数为空，";
            } else {
                li.setfQty(li.getfPlanqty());
            }
            if (StringUtils.isNull(li.getfPlangrossweight())) {
                errinfo = errinfo + "第" + line + "行预计毛重为空，";
            } else {
                li.setfGrossweight(li.getfPlangrossweight());
            }
            if (StringUtils.isNull(li.getfPlannetweight())) {
                errinfo = errinfo + "第" + line + "行预计净重为空，";
            } else {
                li.setfNetweight(li.getfPlannetweight());
            }
            line++;
        }
        if (StringUtils.isEmpty(errinfo)) {
            return AjaxResult.success(itemList);
        } else {
            return AjaxResult.success(errinfo, itemList);
        }
    }

    @Override
    public AjaxResult getMblno(TWarehouseBills tWarehousebills) {
        String kh = billnoSerialServiceImpl.getMblno("KH", tWarehousebills.getfLoadportid(), tWarehousebills.getfDestportid(), tWarehousebills.getfVoyid());
        return AjaxResult.success(kh);
    }

    @Override
    @Transactional
    public AjaxResult orderExamine(TWarehouseBills tWarehouseBills, LoginUser loginUser) {
        String key = "";//键
        long actId = 0L;//活动id
        Long fPid = tWarehouseBills.getfId();
        String fidStatus = "";
        Long billStatus = 2L;
        //判断能否提交审核
        boolean b = this.judgmentMessage(tWarehouseBills.getfBilltype(), fPid);
        if (b == false) {
            return AjaxResult.error("已提交审核请勿重复提交审核");
        }
        TWarehouseBills warehouseBills = tWarehouseBillsMapper.selectTWarehousebillsById(fPid);
        if ("XGDD".equals(tWarehouseBills.getfBilltype())) {
            TVoyage tVoyage = tVoyageMapper.selectTVoyageById(warehouseBills.getfVoyid());
            if (tVoyage.getfAtd() != null) {
                Date date = new Date();
                int i = date.compareTo(tVoyage.getfAtd());
                if (i >= 0) {
                    return AjaxResult.error("当前日期已超过开船日期不能,不能变更!");
                }
            }
            actId = 471L;
            key = "khwarehouse.updateOrderMessage.ApprovalFlow";
            fidStatus = "f_updete_status";
        } else if ("XGTJ".equals(tWarehouseBills.getfBilltype())) {
            actId = 472L;
            key = "khwarehouse.submitUpdateOrderMessage.ApprovalFlow";
            fidStatus = "f_submit_update";
        } else if ("DDSC".equals(tWarehouseBills.getfBilltype())) {
            actId = 473L;
            key = "khwarehouse.deleteOrderMessage.ApprovalFlow";
            fidStatus = "f_delete_status";
        }
        boolean isApprove = false;//是否开启审批流
        SysConfig sysConfig = sysConfigMapper.checkConfigKeyUnique(key);
        if (StringUtils.isNull(sysConfig)) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("系统参数异常，未找到开启审批流参数");
        }
        if ("0".equals(sysConfig.getConfigValue())) {
            isApprove = true;
        }
        if (isApprove) {
            billStatus = 4L;
        } else {
            billStatus = 6L;
        }
        TWarehouseBills housebills = new TWarehouseBills();
        housebills.setfId(fPid);
        if ("XGDD".equals(tWarehouseBills.getfBilltype())) {
            housebills.setfUpdeteStatus(billStatus);
            if (billStatus.longValue() == 6L) {
                AjaxResult orderMessage = this.copyKhOrderMessage(fPid);
                String string = orderMessage.get("code").toString();
                if ("500".equals(string)) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return orderMessage;
                }
            }
        } else if ("XGTJ".equals(tWarehouseBills.getfBilltype())) {
            housebills.setfSubmitUpdate(billStatus);
        } else if ("DDSC".equals(tWarehouseBills.getfBilltype())) {
            housebills.setfDeleteStatus(billStatus);
            if (billStatus.longValue() == 6L) {
                housebills.setDelFlag("1");
            }
        }
        int i = tWarehouseBillsMapper.updateKaHeOrder(housebills);
        if (i <= 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("修改订单状态出错");
        }
        if (isApprove) {
            AuditItems auditItems = new AuditItems();
            auditItems.setLevelId(0L);
            auditItems.setBillId(fPid);
            auditItems.setActId(actId);
            auditItems.setIffinalItem("F");
            auditItems.setBillNo(warehouseBills.getfBillno());
            // 存储委托方（货权方）
            auditItems.setRefno1(warehouseBills.getfCorpid() + "");
            // 存储业务类型（业务类型）
            auditItems.setRefno2(tWarehouseBills.getfBilltype());
            // 存储提单号（提单号）
            if (StringUtils.isNotEmpty(warehouseBills.getfMblno())) {
                auditItems.setRefno3(warehouseBills.getfMblno());
            } else {
                auditItems.setRefno3(warehouseBills.getfBillno());
            }
            auditItems.setSendUserId(loginUser.getUser().getUserId());
            auditItems.setSendName(SecurityUtils.getUsername());
            auditItems.setSendTime(new Date());
            auditItems.setAuditUserId(loginUser.getUser().getUserId());
            auditItems.setAuditItem(new Date());
            auditItems.setAuditOpTime(new Date());
            auditItems.setAuditMsg("提交");
            auditItems.setAuditStatus("O");
            auditItems.setFidStatus(fidStatus);
            auditItems.setTimes(1L);
            AjaxResult approvalFlow = auditItemsService.createApprovalFlow(auditItems);
//            Long code = Long.valueOf(String.valueOf(approvalFlow.get("code"))).longValue();
            String code = approvalFlow.get("code").toString();
//                Long code = Long.valueOf(String.valueOf(ajaxResult.get("code"))).longValue();
            if ("500".equals(code)) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
            return approvalFlow;
        } else {
            TWarehouseBills tWarehousebillsById = tWarehouseBillsMapper.selectTWarehousebillsById(fPid);
            if (tWarehousebillsById.getfSubmitUpdate().longValue() == 6L) {
                TWarehouseBills bills = new TWarehouseBills();
                bills.setfId(tWarehousebillsById.getfId());
                bills.setfSubmitUpdate(2L);
                bills.setfUpdeteStatus(2L);
                tWarehouseBillsMapper.updateKaHeOrder(bills);
            }
        }
        return AjaxResult.success();
    }

    @Override
    @Transactional
    public AjaxResult waybillChanges(String tWarehousebills, String tWarehousebillsCntr, String tWarehousebillsCntritems, LoginUser loginUser, String billsType) {
        Date date = new Date();//修改时间
        String userName = loginUser.getUser().getUserName();//修改人
        //修改主表信息
        TWarehouseBills warehouseBills = JSONArray.parseObject(tWarehousebills, TWarehouseBills.class);
        warehouseBills.setUpdateBy(userName);
        warehouseBills.setUpdateTime(date);
        TWarehouseBills tWarehousebillsById = tWarehouseBillsMapper.selectTWarehousebillsById(warehouseBills.getfId());
        if (tWarehousebillsById.getfUpdeteStatus().longValue() != 6L) {
            return AjaxResult.error("修改审批未通过,请提交审批并且审批通过后再保存修改");
        }
        if (tWarehousebillsById.getfSubmitUpdate().longValue() == 4L
                || tWarehousebillsById.getfSubmitUpdate().longValue() == 5L
                || tWarehousebillsById.getfSubmitUpdate().longValue() == 6L) {
            return AjaxResult.error("修改已提交审批,不支持修改");
        }
        int i = tWarehouseBillsMapper.updateKaHeOrder(warehouseBills);
        if (i <= 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("更新主表信息出错!");
        }
        //删除箱信息
        tWarehousebillsCntritemsMapper.deleteTWarehousebillsCntritemsfPid(warehouseBills.getfId());
        //修改货物信息
        if (StringUtils.isNotEmpty(tWarehousebillsCntr) && !"[]".equals(tWarehousebillsCntr)) {
            tWarehousebillsCntrMapper.deleteTWarehousebillsCntrfPid(warehouseBills.getfId());
            JSONArray jsonCrArray = JSONArray.parseArray(tWarehousebillsCntr);
            List<TWarehousebillsCntr> tWarehousebillsCntrList = JSONObject.parseArray(jsonCrArray.toJSONString(), TWarehousebillsCntr.class);
            for (TWarehousebillsCntr warehousebillsCntr : tWarehousebillsCntrList) {
                if (warehousebillsCntr.getfId() == null) {
                    warehousebillsCntr.setfPid(warehouseBills.getfId());
                }
                if (warehousebillsCntr.getCreateTime() == null) {
                    warehousebillsCntr.setCreateTime(date);
                } else {
                    warehousebillsCntr.setUpdateTime(date);
                }
                if (StringUtils.isNull(warehousebillsCntr.getCreateBy())) {
                    warehousebillsCntr.setCreateBy(userName);
                } else {
                    warehousebillsCntr.setUpdateBy(userName);
                }
                tWarehousebillsCntrMapper.insertTWarehousebillsCntr(warehousebillsCntr);
            }
        }
        TWarehousebillsCntr warehousebillsCntr = tWarehousebillsCntrMapper.selectTWarehousebillsCntrByPId(warehouseBills.getfId());
        //修改箱信息
        if (StringUtils.isNotEmpty(tWarehousebillsCntritems) && !"[]".equals(tWarehousebillsCntritems)) {
            JSONArray objects = JSONArray.parseArray(tWarehousebillsCntritems);
            List<TWarehousebillsCntritems> tWarehousebillsCntritemsList = JSONObject.parseArray(objects.toJSONString(), TWarehousebillsCntritems.class);
            for (TWarehousebillsCntritems warehousebillsCntritems : tWarehousebillsCntritemsList) {
                if (warehousebillsCntritems.getfId() == null) {
                    warehousebillsCntritems.setfPid(warehouseBills.getfId());
                }
                if (warehousebillsCntritems.getCreateTime() == null) {
                    warehousebillsCntritems.setCreateTime(date);
                } else {
                    warehousebillsCntritems.setUpdateTime(date);
                }
                if (StringUtils.isNull(warehousebillsCntritems.getCreateBy())) {
                    warehousebillsCntritems.setCreateBy(userName);
                } else {
                    warehousebillsCntritems.setUpdateBy(userName);
                }
                //判断箱是否存在，判断箱型是否一致
                AjaxResult ajaxResult = this.judgeBoxPile(warehousebillsCntritems, warehousebillsCntr.getfCntrid());
                String code = ajaxResult.get("code").toString();
                if ("500".equals(code)) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.success("error", ajaxResult.get("msg").toString());
                }
                tWarehousebillsCntritemsMapper.insertTWarehousebillsCntritems(warehousebillsCntritems);
            }
        }
        return AjaxResult.success();
    }

    @Override
    @Transactional
    public AjaxResult copyKhOrderMessage(Long fId) {
        int i = tWarehousebillsLoggerMapper.copyTwarehousebills(fId);
        tWarehousebillsCntrLoggerMapper.copyTwarehousebillsCntr(fId);
        tWarehousebillsCntritemsLoggerMapper.copyTwarehousebillsCntritems(fId);
        tWarehousebillsfeesLoggerMapper.copyTWarehousebillsfees(fId);
        if (i > 0) {
            return AjaxResult.success();
        } else {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("运单变更记录日志出错");
        }
    }

    @Override
    public AjaxResult exportInventory(TWarehouseBills tWarehouseBills) {
        //获取船名
        TVessel tVessel = tVesselMapper.selectTVesselById(tWarehouseBills.getfVslid());
        //获取航次
        TVoyage tVoyage = tVoyageMapper.selectTVoyageById(tWarehouseBills.getfVoyid());
        //1.创建一个workbook,对应一个excel文件
        HSSFWorkbook wb = new HSSFWorkbook();

        //2.在workbook中添加一个sheet,对应Excel中的sheet
        HSSFSheet sheet = wb.createSheet("清单");

        //设置每一列的列宽
        sheet.setColumnWidth(0, 256 * 15);
        sheet.setColumnWidth(1, 256 * 20);
        sheet.setColumnWidth(2, 256 * 20);
        sheet.setColumnWidth(3, 256 * 20);
        sheet.setColumnWidth(4, 256 * 15);
        sheet.setColumnWidth(5, 256 * 15);
        sheet.setColumnWidth(6, 256 * 15);
        sheet.setColumnWidth(7, 256 * 35);
        sheet.setColumnWidth(8, 256 * 15);
        sheet.setColumnWidth(9, 256 * 15);
        sheet.setColumnWidth(10, 256 * 15);
        sheet.setColumnWidth(11, 256 * 20);
        sheet.setColumnWidth(12, 256 * 35);
        sheet.setColumnWidth(13, 256 * 35);
        sheet.setColumnWidth(14, 256 * 25);
        sheet.setColumnWidth(15, 256 * 25);

        //3.设置样式以及字体样式
        HSSFCellStyle titleStyle = ExcelUtils.createTitleCellStyle(wb);
        HSSFCellStyle headerStyle = ExcelUtils.createHeadCellStyle(wb);
        HSSFCellStyle contentStyle = ExcelUtils.createContentCellStyle(wb);

        //4.创建标题，合并标题单元格
        //行号
        int rowNum = 0;

        //创建第一行，索引从0开始(标题行)
        HSSFRow row0 = sheet.createRow(rowNum++);
        row0.setHeight((short) 800);// 设置行高
        String title = "青岛凯和志诚物流装船清单";
        HSSFCell c00 = row0.createCell(0);
        c00.setCellValue(title);
        c00.setCellStyle(contentStyle);
        // 合并单元格，参数依次为起始行，结束行，起始列，结束列 （索引0开始）
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 15));//标题合并单元格操作，总列数为16
        //第三行
        HSSFRow row1 = sheet.createRow(rowNum++);
        row1.setHeight((short) 500);
        String string = "船名:" + tVessel.getfName() + "          " + "航次:" + tVoyage.getfNo() + "         " + "离港日期";
        String[] row_first = {string};
        for (int i = 0; i < row_first.length; i++) {
            HSSFCell tempCell = row1.createCell(i);
            tempCell.setCellValue(row_first[i]);
            tempCell.setCellStyle(contentStyle);
        }
        //合并单元格
        sheet.addMergedRegion(new CellRangeAddress(1, 1, 0, 15));
        //第四行
        HSSFRow row3 = sheet.createRow(rowNum++);
        row3.setHeight((short) 500);
        String[] row_third = {"序号", "提单号", "箱号", "铅封号", "尺寸", "类型", "重量", "箱公司", "始发港", "目的港", "货名", "运输条款", "订舱公司", "收货公司名称", "收货人地址", "收货电话"};
        for (int i = 0; i < row_third.length; i++) {
            HSSFCell tempCell = row3.createCell(i);
            tempCell.setCellValue(row_third[i]);
            tempCell.setCellStyle(contentStyle);
        }

        //根据船名航次查询清单
        List<DeriveInventoryExcel> list = tWarehouseBillsMapper.deriveInventory(tWarehouseBills);

        for (int i = 0; i < list.size(); i++) {
            HSSFRow tempRow = sheet.createRow(rowNum++);
            tempRow.setHeight((short) 500);
            //循环单元格填入数据
            for (int j = 0; j < 16; j++) {
                HSSFCell tempCell = tempRow.createCell(j);
                tempCell.setCellStyle(contentStyle);
                String cellValue = "";
                if (j == 0) {
                    //序号
                    cellValue = list.get(i).getRankNo().toString();
                } else if (j == 1) {
                    //提单号
                    cellValue = list.get(i).getfMblno();
                } else if (j == 2) {
                    //箱号
                    cellValue = list.get(i).getfCntrno();
                } else if (j == 3) {
                    //铅封号
                    cellValue = list.get(i).getfSealno();
                } else if (j == 4) {
                    //尺寸
                    cellValue = list.get(i).getMeasure();
                } else if (j == 5) {
                    //类型
                    cellValue = list.get(i).getGenre();
                } else if (j == 6) {
                    //重量
                    cellValue = list.get(i).getfCntrweight().toString();
                } else if (j == 7) {
                    //箱公司
                    cellValue = list.get(i).getBoxCompany();
                } else if (j == 8) {
                    //始发港
                    cellValue = list.get(i).getPortOfDeparture();
                } else if (j == 9) {
                    //目的港
                    cellValue = list.get(i).getDestinationPort();
                } else if (j == 10) {
                    //货名
                    cellValue = list.get(i).getGoodName();
                } else if (j == 11) {
                    //运输条款
                    cellValue = list.get(i).getTransitClause();
                } else if (j == 12) {
                    //订舱公司
                    cellValue = list.get(i).getBookingCompany();
                } else if (j == 13) {
                    //收货公司名称
                    cellValue = list.get(i).getfConsigneername();
                } else if (j == 14) {
                    //收货公司地址
                    cellValue = list.get(i).getfConsigneeattn();
                } else if (j == 15) {
                    //收货公司电话
                    cellValue = list.get(i).getfConsigneetel();
                }
                tempCell.setCellValue(cellValue);
            }
        }
        //导出excel

        String fileName = "清单.xls";
        try {
            OutputStream out = null;
            out = new FileOutputStream(getAbsoluteFile(fileName));
            wb.write(out);
            if (null != wb && null != out) {
                wb.write(out);
                wb.close();
                out.close();
            }
            return AjaxResult.success(fileName);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error("导出Excel失败");
        }
    }

    @Override
    public AjaxResult deleteOrder(TWarehouseBills tWarehouseBills, LoginUser loginUser) {
        TWarehouseBills warehouseBills = tWarehouseBillsMapper.selectTWarehousebillsById(tWarehouseBills.getfId());
        if (warehouseBills == null) {
            return AjaxResult.error("未找到订单信息,请确认");
        }
        //修改订单状态
        TWarehouseBills bills = new TWarehouseBills();
        bills.setfId(tWarehouseBills.getfId());
        bills.setDelFlag("1");
        bills.setUpdateBy(loginUser.getUser().getUserName());
        bills.setUpdateTime(new Date());
        int i = tWarehouseBillsMapper.updateKaHeOrder(bills);
        if (i <= 0) {
            return AjaxResult.error("删除订单失败");
        }
        //删除审批流
        int billId = auditItemsMapper.deleteAuditItemsByBillId(tWarehouseBills.getfId());
        return AjaxResult.success();
    }

    @Override
    @Transactional
    public AjaxResult batchModifyingVesselVoyage(Long[] fIds, Long fVessel, Long fVoyage, Long fCargoPlanning) {
        //先查要改的多个订单的船名航次是否一直
        Long fLoadportid = null;
        Long fDestportid = null;
        Integer fLaneid = null;
        if (fVessel != null && fVoyage != null) {
            List<TWarehouseBills> tWarehouseBills = tWarehouseBillsMapper.selectTWarehousebillsByIds(fIds);
            //循环判断是否存在已经离港出运或者到港卸货的船名航次
            if (CollectionUtils.isNotEmpty(tWarehouseBills) && fCargoPlanning.longValue() == 0) {
                List<String> list = new ArrayList<>();
                List<String> boxMessage = new ArrayList<>();
                for (TWarehouseBills tWarehouseBill : tWarehouseBills) {
                    if (tWarehouseBill.getfCargoPlanning().longValue() == 0) {
                        list.add(tWarehouseBill.getfBillno());
                    }
                    //查询货物信息中的箱量
                    TWarehousebillsCntr warehousebillsCntr = tWarehousebillsCntrMapper.selectTWarehousebillsCntrByPId(tWarehouseBill.getfId());
                    //查询箱信息数量
                    List<TWarehousebillsCntritems> tWarehousebillsCntritems = tWarehousebillsCntritemsMapper.selectTWarehousebillsCntritemsByPId(tWarehouseBill.getfId());
                    if (CollectionUtils.isEmpty(tWarehousebillsCntritems) || tWarehousebillsCntritems.size() != warehousebillsCntr.getfCntrcount()) {
                        boxMessage.add(tWarehouseBill.getfBillno());
                    }

                }
                if (CollectionUtils.isNotEmpty(list) || CollectionUtils.isNotEmpty(boxMessage)) {
                    String message = "";
                    if (CollectionUtils.isNotEmpty(boxMessage) && CollectionUtils.isNotEmpty(list)) {
                        StringBuffer stringBuffer = new StringBuffer("订单缺少箱信息或者箱量不足,订单号为:");
                        stringBuffer.append(org.apache.commons.lang.StringUtils.join(boxMessage.toArray(), ","));
                        StringBuffer buffer = new StringBuffer("订单已配船请勿重复配船,订单号为:");
                        buffer.append(org.apache.commons.lang.StringUtils.join(list.toArray(), ","));
                        message = message + stringBuffer.toString() + "," + buffer.toString();
                    } else if (CollectionUtils.isNotEmpty(boxMessage) && CollectionUtils.isEmpty(list)) {
                        StringBuffer stringBuffer = new StringBuffer("订单缺少箱信息或者箱量不足,订单号为:");
                        stringBuffer.append(org.apache.commons.lang.StringUtils.join(boxMessage.toArray(), ","));
                        message = message + stringBuffer.toString();
                    } else if (CollectionUtils.isEmpty(boxMessage) && CollectionUtils.isNotEmpty(list)) {
                        StringBuffer buffer = new StringBuffer("订单已配船请勿重复配船,订单号为:");
                        buffer.append(org.apache.commons.lang.StringUtils.join(list.toArray(), ","));
                        message = message + buffer.toString();
                    }
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error(message);
                }
            }
            ArrayList<TWarehouseBills> collect = tWarehouseBills.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(TWarehouseBills -> TWarehouseBills.getfVslid() + ";" + TWarehouseBills.getfVoyid()))), ArrayList::new));
            if (collect.size() > 1) {
                return AjaxResult.error("请选择相同的船名航次");
            }
        } else {
            List<TWarehouseBills> tWarehouseBills = tWarehouseBillsMapper.selectTWarehousebillsByIds(fIds);
            if (CollectionUtils.isNotEmpty(tWarehouseBills) && fCargoPlanning.longValue() == 1) {
                List<String> list = new ArrayList<>();
                for (TWarehouseBills tWarehouseBill : tWarehouseBills) {
                    if (tWarehouseBill.getfArrivalStatus().longValue() != 0) {
                        list.add(tWarehouseBill.getfBillno());
                    }
                }
                if (CollectionUtils.isNotEmpty(list)) {
                    StringBuffer stringBuffer = new StringBuffer("订单已离港出运或到港卸货,订单号为:");
                    stringBuffer.append(org.apache.commons.lang.StringUtils.join(list.toArray(), ","));
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error(stringBuffer.toString());
                }
            }
        }
        //一致批量更改船名航次
        /*if (fVoyage != null) {
            TVoyage voyage = tVoyageMapper.selectTVoyageById(fVoyage);
            fLoadportid = voyage.getfPortofloadid();
            fDestportid = voyage.getfDistinationid();
            fLaneid = voyage.getfLaneid();

        }*/
        int i = tWarehouseBillsMapper.updateTWarehousebillsByIds(fIds, fVessel, fVoyage, fCargoPlanning,
                fLoadportid, fDestportid, fLaneid);
        if (i >= 1) {
            return AjaxResult.success();
        } else {
            return AjaxResult.error("批量更新失败");
        }
    }

    @Override
    public int updateKaHeOrder(TWarehouseBills tWarehousebills) {
        return tWarehouseBillsMapper.updateKaHeOrder(tWarehousebills);
    }

    @Override
    public List<SingleVoyageByShipExcel> singleVoyageByShip(TWarehouseBills tWarehouseBills) {
        return tWarehouseBillsMapper.singleVoyageByShip(tWarehouseBills);
    }

    private String getAbsoluteFile(String fileName) {
        String downloadPath = RuoYiConfig.getDownloadPath() + fileName;
        File desc = new File(downloadPath);
        if (!desc.getParentFile().exists()) {
            desc.getParentFile().mkdirs();
        }
        return downloadPath;
    }

    /**
     * 判断能否提交审批
     *
     * @param billType
     * @param fid
     * @return
     */
    public boolean judgmentMessage(String billType, Long fid) {
        TWarehouseBills warehouseBills = tWarehouseBillsMapper.selectTWarehousebillsById(fid);
        if ("XGDD".equals(billType) && warehouseBills.getfUpdeteStatus() == 2L) {
            return true;
        } else if ("XGDD".equals(billType) && warehouseBills.getfUpdeteStatus() == 3L) {
            return true;
        } else if ("XGTJ".equals(billType) && warehouseBills.getfSubmitUpdate() == 2L) {
            return true;
        } else if ("XGTJ".equals(billType) && warehouseBills.getfSubmitUpdate() == 3L) {
            return true;
        } else if ("DDSC".equals(billType) && warehouseBills.getfDeleteStatus() == 2L) {
            return true;
        } else if ("DDSC".equals(billType) && warehouseBills.getfDeleteStatus() == 3L) {
            return true;
        }
        return false;
    }

    /**
     * 撤销入账
     *
     * @param warehouseBills      主表
     * @param warehousebillsitems 明细
     * @param loginUser           当前登录人
     * @param billsType           状态
     * @return 结果
     */
    @Override
    @Transactional
    public AjaxResult revokeTWarehousebillsById1(String warehouseBills, String warehousebillsitems, String tEnclosure,
                                                 String warehousebillsfeesCr, String warehousebillsfeesDr, LoginUser loginUser, String tCntr, String billsType) {
        if (StringUtils.isNull(warehouseBills) || "[]".equals(warehouseBills)) {
            return AjaxResult.error("未找到主表信息");
        }
        if (StringUtils.isNull(warehousebillsitems) || "[]".equals(warehousebillsitems)) {
            return AjaxResult.error("未找到入账信息");
        }
        TWarehouseBills tWarehousebills = JSONArray.parseObject(warehouseBills, TWarehouseBills.class);
        tWarehousebills.setfItemsStatus(1L); //撤销状态
        tWarehousebills.setUpdateTime(new Date());
        tWarehousebills.setUpdateBy(loginUser.getUsername());
        Long timestamp = DateUtils.getTimestamp(new Date());
        tWarehousebills.setfDateChanged(timestamp.toString() + (int) (Math.random() * 900) + 100);
        tEnclosureMapper.deleteByFPid(tWarehousebills.getfId());
        tWarehousebillsfeesMapper.deleteByFPid(tWarehousebills.getfId());
        tWarehousebillsCntrMapper.deleteTWarehousebillsCntrfPid(tWarehousebills.getfId());
        JSONArray warehouseJSON = JSONArray.parseArray(warehousebillsitems);
        List<TWarehousebillsitems> warehousebillsitemsList = JSONObject.parseArray(warehouseJSON.toJSONString(), TWarehousebillsitems.class);
        /**
         * 流水号回收
         *  1、 获取所有流水号
         */
        List<String> serialNumberList = new ArrayList<>();
        if (StringUtils.isNotEmpty(warehousebillsitemsList)) {
            int i = 1;
            for (TWarehousebillsitems wb : warehousebillsitemsList) {
                TGoods goods = tGoodsMapper.selectTGoodsById(wb.getfGoodsid());
                if ("1".equals(goods.getIfCntrno()) && StringUtils.isNull(wb.getfCntrno())) {
                    return AjaxResult.error("仓库明细第" + i + "行未找到箱号");
                }
                if (StringUtils.isNotNull(wb.getfSerialNumber())) {
                    serialNumberList.add(wb.getfSerialNumber()); // 流水号回收
                }
                if (WarehouseTypeEnum.SJRK_REVOKE.getType().equals(billsType)) { // 撤销 入库
                    // 查询库存总账
                    TWhgenleg tWhgenle = queryWhgenlegService.stockWhgenleg(tWarehousebills, wb, goods.getIfCntrno(), WarehouseTypeEnum.UNDO_OPERATION.getType());
                    if (wb.getfIsInventory().equals(0L)) {
                        if (StringUtils.isNotNull(tWhgenle) && (wb.getfQty() <= tWhgenle.getfQtyblc())) { // 非空 且 撤销数 <= 结余数
                            updateTWhgenlegData(wb, tWhgenle.getfId(), billsType);
                        } else { // 撤销数>结余数
                            throw new WarehouseException("第" + i + "行撤销数大于库存结余数");
                        }
                    }
                    wb.setfBillstatus(10L);
                } else if (WarehouseTypeEnum.SJCK_REVOKE.getType().equals(billsType)) { // 撤销出库
                    TWarehousebillsitems item = tWarehousebillsitemsMapper.selectTWarehousebillsitemsById(wb.getfId());
                    if (Objects.nonNull(item.getfStorageFeeDeadline())) {
                        throw new WarehouseException("明细信息已计算仓储费不允许撤销");
                    }
                    // 查询库存总账
                    TWhgenleg tWhgenle = queryWhgenlegService.stockWhgenleg(tWarehousebills, wb, goods.getIfCntrno(), WarehouseTypeEnum.UNDO_OPERATION.getType());
                    if (StringUtils.isNotNull(tWhgenle)) { // 非空
                        updateTWhgenlegData(wb, tWhgenle.getfId(), billsType);
                    } else {
                        throw new WarehouseException("第" + i + "行未查询到库存信息");
                    }
                    wb.setfBillstatus(10L);
                } else if (WarehouseTypeEnum.CKDB_REVOKE.getType().equals(billsType)) { // 调拨 撤销
                    if (wb.getCreateTime().before(new Date(1637196750745L))) {
                        throw new WarehouseException("该单据已被锁定，请联系管理员");
                    }
                    if (!Objects.equals(wb.getfWarehouselocid(), wb.getfTransferWarehouselocid())) {
                        //  1、新货权方撤销入库
                        TWhgenleg tWhgenle = queryWhgenlegService.secondStockWhgenleg(tWarehousebills, wb, goods.getIfCntrno(), WarehouseTypeEnum.CONFIRM_OPERATION.getType());
                        if (StringUtils.isNotNull(tWhgenle) && (wb.getfQty() <= tWhgenle.getfQtyblc())) {
                            updateTWhgenlegData(wb, tWhgenle.getfId(), WarehouseTypeEnum.SJRK_REVOKE.getType());
                        } else {
                            throw new WarehouseException("第" + i + "行撤销数大于库存结余数");
                        }
                        //  2、原货权方撤销出库
                        TWhgenleg whgenleg = queryWhgenlegService.stockWhgenleg(tWarehousebills, wb, goods.getIfCntrno(), WarehouseTypeEnum.UNDO_OPERATION.getType());
                        updateTWhgenlegData(wb, whgenleg.getfId(), WarehouseTypeEnum.SJCK_REVOKE.getType());
                    }
                    wb.setfBillstatus(10L);
                } else if (WarehouseTypeEnum.HWTG_REVOKE.getType().equals(billsType)) { // 调拨 撤销
                    if (wb.getCreateTime().before(new Date(1637196750745L))) {
                        throw new WarehouseException("该单据已被锁定，请联系管理员");
                    }
                    //  1、新货权方撤销入库
                    // 查询库存总账
                    TWhgenleg tWhgenle = queryWhgenlegService.secondStockWhgenleg(tWarehousebills, wb, goods.getIfCntrno(), WarehouseTypeEnum.CONFIRM_OPERATION.getType());
                    if (StringUtils.isNotNull(tWhgenle) && (wb.getfQty() <= tWhgenle.getfQtyblc())) {
                        updateTWhgenlegData(wb, tWhgenle.getfId(), WarehouseTypeEnum.SJRK_REVOKE.getType());
                    } else {
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return AjaxResult.error("第" + i + "行撤销数大于库存结余数");
                    }
                    //  2、原货权方撤销出库
                    // 查询库存总账
                    TWhgenleg whgenleg = queryWhgenlegService.stockWhgenleg(tWarehousebills, wb, goods.getIfCntrno(), WarehouseTypeEnum.UNDO_OPERATION.getType());
                    updateTWhgenlegData(wb, whgenleg.getfId(), WarehouseTypeEnum.SJCK_REVOKE.getType());
                    wb.setfBillstatus(10L);
                } else if (WarehouseTypeEnum.HQZY_REVOKE.getType().equals(billsType)) { // 货转撤销
                    if (wb.getCreateTime().before(new Date(1637196750745L))) {
                        throw new WarehouseException("该单据已被锁定，请联系管理员");
                    }
                    Long fCorpid = tWarehousebills.getfCorpid();// 原货权方
                    Long fTocorpid = tWarehousebills.getfTocorpid(); // 新货权方
                    //  1、新货权方撤销入库
                    // 查询库存总账
                    tWarehousebills.setfCorpid(fTocorpid);
                    TWhgenleg tWhgenle1 = queryWhgenlegService.secondStockWhgenleg(tWarehousebills, wb, goods.getIfCntrno(), WarehouseTypeEnum.CONFIRM_OPERATION.getType());
                    if (StringUtils.isNotNull(tWhgenle1) && (wb.getfQty() <= tWhgenle1.getfQtyblc())) {
                        updateTWhgenlegData(wb, tWhgenle1.getfId(), WarehouseTypeEnum.SJRK_REVOKE.getType());
                    } else {
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return AjaxResult.error("第" + i + "行撤销数大于库存结余数");
                    }
                    //  2、原货权方撤销出库
                    // 查询库存总账
                    tWarehousebills.setfCorpid(fCorpid);
                    TWhgenleg tWhgenle2 = queryWhgenlegService.stockWhgenleg(tWarehousebills, wb, goods.getIfCntrno(), WarehouseTypeEnum.UNDO_OPERATION.getType());
                    updateTWhgenlegData(wb, tWhgenle2.getfId(), WarehouseTypeEnum.SJCK_REVOKE.getType());
                    wb.setfBillstatus(1L);
                }
                i++;
                wb.setUpdateBy(loginUser.getUser().getUserName());
                wb.setUpdateTime(new Date());
                wb.setfSerialNumber(null);
                if (tWarehousebillsitemsMapper.updateTWarehousebillsitems(wb) <= 0) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error("新增库存明细失败");
                }
            }
        }
        if (!WarehouseTypeEnum.HQZY_REVOKE.getType().equals(billsType)) {
            /**
             * 流水号回收
             *  2、 流水号去重
             *  3、 添加到 billno_del
             */
            List<String> serialNumberNewList = delRepeat(serialNumberList);
            serialNumberNewList.forEach(item -> {
                BillnoDel billnoDel = new BillnoDel();
                billnoDel.setBillType(item.substring(0, 2));
                billnoDel.setBillNo(item);
                billnoDelMapper.insertBillnoDel(billnoDel);
            });
        }
        //  箱型数据
        if (StringUtils.isNotNull(tCntr) && !"[]".equals(tCntr)) {
            JSONArray jsonDrArray = JSONArray.parseArray(tCntr);
            List<TWarehousebillsCntr> tWarehousebillsCntrs = JSONObject.parseArray(jsonDrArray.toJSONString(), TWarehousebillsCntr.class);
            int line = 0;
            for (TWarehousebillsCntr cntr : tWarehousebillsCntrs) {
                line++;
                if (StringUtils.isNull(cntr.getfCntrid()) || StringUtils.isNull(cntr.getfCntrcount()) || cntr.getfCntrcount() == 0) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error("箱型数据第" + line + "行数据缺少必填数据");
                }
                cntr.setfPid(tWarehousebills.getfId());
                cntr.setfGoodsid(0L);
                cntr.setfPackageid("0");
                cntr.setfCntrweight(new BigDecimal(0));
                cntr.setCreateBy(loginUser.getUser().getUserName());
                cntr.setCreateTime(new Date());
                tWarehousebillsCntrMapper.insertTWarehousebillsCntr(cntr);
            }
        }
        //  附件添加
        if (StringUtils.isNotEmpty(tEnclosure) && !"[]".equals(tEnclosure)) {
            JSONArray jsonDrArray = JSONArray.parseArray(tEnclosure);
            List<TEnclosure> tEnclosureList = JSONObject.parseArray(jsonDrArray.toJSONString(), TEnclosure.class);
            for (TEnclosure enclosure : tEnclosureList) {
                enclosure.setfPid(tWarehousebills.getfId());
                enclosure.setCreateBy(loginUser.getUser().getUserName());
                enclosure.setCreateTime(new Date());
                tEnclosureMapper.insertTEnclosure(enclosure);
            }
        }
        // 收款明细添加
        if (StringUtils.isNotEmpty(warehousebillsfeesDr) && !"[]".equals(warehousebillsfeesDr)) {
            JSONArray jsonDrArray = JSONArray.parseArray(warehousebillsfeesDr);
            List<TWarehousebillsfees> warehousebillsfeesDrList = JSONObject.parseArray(jsonDrArray.toJSONString(), TWarehousebillsfees.class);
            for (TWarehousebillsfees wbDr : warehousebillsfeesDrList) {
                wbDr.setfPid(tWarehousebills.getfId());
                wbDr.setfDc("D");
                wbDr.setCreateBy(loginUser.getUser().getUserName());
                wbDr.setCreateTime(new Date());
                if (tWarehousebills.getfBsdate() != null && !tWarehousebills.getfBsdate().equals("")) {
                    wbDr.setfBsdate(tWarehousebills.getfBsdate());
                }
                tWarehousebillsfeesMapper.insertTWarehousebillsfees(wbDr);
            }
        }
        // 付款明细添加
        if (StringUtils.isNotNull(warehousebillsfeesCr) && !"[]".equals(warehousebillsfeesCr)) {
            JSONArray jsonCrArray = JSONArray.parseArray(warehousebillsfeesCr);
            List<TWarehousebillsfees> warehousebillsfeesCrList = JSONObject.parseArray(jsonCrArray.toJSONString(), TWarehousebillsfees.class);
            for (TWarehousebillsfees wbCr : warehousebillsfeesCrList) {
                wbCr.setfPid(tWarehousebills.getfId());
                wbCr.setfDc("C");
                wbCr.setCreateBy(loginUser.getUser().getUserName());
                wbCr.setCreateTime(new Date());
                if (tWarehousebills.getfBsdate() != null && !tWarehousebills.getfBsdate().equals("")) {
                    wbCr.setfBsdate(tWarehousebills.getfBsdate());
                }
                tWarehousebillsfeesMapper.insertTWarehousebillsfees(wbCr);
            }
        }
        //从表更新完再查询主表信息修改入库件数
        TWarehousebillsitems itemInFo = tWarehousebillsitemsMapper.selectItemQtyByFPid(tWarehousebills.getfId());
        tWarehousebills.setfQty(itemInFo.getfQty());
        tWarehousebills.setfNetweight(itemInFo.getfNetweight());
        tWarehousebills.setfGrossweight(itemInFo.getfGrossweight());
        tWarehouseBillsMapper.updateTWarehousebills(tWarehousebills);
        return AjaxResult.success(tWarehousebills.getfDateChanged());
    }


    public static List<String> delRepeat(List<String> list) {
        List<String> myList = list.stream().distinct().collect(Collectors.toList());
        return myList;
    }

    /**
     * 添加 库存明细状态
     *
     * @param wbItem
     * @param status
     */
    public void insertTWarehousebillsLog(TWarehousebillsitems wbItem, Long status) {
        // 添加状态log
        TWarehousebillsLog tWarehousebillsLog = new TWarehousebillsLog();
        tWarehousebillsLog.setfPid(wbItem.getfPid());
        tWarehousebillsLog.setfItmeid(wbItem.getfId());
        tWarehousebillsLog.setfItmestatus(status);
        tWarehousebillsLog.setCreateTime(new Date());
        tWarehousebillsLog.setCreateBy(SecurityUtils.getUsername());
        tWarehousebillsLogMapper.insertTWarehousebillsLog(tWarehousebillsLog);
    }

    /**
     * 删除 库存明细
     *
     * @param fid
     * @param tWarehousebillsitems
     */
    public void deleteBillsitems(Long fid, String tWarehousebillsitems) {
        List<Long> oldList = new ArrayList<Long>();
        List<Long> newList = new ArrayList<Long>();

        // 查询所有从表数据
        TWarehousebillsitems tWarehousebillsitem = new TWarehousebillsitems();
        tWarehousebillsitem.setfPid(fid);
        List<TWarehousebillsitems> warehousebillsitemsList = tWarehousebillsitemsMapper.selectTWarehousebillsitemsList(tWarehousebillsitem);
        warehousebillsitemsList.forEach(wb ->
                oldList.add(wb.getfId())
        );

        // 获取提交从表数据ID
        if (tWarehousebillsitems != null) {
            JSONArray warehouseJSON = JSONArray.parseArray(tWarehousebillsitems);
            List<TWarehousebillsitems> warehousebillsitemsLists = JSONObject.parseArray(warehouseJSON.toJSONString(), TWarehousebillsitems.class);
            warehousebillsitemsLists.forEach(wb ->
                    newList.add(wb.getfId())
            );
        }
        // 删除多余的ID
        List<Long> reduce1 = oldList.stream().filter(item -> !newList.contains(item)).collect(toList());
        reduce1.forEach(id ->
                tWarehousebillsitemsMapper.deleteTWarehousebillsitemsById(id)
        );
    }

    /**
     * 库容-结余毛重
     *
     * @param fTotalgross
     * @param fGrossweightblc
     * @return
     */
    public static BigDecimal calculation1(String fTotalgross, String fGrossweightblc) {
        BigDecimal num1 = new BigDecimal(fTotalgross);
        BigDecimal num2 = new BigDecimal(fGrossweightblc);
        BigDecimal result = num1.subtract(num2);
        return result.setScale(2, RoundingMode.HALF_UP);
    }

    /**
     * 判断  是否允许 入库
     *
     * @param fId
     */
    public int calculation(Long fId, BigDecimal fGrossweight) {
        // 仓库库容
        TWarehouse tWarehouse = tWarehouseMapper.selectTWarehouseById(fId);
        // 毛重公斤转化为吨
        fGrossweight = fGrossweight.divide(new BigDecimal(1000), 0, RoundingMode.HALF_UP);
        // 总账使用
        List<Map<String, Object>> whouseList = tWhgenlegMapper.selectWareHouseListWhouse(fId);
        if (CollectionUtils.isNotEmpty(whouseList)) {
            String fTotalgross = null;
            String fGrossweightblc = null;
            for (Map<String, Object> m : whouseList) {
                for (String k : m.keySet()) {
                    // 获取毛重库容
                    if (k.equals("fTotalgross")) {
                        fTotalgross = m.get(k).toString();
                    }
                    if (k.equals("fGrossweightD")) {
                        fGrossweightblc = m.get(k).toString();
                    }
                }
            }
            BigDecimal bd = new BigDecimal(fGrossweightblc);
            fGrossweightblc = bd.divide(new BigDecimal(1000), 0, BigDecimal.ROUND_HALF_UP).toString();
            BigDecimal result = calculation1(fTotalgross, fGrossweightblc);
            if (result.compareTo(fGrossweight) == -1) {
                return 0;// 结余库容小于入库数
            } else {
                return 1;
            }
        } else {
            if (tWarehouse.getfTotalgross() != null) {
                if (tWarehouse.getfTotalgross().compareTo(fGrossweight) == -1) {
                    return 0;// 库容小于入库数
                } else {
                    return 1;
                }
            } else {
                return 0;// 库容小于入库数
            }
        }
    }

    @Transactional
    public AjaxResult updateKaHeOrder(Long fPid, long fettle, Date auditItem) {
        if (StringUtils.isNull(fPid)) {
            return AjaxResult.error("协议更新状态未找到主表信息，请与管理员联系");
        }
        TWarehouseBills tWarehouseBills = new TWarehouseBills();
        tWarehouseBills.setfId(fPid);
        tWarehouseBills.setfBillstatus(fettle);
        if (fettle == 11L) {
            tWarehouseBills.setfReviewDate(auditItem);
        }
        int tFeeUpdateResult = tWarehouseBillsMapper.updateKaHeOrder(tWarehouseBills);
        if (tFeeUpdateResult <= 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("更新订单主表状态失败，请联系管理员");
        }
        return AjaxResult.success();
    }

    /**
     * 根据fid获取订单主表信息
     *
     * @param fid
     * @return
     */
    public TWarehouseBills selectKaHeById(Long fid) {
        return tWarehouseBillsMapper.selectTWarehousebillsById(fid);
    }

    /**
     * 查询是否开启审批流
     *
     * @param billsType
     * @return
     */
    public SysConfig queryWarehouseConfig(String billsType) {
        String key = "";
        if ("SJRK".equals(billsType)) {
            key = "instock.orders.approval";
        } else if ("SJCK".equals(billsType)) {
            key = "outStock.orders.approvalFlow";
        } else if (WarehouseTypeEnum.CKDB.getType().equals(billsType)) {
            key = "stockTransfer.orders.approvalFlow";
        } else if (WarehouseTypeEnum.HQZY.getType().equals(billsType)) {
            key = "transfer.orders.approvalFlow";
        } else if (WarehouseTypeEnum.HWTG.getType().equals(billsType)) {
            key = "cargoClearance.orders.approvalFlow";
        } else if ("SJRKITEM".equals(billsType)) {
            key = "warehouse.inStockItem.ApprovalFlow";
        } else if ("SJCKITEM".equals(billsType)) {
            key = "warehouse.outStockItem.ApprovalFlow";
        }
        return sysConfigMapper.checkConfigKeyUnique(key);
    }

    /**
     * 查询是对应仓储类型活动号
     *
     * @param billsType
     * @return
     */
    public Long queryWarehouseActId(String billsType) {
        long actId = 0L;
        if ("SJRK".equals(billsType)) {
            actId = 110L;
        } else if ("SJCK".equals(billsType)) {
            actId = 120L;
        } else if (WarehouseTypeEnum.CKDB.getType().equals(billsType)) {
            actId = 140L;
        } else if (WarehouseTypeEnum.HQZY.getType().equals(billsType)) {
            actId = 130L;
        } else if (WarehouseTypeEnum.HWTG.getType().equals(billsType)) {
            actId = 160L;
        } else if ("CDZZ".equals(billsType)) {
            actId = 190L;
        }
        return actId;
    }

    /**
     * 校验仓储主表字段是否为空
     * 后续优化进入系统
     *
     * @param warehousebill
     * @return
     */
    public String checkWarehouse(TWarehouseBills warehousebill) {
        if (StringUtils.isNull(warehousebill.getfCorpid())) {
            return "请维护主表客户信息";
        }
        if (StringUtils.isNull(warehousebill.getfBsdate())) {
            return "请维护主表业务日期";
        }
        if (StringUtils.isNull(warehousebill.getfWarehouseid())) {
            return "请维护主表仓库信息";
        }
        if (("SJRK".equals(warehousebill.getfBilltype()) || "SJCK".equals(warehousebill.getfBilltype()))
                && StringUtils.isNull(warehousebill.getfFeetunit())) {
            return "请维护主表业务计费单位";
        }
        if (("SJRK".equals(warehousebill.getfBilltype()) || WarehouseTypeEnum.HQZY.getType().equals(warehousebill.getfBilltype()))
                && StringUtils.isNull(warehousebill.getfChargedate())) {
            return "请维护主表仓储费计费日期";
        }
        if ("SJRK".equals(warehousebill.getfBilltype()) && StringUtils.isNull(warehousebill.getfGoodsid())) {
            return "请维护主表商品信息";
        }
        if (!WarehouseTypeEnum.HQZY.getType().equals(warehousebill.getfBilltype()) && StringUtils.isNull(warehousebill.getfStorekeeper())) {
            return "请维护主表仓管员信息";
        }
        if ("SJRK".equals(warehousebill.getfBilltype()) && StringUtils.isEmpty(warehousebill.getfMblno())) {
            return "请维护主表提单号";
        }
        if (WarehouseTypeEnum.CKDB.getType().equals(warehousebill.getfBilltype()) && StringUtils.isEmpty(warehousebill.getfBusinessType())) {
            return "请维护主表作业类型";
        }
        if ((WarehouseTypeEnum.HQZY.getType().equals(warehousebill.getfBilltype()) || WarehouseTypeEnum.HWTG.getType().equals(warehousebill.getfBilltype()))
                && StringUtils.isNull(warehousebill.getfTrademodeid())) {
            return "请维护主表贸易方式";
        }
        if (WarehouseTypeEnum.HWTG.getType().equals(warehousebill.getfBilltype()) && StringUtils.isNull(warehousebill.getfNewTrademodeid())) {
            return "请维护主表新贸易方式";
        }
        return null;
    }

    /**
     * 获取最小仓储费计算日期
     *
     * @param fId
     * @param date
     * @return
     */
    public boolean getFchargedate(Long fId, Date date) {
        Date fchargedate = tWarehousebillsitemsMapper.getFchargedate(fId);
        if (fchargedate == null) {
            return true;
        }
        int i = date.compareTo(fchargedate);
        if (i == -1) {
            return false;
        } else {
            return true;
        }
    }

    /**
     * 获取仓储费最小日期并更新入库明细的仓储费计算日期
     *
     * @param fId
     * @return
     */
    public AjaxResult updateFchargeDate(Long fId) throws ParseException {
        Date fchargedate = tWarehousebillsitemsMapper.getFchargedate(fId);
        int i = tWarehousebillsitemsMapper.warehouseItemfChargedate(fId, fchargedate);
        if (i > 0) {
            return AjaxResult.success();
        } else if (i == 0) {
            return AjaxResult.error("更新最小仓储费计算日期出错,请找管理员");
        } else {
            return AjaxResult.success();
        }
    }

    /**
     * 判断箱号是否存在 箱型是否一致
     *
     * @param tWarehousebillsCntritems 箱信息表
     * @param fId                      货物信息表箱类型ID
     * @return
     */
    public AjaxResult judgeBoxPile(TWarehousebillsCntritems tWarehousebillsCntritems, Long fId) {
        //判断箱子是否存在
        if (StringUtils.isEmpty(tWarehousebillsCntritems.getfCntrno())) {
            return AjaxResult.error("箱号不能为空");
        }
        TCntrno tCntrno = tCntrnoMapper.selectTCnTrNoByfNo(tWarehousebillsCntritems.getfCntrno());
        if (tCntrno == null) {
            return AjaxResult.error("箱号" + tWarehousebillsCntritems.getfCntrno() + "不存在");
        }
        //判断箱型是否一致
        //TCntr tCntr = tCntrMapper.selectTCntrById(fId);//查询货物信息对应的箱类型
        TCntrno cnTrNo = tCntrnoMapper.selectTCnTrNoByfNo(tWarehousebillsCntritems.getfCntrno());//查询箱号对应的箱信息
        TCntr tCntr = tCntrMapper.selectTCntrById(cnTrNo.getfTypeid());//查询箱类型
        if (cnTrNo != null && Objects.equals(cnTrNo.getfTypeid(), tWarehousebillsCntritems.getfCntrid())) {
            if (!Objects.equals(tWarehousebillsCntritems.getfCntrid(), fId)) {
                TCntr cntr = tCntrMapper.selectTCntrById(fId);
                return AjaxResult.error("箱号" + tWarehousebillsCntritems.getfCntrno() + "跟货物信息中箱类型不一致,箱类型应为:" + cntr.getfNo());
            }
        } else if (cnTrNo != null && !Objects.equals(cnTrNo.getfTypeid(), tWarehousebillsCntritems.getfCntrid())) {
            return AjaxResult.error("箱号" + tWarehousebillsCntritems.getfCntrno() + "跟基础信息中箱类型不一致,箱类型应为:" + tCntr.getfNo());
        }
        return AjaxResult.success();
    }

    @Override
    @Transactional
    public AjaxResult updateBoxMessage(TCntrnoMessage tCntrno, LoginUser loginUser) {
        String remark = tCntrno.getfVsl() + tCntrno.getfVoy();
        Date date = tCntrno.getfUpdatetime();
        //查询船名航次对应的信息
        TWarehouseBills tWarehouseBills = new TWarehouseBills();
        tWarehouseBills.setfVslid(tCntrno.getfVslid());
        tWarehouseBills.setfVoyid(tCntrno.getfVoyid());
        tWarehouseBills.setfCargoPlanning(0L);
        if (tCntrno.getUpdateStatus().longValue() == 1) {
            tWarehouseBills.setfArrivalStatus(0);
            List<TWarehouseBills> tWarehouseBillsList = tWarehouseBillsMapper.webVersionOrderList(tWarehouseBills);
            if (CollectionUtils.isEmpty(tWarehouseBillsList)) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error("该船名航次未配船或已离港出运或到港卸船");
            }
            //获取地点ID
            Long aLong = tAddressMapper.selectTAddressByfName("在船");
            if (aLong == null) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error("系统中缺少在船地点请维护");
            }
            //获取调箱动态ID
            String fOpCTnsTaTus = sysDictDataMapper.selectDictValue("f_opctnstatus", "装船");
            if (StringUtils.isEmpty(fOpCTnsTaTus)) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error("系统缺少箱动态装船请维护");
            }
            for (TWarehouseBills bills : tWarehouseBillsList) {
                //查询货物信息
                TWarehousebillsCntr warehousebillsCntr = tWarehousebillsCntrMapper.selectTWarehousebillsCntrByPId(bills.getfId());
                //查询订单箱信息
                TWarehousebillsCntritems tWarehousebillsCntritems = new TWarehousebillsCntritems();
                tWarehousebillsCntritems.setfPid(bills.getfId());
                List<TWarehousebillsCntritems> warehousebillsCntritems = tWarehousebillsCntritemsMapper.selectTWarehousebillsCntritemsList(tWarehousebillsCntritems);
                if (CollectionUtils.isNotEmpty(warehousebillsCntritems)) {
                    for (TWarehousebillsCntritems warehousebillsCntritem : warehousebillsCntritems) {
                        TCntrno cntrno = new TCntrno();
                        cntrno.setfNo(warehousebillsCntritem.getfCntrno());
                        cntrno.setUpdateTime(date);
                        cntrno.setUpdateBy(loginUser.getUser().getUserName());
                        cntrno.setfUpdatetime(date);
                        cntrno.setRemark(remark);
                        cntrno.setfUpdateaddress(aLong.toString());
                        cntrno.setfOpctnstatus(fOpCTnsTaTus);
                        cntrno.setfCntrstatus(warehousebillsCntr.getfCntrstatus());
                        tCntrnoMapper.updateTCntrnoByfNo(cntrno);
                        //保存历史信息
                        TCntrno cntrnoById = tCntrnoMapper.selectTCnTrNoByfNo(warehousebillsCntritem.getfCntrno());
                        if (cntrnoById == null) {
                            continue;
                        }
                        if (cntrnoById.getfStatus().equals("T") || cntrnoById.getfStatus().equals("正常")) {
                            cntrnoById.setfStatus("T");
                        } else {
                            cntrnoById.setfStatus("F");
                        }
                        TCntrtracking tCntrtracking = new TCntrtracking();
                        BeanUtils.copyProperties(cntrnoById, tCntrtracking);
                        tCntrtracking.setfId(null);
                        tCntrtracking.setfVoy(tCntrno.getfVoy());//航次
                        tCntrtracking.setfVsl(tCntrno.getfVsl());//船名
                        tCntrtrackingMapper.insertTCntrtracking(tCntrtracking);
                    }
                }
                //修改主表状态为离港出运
                TWarehouseBills warehouseBills = new TWarehouseBills();
                warehouseBills.setfId(bills.getfId());
                warehouseBills.setfArrivalStatus(1);
                tWarehouseBillsMapper.updateKaHeOrder(warehouseBills);
            }

        } else if (tCntrno.getUpdateStatus().longValue() == 2) {
            tWarehouseBills.setfArrivalStatus(1);
            List<TWarehouseBills> tWarehouseBillsList = tWarehouseBillsMapper.webVersionOrderList(tWarehouseBills);
            if (CollectionUtils.isEmpty(tWarehouseBillsList)) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error("该船名航次未离港出运");
            }
            //获取调箱动态ID
            String fOpCTnsTaTus = sysDictDataMapper.selectDictValue("f_opctnstatus", "卸船");
            if (StringUtils.isEmpty(fOpCTnsTaTus)) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error("系统缺少箱动态卸船请维护");
            }
            for (TWarehouseBills bills : tWarehouseBillsList) {
                //查询货物信息
                TWarehousebillsCntr warehousebillsCntr = tWarehousebillsCntrMapper.selectTWarehousebillsCntrByPId(bills.getfId());
                //查询订单箱信息
                TWarehousebillsCntritems tWarehousebillsCntritems = new TWarehousebillsCntritems();
                tWarehousebillsCntritems.setfPid(bills.getfId());
                List<TWarehousebillsCntritems> warehousebillsCntritems = tWarehousebillsCntritemsMapper.selectTWarehousebillsCntritemsList(tWarehousebillsCntritems);
                if (CollectionUtils.isNotEmpty(warehousebillsCntritems)) {
                    for (TWarehousebillsCntritems warehousebillsCntritem : warehousebillsCntritems) {
                        TCntrno cntrno = new TCntrno();
                        cntrno.setfNo(warehousebillsCntritem.getfCntrno());
                        cntrno.setUpdateTime(date);
                        cntrno.setUpdateBy(loginUser.getUser().getUserName());
                        cntrno.setfUpdatetime(date);
                        cntrno.setRemark(null);
                        cntrno.setfUpdateaddress(bills.getfDestportid().toString());
                        cntrno.setfOpctnstatus(fOpCTnsTaTus);
                        cntrno.setfCntrstatus(warehousebillsCntr.getfCntrstatus());
                        tCntrnoMapper.updateTCntrnoByfNo(cntrno);
                        //保存历史信息
                        TCntrno cntrnoById = tCntrnoMapper.selectTCnTrNoByfNo(warehousebillsCntritem.getfCntrno());
                        if (cntrnoById.getfStatus().equals("T") || cntrnoById.getfStatus().equals("正常")) {
                            cntrnoById.setfStatus("T");
                        } else {
                            cntrnoById.setfStatus("F");
                        }
                        TCntrtracking tCntrtracking = new TCntrtracking();
                        BeanUtils.copyProperties(cntrnoById, tCntrtracking);
                        tCntrtracking.setfId(null);
                        tCntrtracking.setfVoy(tCntrno.getfVoy());//航次
                        tCntrtracking.setfVsl(tCntrno.getfVsl());//船名
                        tCntrtrackingMapper.insertTCntrtracking(tCntrtracking);
                    }
                }
                //修改主表状态为已到港卸货
                TWarehouseBills warehouseBills = new TWarehouseBills();
                warehouseBills.setfId(bills.getfId());
                warehouseBills.setfArrivalStatus(2);
                tWarehouseBillsMapper.updateKaHeOrder(warehouseBills);
            }
        } else {
            return AjaxResult.error("请选择离岗出运或到港卸船");
        }
        return AjaxResult.success();
    }

    /**
     * 获取旧单的箱量与新单的箱量
     * 减去新单的箱量生成旧单的箱量并保存
     * 保存新单的单信息
     *
     * @param tWarehousebills          仓库出入表
     * @param tWarehousebillsCntr      订单从表
     * @param tWarehousebillsCntritems 箱明细表
     * @return
     */
    @Override
    @Transactional
    public AjaxResult updateMessageSign(String tWarehousebills, String tWarehousebillsCntr, String tWarehousebillsCntritems, String fOriginalbillno) {
        //保存新单主表信息
        //保存新单货物信息
        //保存新单想信息
        boolean isApprove = false;//是否开启审批流
        String key = "khwarehouse.dismountOrder.ApprovalFlow";//键
        long actId = 474L;//活动id
        Long billStatus = null; //状态id
        SysConfig sysConfig = sysConfigMapper.checkConfigKeyUnique(key);
        if (StringUtils.isNull(sysConfig)) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("系统参数异常，未找到开启审批流参数");
        }
        if ("0".equals(sysConfig.getConfigValue())) {
            isApprove = true;
        }
        if (isApprove) {
            billStatus = 4L;
        } else {
            billStatus = 6L;
        }
        TWarehouseBills warehouseBills = JSONArray.parseObject(tWarehousebills, TWarehouseBills.class); //新单主表信息
        JSONArray jsonCrArray = JSONArray.parseArray(tWarehousebillsCntr);
        List<TWarehousebillsCntr> tWarehousebillsCntrs = JSONObject.parseArray(jsonCrArray.toJSONString(), TWarehousebillsCntr.class);//新单货物信息
        JSONArray jsonCrArrayItems = JSONArray.parseArray(tWarehousebillsCntritems);
        List<TWarehousebillsCntritems> tWarehousebillsCntritemsList = JSONObject.parseArray(jsonCrArrayItems.toJSONString(), TWarehousebillsCntritems.class);//新单箱信息
        //获取原单信息
        TWarehouseBills bills = new TWarehouseBills();
        bills.setfBillno(fOriginalbillno);
        List<TWarehouseBills> tWarehouseBillsList = tWarehouseBillsMapper.webVersionOrderList(bills);
        if (CollectionUtils.isEmpty(tWarehouseBillsList)) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("未查到原单信息");
        }
        TWarehouseBills selectOne = tWarehouseBillsList.get(0);
        TWarehousebillsCntr Cntr = tWarehousebillsCntrMapper.selectTWarehousebillsCntrByPId(selectOne.getfId());
        if (tWarehousebillsCntritemsList.size() >= Cntr.getfCntrcount()) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("分单箱量不能超出原单数量");
        }
        if (CollectionUtils.isNotEmpty(tWarehousebillsCntrs)) {
            TWarehousebillsCntr cnTrWareHouse = tWarehousebillsCntrs.get(0);
            if (cnTrWareHouse.getfCntrcount() >= Cntr.getfCntrcount()) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error("分单箱量不能超出原单数量");
            }
        }
        //拆单数量
        Long number = 0L;
        if (warehouseBills.getfId() == null) {
            String billNoNew = this.getBillNoNew(selectOne.getfMblno());
            String billNo = billnoSerialServiceImpl.getBillNo("SE", warehouseBills.getfBsdate());
            warehouseBills.setfBillno(billNo);
            warehouseBills.setfMblno(billNoNew);
            warehouseBills.setCreateTime(DateUtils.getNowDate());
            warehouseBills.setCreateBy(SecurityUtils.getUsername());
            warehouseBills.setfBilltype("KHDD");
            warehouseBills.setfTypeid(1);
            warehouseBills.setfOriginalbillno(fOriginalbillno);
            warehouseBills.setfDismountStatus(billStatus);
            warehouseBills.setfDeptid(SecurityUtils.getLoginUser().getUser().getDeptId());
            warehouseBills.setfBsdeptid(SecurityUtils.getLoginUser().getUser().getDeptId());
            int i = tWarehouseBillsMapper.insertTWarehousebills(warehouseBills);
            //货物信息
            if (CollectionUtils.isNotEmpty(tWarehousebillsCntrs)) {
                for (TWarehousebillsCntr warehousebillsCntr : tWarehousebillsCntrs) {
                    number = warehousebillsCntr.getfCntrcount();
                    warehousebillsCntr.setfPid(warehouseBills.getfId());
                    warehousebillsCntr.setCreateTime(DateUtils.getNowDate());
                    warehousebillsCntr.setCreateBy(SecurityUtils.getUsername());
                    int cntr = tWarehousebillsCntrMapper.insertTWarehousebillsCntr(warehousebillsCntr);
                }
            }
            //箱信息
            if (CollectionUtils.isNotEmpty(tWarehousebillsCntritemsList)) {
                for (TWarehousebillsCntritems warehousebillsCntritems : tWarehousebillsCntritemsList) {
                    TWarehousebillsCntr billsCntr = tWarehousebillsCntrMapper.selectTWarehousebillsCntrByPId(warehouseBills.getfId());
                    AjaxResult ajaxResult = this.judgeBoxPile(warehousebillsCntritems, billsCntr.getfCntrid());
                    String code = ajaxResult.get("code").toString();
                    if ("500".equals(code)) {
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return AjaxResult.success("error", ajaxResult.get("msg").toString());
                    }
                    warehousebillsCntritems.setfPid(warehouseBills.getfId());
                    warehousebillsCntritems.setCreateTime(DateUtils.getNowDate());
                    warehousebillsCntritems.setCreateBy(SecurityUtils.getUsername());
                    int cntr = tWarehousebillsCntritemsMapper.insertTWarehousebillsCntritems(warehousebillsCntritems);
                }
            }
            //保存新单费用信息 修改原单费用信息
            List<TWarehousebillsfees> tWarehousebillsfeesList = tWarehousebillsfeesMapper.selectWarehousebillsfeesByPId(selectOne.getfId());
            if (CollectionUtils.isNotEmpty(tWarehousebillsfeesList)) {
                //保存新单费用
                for (TWarehousebillsfees tWarehousebillsfees : tWarehousebillsfeesList) {
                    tWarehousebillsfees.setfId(null);
                    tWarehousebillsfees.setfPid(warehouseBills.getfId());
                    tWarehousebillsfees.setCreateBy(SecurityUtils.getUsername());
                    tWarehousebillsfees.setCreateTime(new Date());
                    tWarehousebillsfees.setSrcBillNo(warehouseBills.getfBillno());
                    tWarehousebillsfees.setfQty(new BigDecimal(number));
                    tWarehousebillsfees.setfAmount(new BigDecimal(number).multiply(tWarehousebillsfees.getfUnitprice()));
                    tWarehousebillsfeesMapper.insertTWarehousebillsfees(tWarehousebillsfees);
                }
            }
        } else {
            TWarehouseBills tWarehouseBills = tWarehouseBillsMapper.selectTWarehousebillsById(warehouseBills.getfId());
            warehouseBills.setUpdateTime(DateUtils.getNowDate());
            warehouseBills.setUpdateBy(SecurityUtils.getUsername());
            warehouseBills.setfDismountStatus(billStatus);
            tWarehouseBillsMapper.updateTWarehousebills(warehouseBills);
            tWarehousebillsCntrMapper.deleteTWarehousebillsCntrfPid(warehouseBills.getfId());
            if (CollectionUtils.isNotEmpty(tWarehousebillsCntrs)) {
                for (TWarehousebillsCntr warehousebillsCntr : tWarehousebillsCntrs) {
                    number = warehousebillsCntr.getfCntrcount();
                    warehousebillsCntr.setfPid(warehouseBills.getfId());
                    warehousebillsCntr.setCreateTime(DateUtils.getNowDate());
                    warehousebillsCntr.setCreateBy(SecurityUtils.getUsername());
                    tWarehousebillsCntrMapper.insertTWarehousebillsCntr(warehousebillsCntr);
                }
            }
            tWarehousebillsCntritemsMapper.deleteTWarehousebillsCntritemsfPid(warehouseBills.getfId());
            if (CollectionUtils.isNotEmpty(tWarehousebillsCntritemsList)) {
                for (TWarehousebillsCntritems warehousebillsCntritems : tWarehousebillsCntritemsList) {
                    TWarehousebillsCntr billsCntr = tWarehousebillsCntrMapper.selectTWarehousebillsCntrByPId(warehouseBills.getfId());
                    AjaxResult ajaxResult = this.judgeBoxPile(warehousebillsCntritems, billsCntr.getfCntrid());
                    String code = ajaxResult.get("code").toString();
                    if ("500".equals(code)) {
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return AjaxResult.success("error", ajaxResult.get("msg").toString());
                    }
                    warehousebillsCntritems.setfPid(warehouseBills.getfId());
                    warehousebillsCntritems.setCreateTime(DateUtils.getNowDate());
                    warehousebillsCntritems.setCreateBy(SecurityUtils.getUsername());
                    tWarehousebillsCntritemsMapper.insertTWarehousebillsCntritems(warehousebillsCntritems);
                }
            }
            tWarehousebillsfeesMapper.deleteByFPid(warehouseBills.getfId());
            //保存新单费用信息 修改原单费用信息
            List<TWarehousebillsfees> tWarehousebillsfeesList = tWarehousebillsfeesMapper.selectWarehousebillsfeesByPId(selectOne.getfId());
            if (CollectionUtils.isNotEmpty(tWarehousebillsfeesList)) {
                //保存新单费用
                for (TWarehousebillsfees tWarehousebillsfees : tWarehousebillsfeesList) {
                    tWarehousebillsfees.setfId(null);
                    tWarehousebillsfees.setfPid(warehouseBills.getfId());
                    tWarehousebillsfees.setCreateBy(SecurityUtils.getUsername());
                    tWarehousebillsfees.setCreateTime(new Date());
                    tWarehousebillsfees.setSrcBillNo(warehouseBills.getfBillno());
                    tWarehousebillsfees.setfQty(new BigDecimal(number));
                    tWarehousebillsfees.setfAmount(new BigDecimal(number).multiply(tWarehousebillsfees.getfUnitprice()));
                    tWarehousebillsfeesMapper.insertTWarehousebillsfees(tWarehousebillsfees);
                }
            }
        }
        if (isApprove) {
            AuditItems auditItems = new AuditItems();
            auditItems.setLevelId(0L);
            auditItems.setBillId(warehouseBills.getfId());
            auditItems.setActId(actId);
            auditItems.setIffinalItem("F");
            auditItems.setBillNo(warehouseBills.getfBillno());
            // 存储委托方（货权方）
            auditItems.setRefno1(warehouseBills.getfCorpid() + "");
            // 存储业务类型（业务类型）
            auditItems.setRefno2(warehouseBills.getfBilltype());
            // 存储提单号（提单号）
            if (StringUtils.isNotEmpty(warehouseBills.getfMblno())) {
                auditItems.setRefno3(warehouseBills.getfMblno());
            } else {
                auditItems.setRefno3(warehouseBills.getfBillno());
            }
            auditItems.setSendUserId(SecurityUtils.getLoginUser().getUser().getUserId());
            auditItems.setSendName(SecurityUtils.getUsername());
            auditItems.setSendTime(new Date());
            auditItems.setAuditUserId(SecurityUtils.getLoginUser().getUser().getUserId());
            auditItems.setAuditItem(new Date());
            auditItems.setAuditOpTime(new Date());
            auditItems.setAuditMsg("提交");
            auditItems.setFidStatus("f_dismount_status");
            auditItems.setAuditStatus("O");
            AjaxResult approvalFlow = auditItemsService.createApprovalFlow(auditItems);
//            Long code = Long.valueOf(String.valueOf(approvalFlow.get("code"))).longValue();
            String code = approvalFlow.get("code").toString();
//                Long code = Long.valueOf(String.valueOf(ajaxResult.get("code"))).longValue();
            if ("500".equals(code)) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
            return approvalFlow;
        }
        return AjaxResult.success();
    }

    /**
     * 获取分单提单号
     *
     * @param fbillNo
     * @return
     */
    public String getBillNoNew(String fbillNo) {
        List<String> strings = Arrays.asList(StringUtils.split("A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z", ","));
        for (String string : strings) {
            String billno = fbillNo + string;
            TWarehouseBills tWarehouseBills = new TWarehouseBills();
            tWarehouseBills.setfMblno(billno);
            List<Map<String, Object>> maps = tWarehouseBillsMapper.ruoYiVersionOrderList(tWarehouseBills);
            if (CollectionUtils.isEmpty(maps)) {
                return billno;
            }
        }
        return null;
    }

    /**
     * 审批通过修改原单信息
     *
     * @param orderId
     * @return
     */
    @Override
    @Transactional
    public AjaxResult approveDismount(Long orderId) {
        TWarehouseBills warehouseBills = tWarehouseBillsMapper.selectTWarehousebillsById(orderId);
        //获取原单信息
        TWarehouseBills bills = new TWarehouseBills();
        bills.setfBillno(warehouseBills.getfOriginalbillno());
        List<TWarehouseBills> tWarehouseBillsList = tWarehouseBillsMapper.webVersionOrderList(bills);
        if (CollectionUtils.isEmpty(tWarehouseBillsList)) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("未查到原单信息");
        }
        TWarehouseBills selectOne = tWarehouseBillsList.get(0);
        //获取新单信息
        TWarehousebillsCntr wareHouseBillsCnTr = tWarehousebillsCntrMapper.selectTWarehousebillsCntrByPId(orderId);
        //获取旧单信息 修改货物信息中的箱量
        TWarehousebillsCntr billsCnTr = tWarehousebillsCntrMapper.selectTWarehousebillsCntrByPId(selectOne.getfId());
        if (wareHouseBillsCnTr.getfCntrcount() >= billsCnTr.getfCntrcount()) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("拆单数量不能超过或等于原单数量,现在原单数量为" + billsCnTr.getfCntrcount() + "个。");
        }
        billsCnTr.setUpdateBy(SecurityUtils.getUsername());
        billsCnTr.setUpdateTime(new Date());
        billsCnTr.setfCntrcount(billsCnTr.getfCntrcount() - wareHouseBillsCnTr.getfCntrcount());
        tWarehousebillsCntrMapper.updateTWarehousebillsCntr(billsCnTr);//修改原单货物信息中的箱量
        //修改原单的费用信息
        List<TWarehousebillsfees> WarehousebillsfeesList = tWarehousebillsfeesMapper.selectWarehousebillsfeesByPId(selectOne.getfId());
        if (CollectionUtils.isNotEmpty(WarehousebillsfeesList)) {
            //修改原单费用
            for (TWarehousebillsfees tWarehousebillsfees : WarehousebillsfeesList) {
                tWarehousebillsfees.setUpdateBy(SecurityUtils.getUsername());
                tWarehousebillsfees.setUpdateTime(new Date());
                tWarehousebillsfees.setfQty(tWarehousebillsfees.getfQty().subtract(new BigDecimal(wareHouseBillsCnTr.getfCntrcount())));
                tWarehousebillsfees.setfAmount(tWarehousebillsfees.getfQty().multiply(tWarehousebillsfees.getfUnitprice()));
                tWarehousebillsfeesMapper.updateTWarehousebillsfees(tWarehousebillsfees);
            }
        }
        //修改原单箱信息
        List<TWarehousebillsCntritems> tWarehousebillsCntritemsList = tWarehousebillsCntritemsMapper.selectTWarehousebillsCntritemsByPId(orderId);
        if (CollectionUtils.isNotEmpty(tWarehousebillsCntritemsList)) {
            for (TWarehousebillsCntritems warehousebillsCntritems : tWarehousebillsCntritemsList) {
                tWarehousebillsCntritemsMapper.deleteTWarehousebillsCntritemOlder(selectOne.getfId(), warehousebillsCntritems.getfCntrno());
            }
        }
        return AjaxResult.success();
    }

    /**
     * 根据仓库id查询最新两条审核人信息
     *
     * @param id 仓库id
     * @return
     */
    @Override
    public AjaxResult queryReviewer(Long id) {

        List<Integer> actIds = WarehouseActIdEnum.isWarehousingBusiness();
        // 根据仓库id与活动号集合查询审核成功最新两条数据
        List<String> userName = auditItemsMapper.selectListByRefno1AndActId(id, actIds);
        if (CollectionUtils.isNotEmpty(userName)) {
            return AjaxResult.success(userName);
        }
        return AjaxResult.success();
    }

    /**
     * 根据费用id 更新审核信息
     *
     * @param id 费用id
     * @return
     */
    @Override
    public AjaxResult feeReviewSubmit(Long id) {
        TWarehousebillsfees warehousebillsfees = tWarehousebillsfeesMapper.selectTWarehousebillsfeesById(id);
        if (StringUtils.isNull(warehousebillsfees.getfCorpid()) || StringUtils.isNull(warehousebillsfees.getfFeeid()) ||
                StringUtils.isNull(warehousebillsfees.getfFeeunitid())) {
            throw new WarehouseException("请确认是否维护客户、费用信息、计价单位");
        }
        if (Objects.isNull(warehousebillsfees) || Objects.nonNull(warehousebillsfees.getfReviewDate())) {
            throw new WarehouseException("未找到费用信息或费用已被审核");
        }
        tWarehousebillsfeesMapper.warehouseFeesFollowUpdateById(id, Long.parseLong(FeesTypeEnum.APPROVE.getType()), new Date());
        TWarehouseBills warehouseBills = new TWarehouseBills();
        warehouseBills.setfId(warehousebillsfees.getfPid());
        calculationWarehouseService.calculationFeeStatus(warehouseBills);
        tWarehouseBillsMapper.updateTWarehousebills(warehouseBills);
        return AjaxResult.success(tWarehousebillsfeesMapper.selectTWarehousebillsfeesById(id));
    }

    /**
     * 根据id撤销已费用审核状态
     *
     * @param id
     * @return
     */
    @Override
    public AjaxResult revokefeeReview(Long id) {
        TWarehousebillsfees warehousebillsfees = tWarehousebillsfeesMapper.selectTWarehousebillsfeesById(id);
        if (Objects.isNull(warehousebillsfees) || warehousebillsfees.getfAccamount().compareTo(BigDecimal.ZERO) > 0
                || warehousebillsfees.getfStlamount().compareTo(BigDecimal.ZERO) > 0
                || warehousebillsfees.getfInvamount().compareTo(BigDecimal.ZERO) > 0) {

            throw new WarehouseException("未找到费用信息或费用已计算费用");
        }
        tWarehousebillsfeesMapper.warehouseFeesFollowUpdateById(id, Long.parseLong(FeesTypeEnum.SAVE.getType()), new Date());
        TWarehouseBills warehouseBills = new TWarehouseBills();
        warehouseBills.setfId(warehousebillsfees.getfPid());
        calculationWarehouseService.calculationFeeStatus(warehouseBills);
        tWarehouseBillsMapper.updateTWarehousebills(warehouseBills);
        return AjaxResult.success(tWarehousebillsfeesMapper.selectTWarehousebillsfeesById(id));
    }

    /**
     * app根据id查询详情
     *
     * @param id       主表id
     * @param typeEnum 类型
     * @return
     */
    @Override
    public AjaxResult appQueryInit(Long id, String typeEnum) {
        if (Objects.isNull(id)) {
            return AjaxResult.error("无效id");
        }
        TWarehouseBills warehouseBills = tWarehouseBillsMapper.selectTWarehousebillsById(id);
        if (Objects.isNull(warehouseBills)) {
            return AjaxResult.error("仓库信息无效");
        }
        AppWarehouseInfoVO infoVO = new AppWarehouseInfoVO();

        BeanUtils.copyProperties(warehouseBills, infoVO);
        // 如果是入库
        if (infoVO.getfBilltype().equals(WarehouseTypeEnum.SJRK.getType())) {
            isInStock(infoVO);
        }
        // 如果是入库
        if (infoVO.getfBilltype().equals(WarehouseTypeEnum.SJCK.getType())) {
            isOutStock(infoVO);
        }
        // 如果是货权转移
        if (warehouseBills.getfBilltype().equals(WarehouseTypeEnum.HQZY.getType())) {
            isGoodsForwarding(infoVO);
        }
        // 如果是调拨
        if (warehouseBills.getfBilltype().equals(WarehouseTypeEnum.CKDB.getType())) {
            isTransfer(infoVO);
        }
        // 查询订单附件
        List<TEnclosure> tEnclosureList = tEnclosureMapper.selectTEnclosureByPId(infoVO.getfId());
        if (CollectionUtils.isNotEmpty(tEnclosureList)) {
            infoVO.setEnclosureList(tEnclosureList);
        }
        return AjaxResult.success(infoVO);
    }

    /**
     * 货转根据提单号查询可用客户、仓库信息
     *
     * @param warehousebillsDTO 查询条件
     * @return
     */
    @Override
    public AjaxResult corpOrWarehouseByMblno(WarehousebillsDTO warehousebillsDTO) {
        String fMblno = warehousebillsDTO.getfMblno();
        WarehouseBillsVO billsVO = new WarehouseBillsVO();
        // 查询客户
        if (WarehouseTypeEnum.BY_MBLNO.getType().equals(warehousebillsDTO.getType())) {
            // 查询符合条件的库存总帐
            TWhgenleg tWhgenleg = new TWhgenleg();
            tWhgenleg.setfMblno(fMblno);
            List<TWhgenleg> tWhgenlegs = tWhgenlegMapper.selectTWhgenlegList(tWhgenleg);
            if (CollectionUtils.isNotEmpty(tWhgenlegs)) {
                // 查询客户
                List<Long> corpIds = tWhgenlegs.stream().filter(leg -> Objects.nonNull(leg.getfCorpid())).map(TWhgenleg::getfCorpid)
                        .distinct().collect(toList());
                if (CollectionUtils.isNotEmpty(corpIds)) {
                    List<TCorps> corpsList = tCorpsMapper.selectByIds(corpIds);
                    billsVO.setCorpsList(corpsList);
                }
            }
            return AjaxResult.success(billsVO);
        } else if (WarehouseTypeEnum.BY_CPRP.getType().equals(warehousebillsDTO.getType())) {
            if (StringUtils.isNull(warehousebillsDTO.getCorpId())) {
                throw new WarehouseException("未找到客户查询条件");
            }
            // 查询符合条件的库存总帐
            TWhgenleg tWhgenleg = new TWhgenleg();
            tWhgenleg.setfMblno(fMblno);
            tWhgenleg.setfCorpid(warehousebillsDTO.getCorpId());
            List<TWhgenleg> tWhgenlegs = tWhgenlegMapper.selectTWhgenlegList(tWhgenleg);
            if (CollectionUtils.isNotEmpty(tWhgenlegs)) {
                // 查询仓库信息
                List<Long> warehouseIds = tWhgenlegs.stream().filter(leg -> Objects.nonNull(leg.getfWarehouseid()))
                        .map(TWhgenleg::getfWarehouseid).distinct().collect(toList());
                if (CollectionUtils.isNotEmpty(warehouseIds)) {
                    List<TWarehouse> warehouseList = tWarehouseMapper.selectByIds(warehouseIds);
                    billsVO.setWarehouseList(warehouseList);
                }
            }
            return AjaxResult.success(billsVO);
        } else if (WarehouseTypeEnum.BY_WAREHOUSE.getType().equals(warehousebillsDTO.getType())) {
            if (StringUtils.isNull(warehousebillsDTO.getCorpId()) ||
                    StringUtils.isNull(warehousebillsDTO.getWarehouseId())) {
                throw new WarehouseException("未找到客户、仓库查询条件");
            }
            // 查询符合条件的库存总帐
            TWhgenleg tWhgenleg = new TWhgenleg();
            tWhgenleg.setfMblno(fMblno);
            tWhgenleg.setfCorpid(warehousebillsDTO.getCorpId());
            tWhgenleg.setfWarehouseid(warehousebillsDTO.getWarehouseId());
            List<TWhgenleg> tWhgenlegs = tWhgenlegMapper.selectTWhgenlegList(tWhgenleg);
            if (CollectionUtils.isNotEmpty(tWhgenlegs)) {

                List<Long> goodsIds = tWhgenlegs.stream().filter(l -> Objects.nonNull(l.getfGoodsid())).map(TWhgenleg::getfGoodsid).distinct()
                        .collect(toList());
                if (CollectionUtils.isNotEmpty(goodsIds)) {
                    List<TGoods> goodsList = tGoodsMapper.selectByIds(goodsIds);
                    List<GoodsVO> voList = new ArrayList<>();

                    goodsList.forEach(vo -> {
//                        TGoods goods = goodsList.stream().filter(li -> Objects.equals(vo.getfGoodsid(), li.getfId())).findFirst()
//                                .orElseThrow(() -> new WarehouseException("商品信息找不到"));
                        GoodsVO goodsVO = new GoodsVO();
                        goodsVO.setfId(vo.getfId());
                        goodsVO.setfName(vo.getfName());
//                        goodsVO.setFMarks(vo.getfMarks());
//                        goodsVO.setFBusinessType(vo.getfBusinessType());
                        voList.add(goodsVO);
                    });
                    billsVO.setGoodsVOList(voList);
                }
                return AjaxResult.success(billsVO);
            }
        }
        return AjaxResult.success(billsVO);
    }

    /**
     * 快速入库-暂存
     *
     * @param warehousebillsDTO
     * @param loginUser
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult quickStaging(WarehousebillsDTO warehousebillsDTO, LoginUser loginUser) {
        // 校验必填项
        warehouseBillsfilterService.filter(warehousebillsDTO, WarehouseTypeEnum.SAVE.getType());
        // 定义计算毛重净重的仓库主表
        TWarehouseBills warehouseBills = new TWarehouseBills();
        // 根据客户、提单号、仓库是否存在已入库数据，若已存在则追加在其上面
        TWarehouseBills warehouseCondition = new TWarehouseBills();
        warehouseCondition.setfMblno(warehousebillsDTO.getfMblno());
        warehouseCondition.setfCorpid(warehousebillsDTO.getfCorpid());
        warehouseCondition.setfBilltype(WarehouseTypeEnum.SJRK.getType());
        warehouseCondition.setfWarehouseid(warehousebillsDTO.getfWarehouseid());
        warehouseCondition.setfTrademodeid(warehousebillsDTO.getfTrademodeid());
        warehouseCondition.setfBillstatus(Long.parseLong(WarehouseTypeEnum.SAVE.getType()));
        List<TWarehouseBills> warehouseBillsList = tWarehouseBillsMapper.selectTWarehousebillsList(warehouseCondition);
        // 如果是入库、存在一条入库数据
        if (warehousebillsDTO.getfBilltype().equals(WarehouseTypeEnum.SJRK.getType()) &&
                CollectionUtils.isNotEmpty(warehouseBillsList) && warehouseBillsList.size() == 1) {
            TWarehouseBills bills = warehouseBillsList.stream().findFirst()
                    .orElseThrow(() -> new WarehouseException("查询仓库信息失败"));
            // 赋值新对象
            BeanUtils.copyProperties(bills, warehouseBills);
            warehousebillsDTO.setfId(bills.getfId());
        } else {
            // 生成编号
            String billNo = billnoSerialServiceImpl.getBillNo(warehousebillsDTO.getfBilltype(), warehousebillsDTO.getfBsdate());
            warehousebillsDTO.setfBillno(billNo);
            // 如果是入库则需要赋值客户存货编号
            if (WarehouseTypeEnum.SJRK.getType().equals(warehousebillsDTO.getType())) {
                Date time = new Date();
                String bscorpno = billnoSerialServiceImpl.getCorpNo(warehousebillsDTO.getfCorpid(), time);
                warehousebillsDTO.setfBscorpno(bscorpno);
            }
            warehousebillsDTO.setfDateChanged(DateUtils.getTimestamp(new Date()).toString() + (int) (Math.random() * 900) + 100);
            warehousebillsDTO.setCreateTime(new Date());
            warehousebillsDTO.setfBillingway(2L);
            warehousebillsDTO.setCreateBy(loginUser.getUsername());
            warehousebillsDTO.setfBsdeptid(loginUser.getUser().getDeptId());
            warehousebillsDTO.setfChargedate(warehousebillsDTO.getfBsdate());
            warehousebillsDTO.setfBillstatus(Long.parseLong(WarehouseTypeEnum.SAVE.getType()));
            warehousebillsDTO.setfItemsStatus(Long.parseLong(WarehouseTypeEnum.DETAILED_STATUS_PROCESSED.getType()));
            tWarehouseBillsMapper.insertTWarehousebills(warehousebillsDTO);
            // 赋值新对象
            BeanUtils.copyProperties(warehousebillsDTO, warehouseBills);
        }
        // 遍历进行入库、出库确认
        List<TWarehousebillsitems> itemList = warehousebillsDTO.getWarehousebillsitemsList();
        int line = 1;
        String serialNumber;
        if (warehousebillsDTO.getfBilltype().equals(WarehouseTypeEnum.SJRK.getType())) {
            serialNumber = billnoSerialServiceImpl.getSerialNumber(WarehouseTypeEnum.SJRK_NO.getType(), new Date());
        } else {
            serialNumber = billnoSerialServiceImpl.getSerialNumber(WarehouseTypeEnum.SJCK_NO.getType(), new Date());
        }
        for (TWarehousebillsitems li : itemList) {
            li.setfPid(warehouseBills.getfId());
            li.setfBillstatus(10L);
            li.setfSerialNumber(serialNumber);
            li.setfBillno(warehouseBills.getfBillno());
            li.setfBilltype(warehouseBills.getfBilltype());
            if (warehouseBills.getfBilltype().equals(WarehouseTypeEnum.SJRK.getType())) {
                quickStorage(warehouseBills, li, WarehouseTypeEnum.SAVE.getType(), line);
            } else if (warehouseBills.getfBilltype().equals(WarehouseTypeEnum.SJCK.getType())) {
                quickDelivery(warehouseBills, li, WarehouseTypeEnum.SAVE.getType(), line);
                line++;
            }
        }
        // 计算明细数据件数、毛重、净重总和数量
        calculationWarehouseService.calculationWarehouseQuantity(warehouseBills);
        calculationWarehouseService.calculationBillStatus(warehouseBills);
        tWarehouseBillsMapper.updateTWarehousebills(warehouseBills);
        // 遍历费用信息
        if (CollectionUtils.isNotEmpty(warehousebillsDTO.getWarehousebillsfeesList())) {
            quickFee(warehouseBills, warehousebillsDTO.getWarehousebillsfeesList());
        }
        warehousebillsDTO.setBsDate(warehousebillsDTO.getfBsdate().getTime());
        warehousebillsDTO.setBsTime(warehousebillsDTO.getfBstime().getTime());
        return AjaxResult.success(warehousebillsDTO);
    }

    /**
     * 快速出、入库-提交
     *
     * @param warehousebillsDTO 出库信息
     * @param loginUser         登陆人
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult quickOperation(WarehousebillsDTO warehousebillsDTO, LoginUser loginUser) {
        if (CollectionUtils.isEmpty(warehousebillsDTO.getWarehousebillsitemsList())) {
            throw new WarehouseException("未找到仓储的明细数据");
        }
        // 校验必填项
        warehouseBillsfilterService.filter(warehousebillsDTO, WarehouseTypeEnum.SUBMIT.getType());
        // 遍历进行入库、出库确认
        List<TWarehousebillsitems> itemList = warehousebillsDTO.getWarehousebillsitemsList();
        int line = 1;
        for (TWarehousebillsitems li : itemList) {
            // 如果业务时间超出当前时间则不允许
            if (li.getfBsdate().after(new Date())) {
                throw new WarehouseException("业务日期不得超出当前日期");
            }
            li.setfPid(warehousebillsDTO.getfId());
            li.setfBillstatus(40L);
            li.setfBillno(warehousebillsDTO.getfBillno());
            li.setfBilltype(warehousebillsDTO.getfBilltype());
            if (warehousebillsDTO.getfBilltype().equals(WarehouseTypeEnum.SJRK.getType())) {
                quickStorage(warehousebillsDTO, li, WarehouseTypeEnum.SUBMIT.getType(), line);
            } else if (warehousebillsDTO.getfBilltype().equals(WarehouseTypeEnum.SJCK.getType())) {
                quickDelivery(warehousebillsDTO, li, WarehouseTypeEnum.SUBMIT.getType(), line);
                line++;
            }
        }
        // 计算明细数据件数、毛重、净重总和数量
        calculationWarehouseService.calculationWarehouseQuantity(warehousebillsDTO);
        calculationWarehouseService.calculationBillStatus(warehousebillsDTO);
        tWarehouseBillsMapper.updateTWarehousebills(warehousebillsDTO);
        // 遍历费用信息
        if (CollectionUtils.isNotEmpty(warehousebillsDTO.getWarehousebillsfeesList())) {
            quickFee(warehousebillsDTO, warehousebillsDTO.getWarehousebillsfeesList());
        }
        return AjaxResult.success();
    }

    /**
     * 快速入库
     *
     * @param warehouseBills 主表信息
     * @param item           明细信息
     * @param operateType    操作类型
     * @param line           序号
     */
    private void quickStorage(TWarehouseBills warehouseBills, TWarehousebillsitems item, String operateType, int line) {
        // 查询库容量  是否可入库
        if (calculation(warehouseBills.getfWarehouseid(), item.getfGrossweight()) <= 0) {
            throw new WarehouseException("仓储明细第" + line + "行入库毛重大于库容");
        }
        if (StringUtils.isNotEmpty(warehouseBills.getfCustomno())) {
            item.setfCustomno(warehouseBills.getfCustomno());
        }
        item.setfOriginalbilldate(item.getfBsdate());
        item.setfBillingway(warehouseBills.getfBillingway());
        if ("1".equals(warehouseBills.getfChargetype())) {
            item.setfChargedate(item.getfBsdate());
        } else {
            item.setfChargedate(new Date());
        }
        // 校验商品是否区分箱号
        TGoods goods = tGoodsMapper.selectTGoodsById(item.getfGoodsid());
        if ("1".equals(goods.getIfCntrno()) && StringUtils.isNull(item.getfCntrno())) {
            throw new WarehouseException("仓库明细第" + line + "行未找到箱号");
        }
        // 如果不为暂存的话则默认操作库存总帐
        if (!operateType.equals(WarehouseTypeEnum.SAVE.getType())) {
            TWhgenleg tWhgenle = queryTWhgenleg(warehouseBills, item, goods.getIfCntrno());
            if (Objects.nonNull(tWhgenle)) {
                updateTWhgenlegData(item, tWhgenle.getfId(), warehouseBills.getfBilltype());
            } else {
                instalTWhgenleg(warehouseBills, item);
            }
            item.setfIsInventory(Long.parseLong(WarehouseTypeEnum.INVENTORY.getType()));
        }
        if (Objects.nonNull(item.getfId())) {
            item.setUpdateTime(new Date());
            item.setUpdateBy(SecurityUtils.getUsername());
            tWarehousebillsitemsMapper.updateTWarehousebillsitems(item);
        } else {
            item.setCreateTime(new Date());
            item.setCreateBy(SecurityUtils.getUsername());
            tWarehousebillsitemsMapper.insertTWarehousebillsitems(item);
        }
        // 添加状态log
        insertTWarehousebillsLog(item, 40L);
    }

    /**
     * 快速出库
     *
     * @param warehouseBills 主表信息
     * @param item           明细信息
     * @param operateType    是否保存
     * @param line           序号
     */
    private void quickDelivery(TWarehouseBills warehouseBills, TWarehousebillsitems item, String operateType, int line) {
        // 校验商品是否区分箱号
        TGoods goods = tGoodsMapper.selectTGoodsById(item.getfGoodsid());
        if ("1".equals(goods.getIfCntrno()) && StringUtils.isNull(item.getfCntrno())) {
            throw new WarehouseException("仓库明细未找到箱号");
        }
        // 如果不为暂存的话则默认操作库存总帐
        if (!operateType.equals(WarehouseTypeEnum.SAVE.getType())) {
            // 查询总账是否存在
            TWhgenleg tWhgenle = queryTWhgenleg(warehouseBills, item, goods.getIfCntrno());
            if (Objects.nonNull(tWhgenle) && item.getfBsdate().before(tWhgenle.getfChargedate())) {
                throw new WarehouseException("出库明细第" + line + "行业务日期不得超出库存总帐日期");
            }
            if (Objects.isNull(tWhgenle)) {
                throw new WarehouseException("出库库存总帐第" + line + "行不存在");
            }
            //校验计费日期是等于库存总帐计费日，如果不相等则报错
            checkWhgenleg(item, tWhgenle);
            //  库存 <  出库件数
            if (tWhgenle.getfQtyblc() < item.getfQty()) {
                throw new WarehouseException("库存明细第" + line + "行库存不足");
            }
            // 更新库存总账
            updateTWhgenlegData(item, tWhgenle.getfId(), warehouseBills.getfBilltype());
        }
        if (Objects.nonNull(item.getfId())) {
            item.setUpdateTime(new Date());
            item.setUpdateBy(SecurityUtils.getUsername());
            tWarehousebillsitemsMapper.updateTWarehousebillsitems(item);
        } else {
            item.setCreateTime(new Date());
            item.setCreateBy(SecurityUtils.getUsername());
            tWarehousebillsitemsMapper.insertTWarehousebillsitems(item);
        }
        // 添加状态log
        insertTWarehousebillsLog(item, 40L);
    }

    /**
     * 快速-仓库费用
     *
     * @param warehouseBills         主表信息
     * @param warehousebillsfeesList 费用信息
     */
    private void quickFee(TWarehouseBills warehouseBills, List<TWarehousebillsfees> warehousebillsfeesList) {
        warehousebillsfeesList.forEach(fee -> {
            fee.setfPid(warehouseBills.getfId());
            if (Objects.nonNull(fee.getfId())) {
                fee.setUpdateTime(new Date());
                fee.setUpdateBy(SecurityUtils.getUsername());
                tWarehousebillsfeesMapper.updateTWarehousebillsfees(fee);
            } else {
                fee.setCreateTime(new Date());
                fee.setCreateBy(SecurityUtils.getUsername());
                tWarehousebillsfeesMapper.insertTWarehousebillsfees(fee);
            }
        });
    }

    /**
     * 校验提单号是否在同一天出现第二次
     *
     * @param warehousebillsDTO 查询条件
     */
    @Override
    public void checkMblNoRepeat(WarehousebillsDTO warehousebillsDTO) {
        if (CollectionUtils.isNotEmpty(warehousebillsDTO.getWarehousebillsitemsList())) {
            List<TWarehousebillsitems> items = warehousebillsDTO.getWarehousebillsitemsList();
            for (TWarehousebillsitems li : items) {
                if (StringUtils.isNotEmpty(li.getfCntrno())) {
                    warehousebillsDTO.setfCntrno(li.getfCntrno());
                }
//                int num = tWarehouseBillsMapper.selectByMblnoOrCntrnoCount(warehousebillsDTO);
//                if (num > 0 && StringUtils.isEmpty(li.getfCntrno())) {
//                    throw new WarehouseException("该提单号存在重复录入");
//                }
            }
        }
    }

    /**
     * app查询库存总帐明细
     *
     * @param id 查询条件
     * @return 库存总帐明细
     */
    @Override
    public AjaxResult selectWhgenlegDetail(Long id) {
        // 查询明细
        List<WarehouseBillsVO> warehouseBillsVOList = tWarehouseBillsMapper.selectWhgenlegDetailById(id);

        warehouseBillsVOList.forEach(vo -> {
            WarehouseTypeEnum warehouseTypeEnum = WarehouseTypeEnum.fromType(vo.getfBilltype());
            vo.setBillTypeName(warehouseTypeEnum.getName());
        });

        return AjaxResult.success(warehouseBillsVOList);
    }

    @Override
    @Transactional
    public AjaxResult cancellationFees(String tWarehousebills, String tWarehousebillsCntr, String tWarehousebillsCntritems, String tWarehousebillsfeesCr, String tWarehousebillsfeesDr, LoginUser loginUser, String billsType) {
        long actId = 460;
        Long billStatus = 2L;
        TWarehouseBills warehouseBills = JSONArray.parseObject(tWarehousebills, TWarehouseBills.class);
        Map<String, Object> map = new HashMap<>();
        TWarehouseBills tWarehouseBills = tWarehouseBillsMapper.selectTWarehousebillsById(warehouseBills.getfId());
        if (tWarehouseBills == null) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("找不到订单信息");
        }
        AjaxResult ajaxResult = this.changeFees(warehouseBills.getfId());
        String code = ajaxResult.get("code").toString();
        if ("500".equals(code)) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ajaxResult;
        }
        warehouseBills.setfTimes(tWarehouseBills.getfTimes() - 1);
        Integer integer = tWarehouseBillsMapper.updateTWarehousebills(warehouseBills);
        map.put("tWarehouseBills", tWarehouseBills);
        if (StringUtils.isNotEmpty(tWarehousebillsCntritems)) {
            JSONArray jsonCrArray = JSONArray.parseArray(tWarehousebillsCntritems);
            List<TWarehousebillsCntritems> tWarehousebillsCntritemsList = JSONObject.parseArray(jsonCrArray.toJSONString(), TWarehousebillsCntritems.class);
            map.put("tWarehousebillsCntritemsList", tWarehousebillsCntritemsList);
        }
        if (StringUtils.isNotNull(tWarehousebillsfeesCr) && !"[]".equals(tWarehousebillsfeesCr)) {
            JSONArray jsonCrArray = JSONArray.parseArray(tWarehousebillsfeesCr);
            List<TWarehousebillsfees> warehousebillsfeesCrList = JSONObject.parseArray(jsonCrArray.toJSONString(), TWarehousebillsfees.class);
            for (TWarehousebillsfees wbCr : warehousebillsfeesCrList) {
                if (wbCr.getfId() == null) {
                    wbCr.setfPid(warehouseBills.getfId());
                    wbCr.setfDc("C");
                    wbCr.setfBilltype(billsType);
                    wbCr.setfBillstatus(billStatus);
                    wbCr.setCreateTime(new Date());
                    wbCr.setSrcBillNo(tWarehouseBills.getfBillno());
                    wbCr.setCreateBy(loginUser.getUser().getUserName());
                    //wbCr.setfChargedate(warehouseBills.getfChargedate());
                    //wbCr.setfBillingDeadline(warehouseBills.getfChargedate());
                    if (warehouseBills.getfBsdate() != null && !warehouseBills.getfBsdate().equals("")) {
                        wbCr.setfBsdate(warehouseBills.getfBsdate());
                    }
                    tWarehousebillsfeesMapper.insertTWarehousebillsfees(wbCr);
                } else {
                    wbCr.setfBillstatus(billStatus);
                    wbCr.setUpdateBy(loginUser.getUser().getUserName());
                    wbCr.setUpdateTime(new Date());
                    tWarehousebillsfeesMapper.updateTWarehousebillsfees(wbCr);
                }
            }
            map.put("warehousebillsfeesCrList", warehousebillsfeesCrList);
        }
        if (StringUtils.isNotNull(tWarehousebillsfeesDr) && !"[]".equals(tWarehousebillsfeesDr)) {
            JSONArray jsonCrArray = JSONArray.parseArray(tWarehousebillsfeesDr);
            List<TWarehousebillsfees> warehousebillsfeesDrList = JSONObject.parseArray(jsonCrArray.toJSONString(), TWarehousebillsfees.class);
            for (TWarehousebillsfees wbDr : warehousebillsfeesDrList) {
                if (wbDr.getfId() == null) {
                    wbDr.setfPid(warehouseBills.getfId());
                    wbDr.setfDc("D");
                    wbDr.setfBillstatus(billStatus);
                    wbDr.setfBilltype(billsType);
                    wbDr.setCreateTime(new Date());
                    wbDr.setSrcBillNo(tWarehouseBills.getfBillno());
                    wbDr.setCreateBy(loginUser.getUser().getUserName());
                    //wbDr.setfChargedate(warehouseBills.getfChargedate());
                    //wbDr.setfBillingDeadline(warehouseBills.getfChargedate());
                    if (warehouseBills.getfBsdate() != null && !warehouseBills.getfBsdate().equals("")) {
                        wbDr.setfBsdate(warehouseBills.getfBsdate());
                    }
                    tWarehousebillsfeesMapper.insertTWarehousebillsfees(wbDr);
                } else {
                    wbDr.setfBillstatus(billStatus);
                    wbDr.setUpdateTime(new Date());
                    wbDr.setUpdateBy(loginUser.getUser().getUserName());
                    tWarehousebillsfeesMapper.updateTWarehousebillsfees(wbDr);
                }
            }
            map.put("warehousebillsfeesDrList", warehousebillsfeesDrList);
        }
        if (StringUtils.isNotEmpty(tWarehousebillsCntr) && !"[]".equals(tWarehousebillsCntr)) {
            JSONArray jsonCrArray = JSONArray.parseArray(tWarehousebillsCntr);
            List<TWarehousebillsCntr> tWarehousebillsCntrList = JSONObject.parseArray(jsonCrArray.toJSONString(), TWarehousebillsCntr.class);
            map.put("tWarehousebillsCntrList", tWarehousebillsCntrList);
        }
        //删除审批流
        //1.查找审批流
        AuditItems auditItems = new AuditItems();
        auditItems.setActId(actId);
        auditItems.setBillId(warehouseBills.getfId());
        auditItems.setId(warehouseBills.getfId());
        auditItems.setFidStatus("f_billstatus");
        //删除审批流信息
        auditItemsMapper.deletePurchaseApproval(auditItems);

        return AjaxResult.success("success", map);
    }

    /**
     * 如果是入库
     *
     * @param infoVO
     * @return
     */
    private void isInStock(AppWarehouseInfoVO infoVO) {
        if (StringUtils.isNotNull(infoVO.getfCorpid())) {
            TCorps corps = tCorpsMapper.selectTCorpsById(infoVO.getfCorpid());
            // 赋值客户id
            infoVO.setCorpName(corps.getfName());
        }
        // 计费单位
        if (StringUtils.isNotNull(infoVO.getfFeetunit())) {
            String type = "data_unitfees";
            String dictLabel = DictUtils.getDictLabel(type, infoVO.getfFeetunit());
            if (StringUtils.isNotEmpty(dictLabel)) {
                infoVO.setFeetunitName(dictLabel);
            }
        }
        // 商品信息
        if (StringUtils.isNotNull(infoVO.getfGoodsid())) {
            // 添加商品信息
            TGoods tGoods = tGoodsMapper.selectTGoodsById(infoVO.getfGoodsid());
            if (Objects.nonNull(tGoods)) {
                infoVO.setGoodsName(tGoods.getfName());
            }
        }
        // 查询仓库信息
        TWarehouse tWarehouse = tWarehouseMapper.selectTWarehouseById(infoVO.getfWarehouseid());
        if (Objects.nonNull(tWarehouse)) {
            infoVO.setWarehouseName(tWarehouse.getfName());
        }
        // 入库查询箱型箱量
        TWarehousebillsCntr warehousebillsCntr = new TWarehousebillsCntr();
        warehousebillsCntr.setfPid(infoVO.getfId());
        List<TWarehousebillsCntr> cntrsList = tWarehousebillsCntrMapper.selectTWarehousebillsCntrList(warehousebillsCntr);
        if (CollectionUtils.isNotEmpty(cntrsList)) {
            List<Long> cntrIds = cntrsList.stream().map(TWarehousebillsCntr::getfCntrid).distinct().collect(toList());
            if (CollectionUtils.isNotEmpty(cntrIds)) {
                List<TCntr> cntrList = tCntrMapper.selectByIds(cntrIds);

                cntrsList.forEach(li -> {
                    TCntr cntr = cntrList.stream().filter(c -> Objects.equals(c.getfId(), li.getfCntrid())).findFirst()
                            .orElseThrow(() -> new WarehouseException("找不到集装箱信息"));
                    li.setCntrName(cntr.getfName());
                });
            }
            infoVO.setCntrsList(cntrsList);
        }
    }

    /**
     * 如果是出库
     *
     * @param infoVO
     * @return
     */
    private void isOutStock(AppWarehouseInfoVO infoVO) {
        if (StringUtils.isNotNull(infoVO.getfCorpid())) {
            TCorps corps = tCorpsMapper.selectTCorpsById(infoVO.getfCorpid());
            // 赋值客户id
            infoVO.setCorpName(corps.getfName());
        }
        // 结算方式
        if (StringUtils.isNotNull(infoVO.getfStltypeid())) {
            // 定义结算方式
            String fStltypeid = "data_stltype_type";
            String dictLabel = DictUtils.getDictLabel(fStltypeid, infoVO.getfStltypeid().toString());
            infoVO.setStltypeName(dictLabel);
        }
        // 查询仓库信息
        TWarehouse tWarehouse = tWarehouseMapper.selectTWarehouseById(infoVO.getfWarehouseid());
        if (Objects.nonNull(tWarehouse)) {
            infoVO.setWarehouseName(tWarehouse.getfName());
        }
    }

    /**
     * 如果是货转
     *
     * @param infoVO
     * @return
     */
    private void isGoodsForwarding(AppWarehouseInfoVO infoVO) {
        // 查询客户信息
        List<Long> corpIds = new ArrayList<>();
        // 如果是货转客户那么也要查询
        if (StringUtils.isNotNull(infoVO.getfTocorpid())) {
            corpIds.add(infoVO.getfTocorpid());
        }
        corpIds.add(infoVO.getfCorpid());
        List<TCorps> corpsList = tCorpsMapper.selectByIds(corpIds);
        // 赋值客户id
        TCorps corps = corpsList.stream().filter(li -> Objects.equals(li.getfId(), infoVO.getfCorpid())).findFirst()
                .orElseThrow(() -> new WarehouseException("客户不存在"));
        infoVO.setCorpName(corps.getfName());
        // 赋值货转客户id
        TCorps toCorp = corpsList.stream().filter(li -> Objects.equals(li.getfId(), infoVO.getfTocorpid())).findFirst()
                .orElseThrow(() -> new WarehouseException("客户不存在"));
        infoVO.setToCorpName(toCorp.getfName());
        // 查询仓库信息
        TWarehouse tWarehouse = tWarehouseMapper.selectTWarehouseById(infoVO.getfWarehouseid());
        if (Objects.nonNull(tWarehouse)) {
            infoVO.setWarehouseName(tWarehouse.getfName());
        }
        // 结算方式
        if (StringUtils.isNotNull(infoVO.getfStltypeid())) {
            // 定义结算方式
            String fStltypeid = "data_stltype_type";
            String dictLabel = DictUtils.getDictLabel(fStltypeid, infoVO.getfStltypeid().toString());
            infoVO.setStltypeName(dictLabel);
        }
        // 贸易方式
        if (StringUtils.isNotNull(infoVO.getfTrademodeid())) {
            String type = "data_trademodes";
            // 转换贸易方式
            String dictLabel = DictUtils.getDictLabel(type, infoVO.getfTrademodeid().toString());
            if (StringUtils.isNotEmpty(dictLabel)) {
                infoVO.setNewTrademodeName(dictLabel);
            }
        }
        // 计费单位
        if (StringUtils.isNotNull(infoVO.getfFeetunit())) {
            String type = "data_unitfees";
            String dictLabel = DictUtils.getDictLabel(type, infoVO.getfFeetunit().toString());
            if (StringUtils.isNotEmpty(dictLabel)) {
                infoVO.setFeetunitName(dictLabel);
            }
        }
        // 商品信息
        if (StringUtils.isNotNull(infoVO.getfGoodsid())) {
            // 添加商品信息
            TGoods tGoods = tGoodsMapper.selectTGoodsById(infoVO.getfGoodsid());
            if (Objects.nonNull(tGoods)) {
                infoVO.setGoodsName(tGoods.getfName());
            }
        }
    }

    /**
     * 如果是调拨
     *
     * @param infoVO
     * @return
     */
    private void isTransfer(AppWarehouseInfoVO infoVO) {
        if (StringUtils.isNotNull(infoVO.getfCorpid())) {
            TCorps corps = tCorpsMapper.selectTCorpsById(infoVO.getfCorpid());
            // 赋值客户id
            infoVO.setCorpName(corps.getfName());
        }
        // 作业类型
        if (StringUtils.isNotNull(infoVO.getfBusinessType())) {
            String type = "st_trans_type";
            String dictLabel = DictUtils.getDictLabel(type, infoVO.getfBusinessType().toString());
            if (StringUtils.isNotEmpty(dictLabel)) {
                infoVO.setBusinessTypeName(dictLabel);
            }
        }
        // 贸易方式
        if (StringUtils.isNotNull(infoVO.getfTrademodeid())) {
            String type = "data_trademodes";
            // 转换贸易方式
            String dictLabel = DictUtils.getDictLabel(type, infoVO.getfTrademodeid().toString());
            if (StringUtils.isNotEmpty(dictLabel)) {
                infoVO.setNewTrademodeName(dictLabel);
            }
        }
        // 仓库id集合
        List<Long> warehouseIds = new ArrayList<>();
        if (StringUtils.isNotNull(infoVO.getfInwarehouseid())) {
            warehouseIds.add(infoVO.getfInwarehouseid());
        }
        warehouseIds.add(infoVO.getfWarehouseid());
        // 查询仓库信息
        List<TWarehouse> tWarehouseList = tWarehouseMapper.selectByIds(warehouseIds);

        TWarehouse tWarehouse = tWarehouseList.stream().filter(li -> Objects.equals(li.getfId(), infoVO.getfWarehouseid())).findFirst()
                .orElseThrow(() -> new WarehouseException("仓库不存在"));
        infoVO.setWarehouseName(tWarehouse.getfName());
        if (StringUtils.isNotNull(infoVO.getfInwarehouseid())) {
            // 调入仓库
            TWarehouse inWarehouse = tWarehouseList.stream().filter(li -> Objects.equals(li.getfId(), infoVO.getfInwarehouseid())).findFirst()
                    .orElseThrow(() -> new WarehouseException("仓库不存在"));
            infoVO.setInWarehouseName(inWarehouse.getfName());
        }
    }

    /**
     * 能否修改费用信息
     *
     * @param id 订单主表id
     * @return
     */
    private AjaxResult changeFees(Long id) {
        List<TWarehousebillsfees> warehousebillsfees = tWarehousebillsfeesMapper.selectFeesByPId(id, null);
        if (CollectionUtils.isNotEmpty(warehousebillsfees)) {
            for (TWarehousebillsfees warehousebillsfee : warehousebillsfees) {
                if (warehousebillsfee.getfAccamount() != null && warehousebillsfee.getfAccamount().compareTo(new BigDecimal(BigInteger.ZERO)) == 1) {
                    return AjaxResult.error("费用已对账");
                }
                if (warehousebillsfee.getfStlamount() != null && warehousebillsfee.getfStlamount().compareTo(new BigDecimal(BigInteger.ZERO)) == 1) {
                    return AjaxResult.error("费用已收费付费");
                }
                if (warehousebillsfee.getfInvamount() != null && warehousebillsfee.getfInvamount().compareTo(new BigDecimal(BigInteger.ZERO)) == 1) {
                    return AjaxResult.error("费用已开票");
                }
            }
        }
        return AjaxResult.success();
    }

    /**
     * 出入库、库存统计
     *
     * @return
     */
    @Override
    public AjaxResult stockStatistics() {
        String external = null;
        String customerName;
        SysUser user = SecurityUtils.getLoginUser().getUser();
        if ("外部用户".equals(user.getDept().getDeptName())) {
            external = user.getUserName();
            customerName = String.valueOf(tCustomerContactMapper.getCustomerName(external).get("customerName"));
        } else {
            SysConfig config = new SysConfig();
            config.setConfigKey("data_print_title");
            customerName = configMapper.selectConfig(config).getConfigValue();
        }

        Map<String, String> data = new HashMap<>();
        // 客户名称
        data.put("customerName", customerName);
        // 全部库存
        data.put("stockTotal", stockStatistics(null, null, external));

        // 今天
        data.put("inStockTotalToday", inAndOutStockStatistics("SJRK", DateUtils.today(), DateUtils.today(), external));
        data.put("outStockTotalToday", inAndOutStockStatistics("SJCK", DateUtils.today(), DateUtils.today(), external));
        // 昨天
        data.put("inStockTotalYesterday", inAndOutStockStatistics("SJRK", DateUtils.yesterday(), DateUtils.yesterday(), external));
        data.put("outStockTotalYesterday", inAndOutStockStatistics("SJCK", DateUtils.yesterday(), DateUtils.yesterday(), external));
        // 本周
        data.put("inStockTotalWeek", inAndOutStockStatistics("SJRK", DateUtils.beginOfWeek(), DateUtils.endOfWeek(), external));
        data.put("outStockTotalWeek", inAndOutStockStatistics("SJCK", DateUtils.beginOfWeek(), DateUtils.endOfWeek(), external));
        // 本月
        data.put("inStockTotalMonth", inAndOutStockStatistics("SJRK", DateUtils.beginOfMonth(), DateUtils.endOfMonth(), external));
        data.put("outStockTotalMonth", inAndOutStockStatistics("SJCK", DateUtils.beginOfMonth(), DateUtils.endOfMonth(), external));
        // 上个月
        data.put("inStockTotalLastMonth", inAndOutStockStatistics("SJRK", DateUtils.beginOfLastMonth(), DateUtils.endOfLastMonth(), external));
        data.put("outStockTotalLastMonth", inAndOutStockStatistics("SJCK", DateUtils.beginOfLastMonth(), DateUtils.endOfLastMonth(), external));

        // 库龄
        data.put("stockDays", String.valueOf(tWhgenlegMapper.stockDays(external).get("days")));
        return AjaxResult.success(data);
    }

    /**
     * 周期库存统计
     *
     * @return
     */
    @Override
    public AjaxResult cycleStockStatistics() {
        String external = null;
        SysUser user = SecurityUtils.getLoginUser().getUser();
        if ("外部用户".equals(user.getDept().getDeptName())) {
            external = user.getUserName();
        }

        Map<String, String> data = new HashMap<>();
        // 7天
        data.put("stockTotalA", stockStatistics(DateUtils.offsetDate(-6), null, external));
        // 15天
        data.put("stockTotalB", stockStatistics(DateUtils.offsetDate(-14), DateUtils.offsetDate(-6), external));
        // 30天
        data.put("stockTotalC", stockStatistics(DateUtils.offsetDate(-29), DateUtils.offsetDate(-14), external));
        // 60天
        data.put("stockTotalD", stockStatistics(DateUtils.offsetDate(-59), DateUtils.offsetDate(-29), external));
        // 90天
        data.put("stockTotalE", stockStatistics(DateUtils.offsetDate(-89), DateUtils.offsetDate(-59), external));
        // 180天
        data.put("stockTotalF", stockStatistics(DateUtils.offsetDate(-179), DateUtils.offsetDate(-89), external));
        // 180天+
        data.put("stockTotalG", stockStatistics(null, DateUtils.offsetDate(-179), external));
        return AjaxResult.success(data);
    }

    private String inAndOutStockStatistics(String billType, String beginDate, String endDate, String external) {
        beginDate += " 00:00:00";
        endDate += " 23:59:59";
        Map<String, Object> statistics = tWarehousebillsfeesMapper.inAndOutStockStatistics(billType, beginDate, endDate, external);
        return String.valueOf(statistics.get("total"));
    }

    private String stockStatistics(String beginDate, String endDate, String external) {
        if (StringUtils.isNotEmpty(beginDate)) {
            beginDate += " 00:00:00";
        }
        if (StringUtils.isNotEmpty(endDate)) {
            endDate += " 00:00:00";
        }
        Map<String, Object> statistics = tWhgenlegMapper.stockStatistics(beginDate, endDate, external);
        return String.valueOf(statistics.get("total"));
    }

}
