package com.ruoyi.warehouseBusiness.service.impl;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.approvalFlow.domain.AuditItems;
import com.ruoyi.approvalFlow.mapper.AuditItemsMapper;
import com.ruoyi.approvalFlow.service.impl.AuditItemsServiceImpl;
import com.ruoyi.basicData.domain.*;
import com.ruoyi.basicData.mapper.*;
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.model.LoginUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.reportManagement.domain.TWareHouseItemsExcel;
import com.ruoyi.reportManagement.domain.TWhgenleg;
import com.ruoyi.reportManagement.mapper.TWhgenlegMapper;
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.warehouseBusiness.domain.*;
import com.ruoyi.warehouseBusiness.mapper.*;
import com.ruoyi.warehouseBusiness.service.ITWarehouseBillsService;
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 com.ruoyi.common.core.domain.entity.TWarehouse;

import java.math.BigDecimal;
import java.util.*;

import static java.util.stream.Collectors.toList;

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

    @Autowired
    private TWhgenlegMapper tWhgenlegMapper;

    @Autowired
    private TGoodsMapper tGoodsMapper;

    @Autowired
    private SysConfigMapper sysConfigMapper;

    @Autowired
    private AuditItemsServiceImpl auditItemsService;

    @Autowired
    private AuditItemsMapper auditItemsMapper;

    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private TCorpsMapper tCorpsMapper;

    @Autowired
    private TFeesMapper tFeesMapper;

    @Autowired
    private TWarehouseMapper tWarehouseMapper;

    @Autowired
    private SysDictDataMapper sysDictDataMapper;

    @Autowired
    private TWarehouseAreaMapper tWarehouseAreaMapper;

    @Autowired
    private TEnclosureMapper tEnclosureMapper;

    @Autowired
    private TWarehouseBillsMapper tWarehouseBillsMapper;

    @Autowired
    private TWarehousebillsfeesMapper tWarehousebillsfeesMapper;

    @Autowired
    private TWarehousebillsitemsMapper tWarehousebillsitemsMapper;

    @Autowired
    private BillnoSerialServiceImpl billnoSerialServiceImpl;

    @Autowired
    private BillnoDelMapper billnoDelMapper;

    @Autowired
    private TWarehousebillsLogMapper tWarehousebillsLogMapper;

    @Autowired
    private TWarehouseAgreementServiceImpl tWarehouseAgreementService;


    /**
     * 查询详情主表
     *
     * @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> 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());
            corpsId.add(tWarehousebills.getfCorpid());
            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);
            }
            // 查询经营单位
            corpsId.add(tWarehousebills.getfSbu());
            map.put("warehousebills", tWarehousebills);
        }
        // 查询仓库明细从表数据
        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("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<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("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;
    }

    /**
     * 查询详情主表列表
     *
     * @param tWarehousebills 详情主表
     * @return 详情主表
     */
    @Override
    public List<Map<String, Object>> selectWarehouseBusinessList(TWarehouseBills tWarehousebills) {
        return tWarehouseBillsMapper.selectWarehouseBusinessList(tWarehousebills);
    }

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

    /**
     * 根据条件查询总账是否存在
     *
     * @param warehouseBills      仓库主表
     * @param warehousebillsitems 仓库明细表
     * @return 库存总账
     */
    public TWhgenleg queryTWhgenleg(TWarehouseBills warehouseBills, TWarehousebillsitems warehousebillsitems) {
        TWhgenleg tWhgenleg = new TWhgenleg();
        // 客户
        tWhgenleg.setfCorpid(warehouseBills.getfCorpid());
        // 提单号
        if ("HQZY".equals(warehouseBills.getfBilltype()) || "CKDB".equals(warehouseBills.getfBilltype())) {
            tWhgenleg.setfMblno(warehousebillsitems.getfMblno());
        } else {
            tWhgenleg.setfMblno(warehouseBills.getfMblno());
        }
        // 库区
        tWhgenleg.setfWarehouseLocationid(warehousebillsitems.getfWarehouselocid());
        // 货物品名
        tWhgenleg.setfGoodsid(warehousebillsitems.getfGoodsid());
        // 贸易方式
        tWhgenleg.setfTrademodeid(warehouseBills.getfTrademodeid());
        return tWhgenlegMapper.selectTWhgenleg(tWhgenleg);
    }

    /**
     * 新增库存总账
     *
     * @param warehouseBills      仓库主表
     * @param warehousebillsitems 仓库明细表
     * @return 结果
     */
    @Transactional
    public int instalTWhgenleg(TWarehouseBills warehouseBills, TWarehousebillsitems warehousebillsitems, SysUser user) {
        TWhgenleg tWhgenleg = new TWhgenleg();
        if ("SJRK".equals(warehouseBills.getfBilltype())) {
            tWhgenleg.setfOriginalbilldate(warehousebillsitems.getfBsdate());
        }
        if ("HQZY".equals(warehouseBills.getfBilltype()) || "CKDB".equals(warehouseBills.getfBilltype())) {
            tWhgenleg.setfOriginalbilldate(warehousebillsitems.getfOriginalbilldate());
            if ("CKDB".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());
        }
        // 明细类型
        tWhgenleg.setfBusinessType(warehousebillsitems.getfBusinessType());
        // 仓库
        tWhgenleg.setfWarehouseid(warehouseBills.getfWarehouseid());
        // 库区
        tWhgenleg.setfWarehouseLocationid(warehousebillsitems.getfWarehouselocid());
        // 货物品名
        tWhgenleg.setfGoodsid(warehousebillsitems.getfGoodsid());
        // 计费方式
        tWhgenleg.setfBillingway(warehousebillsitems.getfBillingway());
        // 仓储计费日期
        tWhgenleg.setfChargedate(warehousebillsitems.getfChargedate());
        // 贸易方式
        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(user.getUserName());
        // 创建人
        tWhgenleg.setCreateTime(new Date());
        // 状态
        tWhgenleg.setfStatus("T");
        // 结余件数
        tWhgenleg.setfQtyblc(warehousebillsitems.getfQty());
        return tWhgenlegMapper.insertTWhgenleg(tWhgenleg);
    }

    @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 billsType) {
        Long fPid = null;
        Map<String, Object> map = new HashMap<>();
        TWarehouseBills warehouseBills = JSONArray.parseObject(tWarehouseBills, TWarehouseBills.class);
        if (StringUtils.isNull(warehouseBills.getfId())) {
            // 如果是新数据
            warehouseBills.setfBillstatus(2L);
            warehouseBills.setCreateBy(loginUser.getUser().getUserName());
            warehouseBills.setfBilltype(billsType);
            warehouseBills.setfBsdeptid(loginUser.getUser().getDeptId());
            // 业务编码
            String billNo = billnoSerialServiceImpl.getBillNo(billsType, warehouseBills.getfBsdate());
            warehouseBills.setfBillno(billNo);
            if ("SJRK".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)) {
                warehouseBills.setfChargedate(warehouseBills.getfBsdate());
            }
            warehouseBills.setUpdateBy(loginUser.getUser().getUserName());
            warehouseBills.setUpdateTime(new Date());
            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);
            for (TWarehousebillsitems wbItem : warehousebillsitemsList) {
                /*if(StringUtils.isNull(wbItem.getfSerialNumber())){
                    // 生成流水号
                    Date time = new Date();
                    String serialNumber;
                    if ("SJRK".equals(billsType)) { // 生成 入库 流水号
                        serialNumber = billnoSerialServiceImpl.getSerialNumber("RK", time);
                        wbItem.setfSerialNumber(serialNumber);
                    } else if ("SJCK".equals(billsType)) { //生成 出库 流水号
                        serialNumber = billnoSerialServiceImpl.getSerialNumber("CK", time);
                        wbItem.setfSerialNumber(serialNumber);
                    } else if ("CKDB".equals(billsType)) { //生成 出库 流水号
                        serialNumber = billnoSerialServiceImpl.getSerialNumber("DB", time);
                        wbItem.setfSerialNumber(serialNumber);
                    }
                }*/
                boolean warehouseStatus = "SJRK".equals(billsType) || "SJCK".equals(billsType) || "CKDB".equals(billsType);
                // 仓储计费日期
                wbItem.setfBilltype(billsType);
                if ("SJRK".equals(billsType)) {
                    wbItem.setfChargedate(warehouseBills.getfChargedate());
                    wbItem.setfBillingway(warehouseBills.getfBillingway());
                }
                if (null != wbItem.getfId()) {
                    wbItem.setUpdateTime(new Date());
                    wbItem.setUpdateBy(loginUser.getUser().getUserName());
                    tWarehousebillsitemsMapper.updateTWarehousebillsitems(wbItem);
                } else {
                    // 添加主表 业务单号
                    wbItem.setfBillno(warehouseBills.getfBillno());
                    if (!warehouseStatus) {
//                        wbItem.setfMblno(warehouseBills.getfMblno());
                        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, loginUser);
                    }
                }
            }
        }
        //  附件添加
        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(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 && !warehouseBills.getfBsdate().equals("")) {
                    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);
            }
        }
        TWarehousebillsitems warehousebillsitems = new TWarehousebillsitems();
        warehousebillsitems.setfPid(fPid);
        map.put("warehouseBills", warehouseBills);
        map.put("warehousebillsitems", tWarehousebillsitemsMapper.selectGoodsTransferitemsList(warehousebillsitems));
        return AjaxResult.success("成功", 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 billsType) {
        Long fPid = null;
        boolean isApprove = false;
        String key = "";
        long actId = 0L;
        if ("SJRK".equals(billsType)) {
            actId = 110L;
            key = "warehouse.inStock.ApprovalFlow";
        } else if ("SJCK".equals(billsType)) {
            actId = 120L;
            key = "warehouse.outStock.ApprovalFlow";
        } else if ("CKDB".equals(billsType)) {
            actId = 140L;
            key = "warehouse.stockTransfer.ApprovalFlow";
        } else if ("HQZY".equals(billsType)) {
            actId = 130L;
            key = "warehouse.transfer.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);
        warehouseBills.setfItemsStatus(4L);
        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)) {
                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)) {
                warehouseBills.setfChargedate(warehouseBills.getfBsdate());
            }
            warehouseBills.setUpdateBy(loginUser.getUser().getUserName());
            tEnclosureMapper.deleteByFPid(fPid);
            tWarehousebillsfeesMapper.deleteByFPid(fPid);
            tWarehousebillsitemsMapper.deleteByFPid(fPid);
            tWarehouseBillsMapper.updateTWarehousebills(warehouseBills);
        }
        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) || "CKDB".equals(billsType)) {
                // 除了入库其他模块不需要更新主表的 仓储费计费日期到明细表，其他模块 应从库存总账把仓储费计费日期 赋给明细表
                if ("SJRK".equals(billsType)) {
                    wbItem.setfMblno(warehouseBills.getfMblno());
                    wbItem.setfBillingway(warehouseBills.getfBillingway());
                    wbItem.setfChargedate(warehouseBills.getfChargedate());
                    wbItem.setfOriginalbilldate(warehouseBills.getfBsdate());
                }
                if (!wbItem.getfBillstatus().equals(40L)) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error("库存明细第" + line + "行状态异常，请确认");
                }
            } else {
                if (!wbItem.getfBillstatus().equals(6L)) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error("库存明细第" + line + "行状态异常，请确认");
                }
            }
            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(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");
                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");
            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();
//                Long code = Long.valueOf(String.valueOf(ajaxResult.get("code"))).longValue();
            if ("500".equals(code)) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
            return ajaxResult;
        }
    }

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

    @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.getSerialNumber("RK", time);
         } else if ("SJCK".equals(billsType)) { //生成 出库 流水号
             serialNumber = billnoSerialServiceImpl.getSerialNumber("CK", time);
         } else if ("CKDB".equals(billsType)) { //生成 出库 流水号
             serialNumber = billnoSerialServiceImpl.getSerialNumber("DB", time);
         }
         map.put("fSerialNumber",serialNumber);
        return AjaxResult.success("成功",map);
    }

    /**
     * 根据仓库主表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();
    }

    /**
     * 根据仓库主表id 更新对应明细表状态
     *
     * @param fPid 仓库主表id
     * @return 结果
     */
    @Transactional
    public AjaxResult storageFeeFollow(Long fPid, long fettle) {
        if (StringUtils.isNull(fPid)) {
            return AjaxResult.error("仓库更新状态未找到主表信息，请与管理员联系");
        }
        int warehouseUpdateResult = tWarehouseBillsMapper.warehouseFollowUpdate(fPid, fettle, new Date());
        if (warehouseUpdateResult <= 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("更新库存明细状态失败，请联系管理员");
        }
        TWarehousebillsfees warehousebillsfees = new TWarehousebillsfees();
        warehousebillsfees.setfPid(fPid);
        List<TWarehousebillsfees> warehousebillsfeesList = tWarehousebillsfeesMapper.selectTWarehousebillsfeesList(warehousebillsfees);
        for (TWarehousebillsfees wareItem : warehousebillsfeesList) {
            if (StringUtils.isNull(wareItem.getSrcId())) {
                continue;
            }
            if ("KCZZ".equals(wareItem.getfBilltype())) {
                TWhgenleg tWhgenleg = tWhgenlegMapper.selectTWhgenlegById(wareItem.getSrcId());
                tWhgenleg.setfChargedate(DateUtils.dateAdd(wareItem.getfBillingDeadline(), 1));
                int i = tWhgenlegMapper.updateTWhgenleg(tWhgenleg);
                if (i <= 0) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error("更新库存费用状态失败，请联系管理员");
                }
            } else {
                TWarehousebillsitems tWarehousebillsitems = tWarehousebillsitemsMapper.selectTWarehousebillsitemsById(wareItem.getSrcId());
                tWarehousebillsitems.setfChargedate(DateUtils.dateAdd(wareItem.getfBillingDeadline(), 1));
                if ("SJCK".equals(wareItem.getfBilltype())) {
                    tWarehousebillsitems.setfStorageFeeDeadline(wareItem.getfBillingDeadline());
                }
                tWarehousebillsitemsMapper.updateTWarehousebillsitems(tWarehousebillsitems);
            }
        }
        int feesUpdateResult = tWarehousebillsfeesMapper.warehouseFeesFollowUpdate(fPid, fettle, new Date());
        if (feesUpdateResult <= 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            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 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);
        tWarehouseBills.setfItemsStatus(4L);
        tWarehouseBills.setfBilltype(billsType);
        tWarehouseBills.setUpdateBy(loginUser.getUser().getUserName());
        tWarehouseBills.setUpdateTime(new Date());
        tWarehouseBillsMapper.updateTWarehousebills(tWarehouseBills);
        tEnclosureMapper.deleteByFPid(tWarehouseBills.getfId());
        tWarehousebillsfeesMapper.deleteByFPid(tWarehouseBills.getfId());
        boolean businessStatus = "场地直装".equals(tWarehouseBills.getfBusinessType());
        JSONArray warehouseJSON = JSONArray.parseArray(warehousebillsitems);
        List<TWarehousebillsitems> warehousebillsitemsList = JSONObject.parseArray(warehouseJSON.toJSONString(), TWarehousebillsitems.class);
        for (TWarehousebillsitems item : warehousebillsitemsList) {
            if (!businessStatus) {
                // 查询库容量  是否可入库
                int m = calculation(tWarehouseBills.getfWarehouseid(), item.getfGrossweight());
                if (m == 0) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error("更新库存总账失败-->入库毛重大于库容");
                }
                item.setfBillingway(tWarehouseBills.getfBillingway());
                item.setfChargedate(tWarehouseBills.getfChargedate());
                TWhgenleg tWhgenle = queryTWhgenleg(tWarehouseBills, item);
                if (StringUtils.isNotNull(tWhgenle)) {
                    int i = updateTWhgenlegData(item, tWhgenle.getfId(), billsType);
                    if (i <= 0) {
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return AjaxResult.error("更新库存总账失败");
                    }
                } else {
                    if (instalTWhgenleg(tWarehouseBills, item, loginUser.getUser()) <= 0) {
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return AjaxResult.error("新增库存总账失败");
                    }
                }
                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());
                num = tWarehousebillsitemsMapper.updateTWarehousebillsitems(item);
                // 添加状态log
                insertTWarehousebillsLog(item, 40L, loginUser);
            }
            if (num <= 0) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error("新增库存明细失败");
            }
        }
        //  附件添加
        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);
            }
        }
        map.put("warehousebillsitems", warehousebillsitemsList);
        return AjaxResult.success("成功", map);
    }

    /**
     * 出库、调拨、货转 确认
     *
     * @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 billsType) {
        Long fPid = null;
        Map<String, Object> map = new HashMap<>();
        TWarehouseBills tWarehouseBills = JSONArray.parseObject(warehouseBills, TWarehouseBills.class);
        tWarehouseBills.setfItemsStatus(4L);
        if (StringUtils.isNotNull(tWarehouseBills.getfId())) {
            tWarehouseBills.setUpdateBy(loginUser.getUser().getUserName());
            tWarehouseBills.setUpdateTime(new Date());
            tWarehouseBillsMapper.updateTWarehousebills(tWarehouseBills);
            fPid = tWarehouseBills.getfId();
        } else {
            tWarehouseBills.setfBsdeptid(loginUser.getUser().getDeptId());
            tWarehouseBills.setCreateBy(loginUser.getUser().getUserName());
            tWarehouseBills.setCreateTime(new Date());
            String billNo = billnoSerialServiceImpl.getBillNo(billsType, tWarehouseBills.getfBsdate());
            tWarehouseBills.setfBillno(billNo);
            tWarehouseBillsMapper.insertTWarehousebills(tWarehouseBills);
            fPid = tWarehouseBills.getfId();
        }
        tEnclosureMapper.deleteByFPid(fPid);
        tWarehousebillsfeesMapper.deleteByFPid(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<>();
        for (TWarehousebillsitems wbItem : warehousebillsitemsList) {
            long warehouselocId = 0L;
            long transferWarehouselocid = 0L;
            if ("CKDB".equals(billsType)) {
                warehouselocId = wbItem.getfWarehouselocid();
                transferWarehouselocid = wbItem.getfTransferWarehouselocid();
//                wbItem.setfWarehouselocid(transferWarehouselocid);
            }
            // 查询总账是否存在
            TWhgenleg tWhgenle = queryTWhgenleg(tWarehouseBills, wbItem);
            //  入库数特殊不判断入账
            if ("SJCK".equals(billsType)) { // 出库 查询
                if (StringUtils.isNull(tWhgenle)) { // 为空 提示没有库存
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error("库存明细第" + i + "行库存为空");
                } else { // 非空修改库存总账
                    //  库存 <  出库件数
                    if (tWhgenle.getfQtyblc() < wbItem.getfQty()) {
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return AjaxResult.error("库存明细第" + i + "行库存不足");
                    }
                    // 更新库存总账
                    updateTWhgenlegData(wbItem, tWhgenle.getfId(), billsType);
                    if (StringUtils.isNull(tWarehouseBills.getfBsdate()) || StringUtils.isNull(wbItem.getfChargedate())) {
                        return AjaxResult.error("库存明细第" + i + "行请检查日期，操作终止");
                    }
                    long dateDay = DateUtils.getDateDay(tWarehouseBills.getfBsdate(), wbItem.getfChargedate());
                    if (StringUtils.isNull(tWarehouseBills.getfCorpid())) {
                        return AjaxResult.error("库存明细第" + i + "行请检查客户信息，操作终止");
                    }
                    /*long fCorpid = tWarehouseBills.getfCorpid();
                    TGoods tGoods = tGoodsMapper.selectTGoodsById(wbItem.getfGoodsid());
                    long fGoodsid = tGoods.getfTypeid();
                    long fBillingway = wbItem.getfBillingway();
                    long fQty = wbItem.getfQty();
                    // 计算仓储费明细
                    Map<String, Object> objectMap = tWarehouseAgreementService.getCarryingCost(fCorpid, fGoodsid, dateDay, fBillingway, fQty , 0L);
                    if (StringUtils.isNull(objectMap)) {
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return AjaxResult.error("库存明细第" + i + "行没有维护出库明细的仓储协议，操作终止");
                    }
                    Long feeId = (Long) objectMap.get("feeId");
                    BigDecimal amt = (BigDecimal) objectMap.get("amt");
                    TFees tFees = tFeesMapper.selectTFeesById(feeId);
                    if (StringUtils.isNotNull(tFees)) {
                        feesList.add(tFees);
                    }
                    TWarehousebillsfees fees = new TWarehousebillsfees();
                    fees.setfPid(fPid);
                    fees.setfFeeid(feeId);
                    fees.setfCorpid(tWarehouseBills.getfCorpid());
                    fees.setfFeeUnitid(fBillingway);
                    fees.setfQty(new BigDecimal(1));
                    fees.setfUnitprice(amt);
                    fees.setfAmount(amt);
                    fees.setfExrate(new BigDecimal(1));
                    fees.setfCurrency("RMB");
                    fees.setRemark(dateDay + "天" + tFees.getfName());
                    warehousebillsfees.add(fees);*/
                }
                wbItem.setfBillstatus(40L);
            } else if ("CKDB".equals(billsType)) { // 调拨查询
                if (StringUtils.isNull(tWhgenle)) { // 为空 提示没有库存
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error("库存明细第" + i + "行库存为空");
                } else { // 非空修改库存总账
                    if (tWhgenle.getfQtyblc() < wbItem.getfQty()) {  //  1、  库存 <  调拨件数  提示库存不足
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return AjaxResult.error("库存明细第" + i + "行库存不足");
                    } else {  // 2、 库存足够 先 进行出库操作
                        wbItem.setfWarehouselocid(warehouselocId);
                        updateTWhgenlegData(wbItem, tWhgenle.getfId(), "SJCK");
                    }
                    // 3、 进行入库操作 查询是否存在库存
                    wbItem.setfWarehouselocid(transferWarehouselocid); // 新库区
                    TWhgenleg tWhgenle1 = queryTWhgenleg(tWarehouseBills, wbItem);
                    if (StringUtils.isNull(tWhgenle1)) {   // 5、 不存在 进行新增库存
                        instalTWhgenleg(tWarehouseBills, wbItem, loginUser.getUser());
                    } else { // 4、 存在 进行跟新库存
                        updateTWhgenlegData(wbItem, tWhgenle1.getfId(), "SJRK");
                    }
                }
                wbItem.setfWarehouselocid(warehouselocId);
                wbItem.setfBillstatus(40L);
            } else if ("HQZY".equals(billsType)) { // 货转
                wbItem.setfBillstatus(6L);
                wbItem.setfChargedate(tWarehouseBills.getfChargedate());
                wbItem.setfBillingway(tWarehouseBills.getfBillingway());
                if (StringUtils.isNull(tWhgenle)) { // 为空 提示没有库存
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error("库存明细第" + i + "行库存为空");
                } else { // 非空修改库存总账
                    if (tWhgenle.getfQtyblc() < wbItem.getfQty()) {  //  1、  库存 <  调拨件数  提示库存不足
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return AjaxResult.error("库存明细第" + i + "行库存不足");
                    } else {  // 2、 库存足够 先 进行出库操作
                        updateTWhgenlegData(wbItem, tWhgenle.getfId(), "SJCK");
                    }
                    long corpId = tWarehouseBills.getfCorpid();
                    tWarehouseBills.setfCorpid(tWarehouseBills.getfTocorpid());
                    // 3、 进行入库操作 查询是否存在库存
                    TWhgenleg tWhgenle1 = queryTWhgenleg(tWarehouseBills, wbItem);
                    if (StringUtils.isNull(tWhgenle1)) {   // 5、 不存在 进行新增库存
                        instalTWhgenleg(tWarehouseBills, wbItem, loginUser.getUser());
                    } else { // 4、 存在 进行跟新库存
                        updateTWhgenlegData(wbItem, tWhgenle1.getfId(), "SJRK");
                    }
                    tWarehouseBills.setfCorpid(corpId);
                }
            }
            i++;
            int num = 0;
            wbItem.setfPid(fPid);
            wbItem.setfBilltype(billsType);
            wbItem.setfBillno(tWarehouseBills.getfBillno());
            wbItem.setfBsdate(tWarehouseBills.getfBsdate());
            if (StringUtils.isNotNull(wbItem.getfId())) {
                wbItem.setUpdateBy(loginUser.getUser().getUserName());
                wbItem.setUpdateTime(new Date());
                num = tWarehousebillsitemsMapper.updateTWarehousebillsitems(wbItem);
                if ("SJCK".equals(billsType)) {
                    // 添加状态log
                    insertTWarehousebillsLog(wbItem, 40L, loginUser);
                }
            } else {
                wbItem.setCreateTime(new Date());
                wbItem.setCreateBy(loginUser.getUsername());
                num = tWarehousebillsitemsMapper.insertTWarehousebillsitems(wbItem);
            }
            if (num <= 0) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error("库存明细更新失败");
            }
        }
        //  附件添加
        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);
            }
        }
        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 warehouseBills
     * @param warehousebillsitems
     * @param tEnclosure
     * @param tWarehousebillsfeesCr
     * @param tWarehousebillsfeesDr
     * @param loginUser
     * @param status
     * @param billtystatus
     * @return
     */
    @Override
    public AjaxResult waitWarehousing(String warehouseBills, String warehousebillsitems,
                                      String tEnclosure, String tWarehousebillsfeesCr, String tWarehousebillsfeesDr,
                                      LoginUser loginUser, Long status, String billtystatus) {
        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);
        if(status==20){
            tWarehouseBills.setfItemsStatus(2L);
        }else if(status==30){
            tWarehouseBills.setfItemsStatus(3L);
        }
        if (StringUtils.isNotNull(tWarehouseBills.getfId())) {
            tWarehouseBills.setUpdateBy(loginUser.getUser().getUserName());
            tWarehouseBills.setUpdateTime(new Date());
            tWarehouseBillsMapper.updateTWarehousebills(tWarehouseBills);
        }
        tEnclosureMapper.deleteByFPid(tWarehouseBills.getfId());
        tWarehousebillsfeesMapper.deleteByFPid(tWarehouseBills.getfId());
        JSONArray warehouseJSON = JSONArray.parseArray(warehousebillsitems);
        List<TWarehousebillsitems> warehousebillsitemsList = JSONObject.parseArray(warehouseJSON.toJSONString(), TWarehousebillsitems.class);
        for (TWarehousebillsitems item : warehousebillsitemsList) {
            // 生成流水号
            Date time = new Date();
            String serialNumber;
            if (item.getfBillstatus() < 30L) {
                if(StringUtils.isNull(item.getfSerialNumber())){
                    if ("RK".equals(billtystatus)) { // 生成 入库 流水号
                        serialNumber = billnoSerialServiceImpl.getSerialNumber("RK", time);
                        item.setfSerialNumber(serialNumber);
                    } else if ("CK".equals(billtystatus)) { //生成 出库 流水号
                        serialNumber = billnoSerialServiceImpl.getSerialNumber("CK", time);
                        item.setfSerialNumber(serialNumber);
                    } else if ("DB".equals(billtystatus)) { //生成 出库 流水号
                        serialNumber = billnoSerialServiceImpl.getSerialNumber("DB", time);
                        item.setfSerialNumber(serialNumber);
                    }
                }
               /* if ("RK".equals(billtystatus)) { // 生成 入库 流水号
                    serialNumber = billnoSerialServiceImpl.getSerialNumber("RK", time);
                    item.setfSerialNumber(serialNumber);
                } else if ("CK".equals(billtystatus)) { //生成 出库 流水号
                    serialNumber = billnoSerialServiceImpl.getSerialNumber("CK", time);
                    item.setfSerialNumber(serialNumber);
                } else if ("DB".equals(billtystatus)) { //生成 出库 流水号
                    serialNumber = billnoSerialServiceImpl.getSerialNumber("DB", time);
                    item.setfSerialNumber(serialNumber);
                }*/
                item.setfBillstatus(status);
                item.setUpdateTime(new Date());
                item.setUpdateBy(loginUser.getUser().getUserName());
                int num = tWarehousebillsitemsMapper.updateTWarehousebillsitems(item);
                // 添加状态log
                insertTWarehousebillsLog(item, status, loginUser);
                if (num <= 0) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error("更新库存明细失败");
                }
            }
        }
        //  附件添加
        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> mapList = tWarehousebillsitemsMapper.selectTWarehousebillsitemsList(tWarehousebillsitems);
        map.put("warehousebillsitems", mapList);
        return AjaxResult.success("成功", map);
    }

    /**
     * 生成计算仓储费信息
     *
     * @param warehouseBills
     * @param mapItem
     * @param loginUser
     * @return
     */
    public Map<String, Object> getWarehouseItems(TWarehouseBills warehouseBills, List<Map<String, Object>> mapItem, LoginUser loginUser) {
        Map<String, Object> map = new HashMap<>();
        long feeId = 0L;
        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;
            }
            Date fBsdate = (Date) item.get("fBsdate");
            long fCorpid = warehouseBills.getfCorpid();
            String fBilltype = (String) item.get("fBilltype");
            long fGoodsid = Long.parseLong((String) item.get("fTypeid"));
            long fId = Long.valueOf(String.valueOf(item.get("fId"))).longValue();
            // 累计计费天数
            long accumulatedDays = 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("fOriginalbilldate"));
                fBillingDays = fInventoryDays;
            } else if ("HQZY".equals(fBilltype)) {
                fInventoryDays = DateUtils.getDateDay(warehouseBills.getfBillingDeadline(), fBsdate);
            } else {
                fBillingDays = DateUtils.getDateDay(warehouseBills.getfBillingDeadline(), (Date) item.get("fChargedate"));
                fInventoryDays = DateUtils.getDateDay(warehouseBills.getfBillingDeadline(), (Date) item.get("fOriginalbilldate"));
            }
            /*if ("KCZZ".equals(fBilltype)) {
            } else {
                fInventoryDays = Long.valueOf(String.valueOf(item.get("fBillingDays")));
            }*/
            Long dictLabel = Long.valueOf(String.valueOf(item.get("fBillingway")));
            BigDecimal fQty = acquiredQuantity(item, dictLabel);
            if (fQty.equals(BigDecimal.ZERO)) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error("单号：" + item.get("fBillno") + ",业务日期:" + item.get("fBsdate") + "未找到计费单位，请确认");
            }
            // 计算仓储费明细
            Map<String, Object> objectMap = tWarehouseAgreementService.getCarryingCost(fCorpid, fGoodsid, fBillingDays, dictLabel, fQty, accumulatedDays);
            if (StringUtils.isNull(objectMap)) {
                map.put("error", "单号：" + item.get("fBillno") + ",业务日期:" + item.get("fBsdate") + "未找到仓储费协议，请确认");
                return map;
            }
            String mblno = "";
            if (StringUtils.isNotNull(item.get("fMblno"))) {
                mblno = item.get("fMblno").toString();
            }
            String remark = objectMap.get("remark").toString();
            feeId = Long.valueOf(String.valueOf(objectMap.get("feeId"))).longValue();
            BigDecimal amt = (BigDecimal) objectMap.get("amt");
            map.put("feeId", feeId);
            map.put("itemFeeId", objectMap.get("feeId"));
            sumAmt = sumAmt.add(amt).setScale(2, BigDecimal.ROUND_HALF_UP);
            TWarehousebillsfees fees = new TWarehousebillsfees();
            fees.setfFeeid(feeId);
            fees.setfDc("D");
            fees.setfAmt(amt);
            fees.setSrcId(fId);
            fees.setfMblno(mblno);
            fees.setRemark(remark);
            fees.setfFeeunitid(2L);
            fees.setfAmount(sumAmt);
            fees.setfBillstatus(2L);
            fees.setfCurrency("RMB");
            fees.setfBsdate(fBsdate);
            fees.setfBillingQty(fQty);
            fees.setfUnitprice(sumAmt);
            fees.setfBilltype(fBilltype);
            fees.setfBillingDays(fBillingDays);
            fees.setCreateTime(new Date());
            fees.setfQty(new BigDecimal(1));
            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"))).longValue());
            tWarehousebillsfeesMapper.insertTWarehousebillsfees(fees);
            itemsList.add(fees);
        }
        map.put("sumAmt", sumAmt);
        map.put("itemsList", itemsList);
        return map;
    }

    /**
     * 新增库存费计算
     *
     * @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("请选择客户信息");
        }
        long fPid = 0L;
        if (StringUtils.isNull(tWarehouseBills.getfId())) {
            // 生成流水号
            Date time = new Date();
            String billNo = billnoSerialServiceImpl.getSerialNumber("JSCCF", 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<>();
        BigDecimal bigDecimal = new BigDecimal(0);
        Map<String, Object> map = new HashMap<>();
        // 库存总账id
        long whgenlegFeeId = 0;
        // 计费单位
        long feeUnitid = 1;
        // 查询 出库 货转的库存明细
        List<Map<String, Object>> warehousebillsitemsList = tWarehousebillsitemsMapper.selectStorageFeeItemList(tWarehouseBills);
        if (warehousebillsitemsList.size() != 0) {
            Map<String, Object> mapItem = getWarehouseItems(tWarehouseBills, warehousebillsitemsList, loginUser);
            if (mapItem.containsKey("error")) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error((String) mapItem.get("error"));
            }
            itemsList = (List<TWarehousebillsfees>) mapItem.get("itemsList");
        }
        List<Map<String, Object>> tWhgenlegs = tWhgenlegMapper.selectStorageFeeItemList(tWarehouseBills);
        if (tWhgenlegs.size() != 0) {
            Map<String, Object> mapItem = getWarehouseItems(tWarehouseBills, tWhgenlegs, loginUser);
            if (mapItem.containsKey("error")) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return AjaxResult.error((String) mapItem.get("error"));
            }
            List<TWarehousebillsfees> itemList = (List<TWarehousebillsfees>) mapItem.get("itemsList");
            if (itemList.size() != 0) {
                for (TWarehousebillsfees ite : itemList) {
                    itemsList.add(ite);
                }
            }
        }
        TFees tFees = new TFees();
        tFees.setfStatus("2");
        tFees.setDelFlag("0");
        List<TFees> feesList = tFeesMapper.selectTFeesList(tFees);
        if (itemsList.size() <= 0) {
            return AjaxResult.error("未找到合适的库存明细");
        }
        map.put("feesList", feesList);
        map.put("warehouseBills", tWarehouseBills);
        map.put("warehouseItemList", itemsList);
        return AjaxResult.success(map);
    }

    /**
     * 仓储费计算提交以及暂存
     *
     * @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 = JSONArray.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 (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("JSCCF", 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.setfId(null);
            item.setSrcBillNo(tWarehousebills.getfBillno());
            item.setfPid(fPid);
            item.setfBillstatus(tWarehousebills.getfBillstatus());
            tWarehousebillsfeesMapper.insertTWarehousebillsfees(item);
        }
        if (StringUtils.isNotNull(warehouseFees) && !"[]".equals(warehouseFees)) {
            JSONArray feesJSON = JSONArray.parseArray(warehouseFees);
            List<TWarehousebillsfees> warehousebillsfeesList = JSONObject.parseArray(feesJSON.toJSONString(), TWarehousebillsfees.class);
            for (TWarehousebillsfees fees : warehousebillsfeesList) {
                fees.setfId(null);
                fees.setfPid(fPid);
                fees.setfDc("D");
                fees.setfBilltype("JSCCF");
                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(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");
                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 {
                AjaxResult ajaxResult = storageFeeFollow(fPid, 6L);
                String code = ajaxResult.get("code").toString();
//                Long code = Long.valueOf(String.valueOf(ajaxResult.get("code"))).longValue();
                if ("500".equals(code)) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                }
                return ajaxResult;
            }
        }
        return AjaxResult.success(tWarehousebills);
    }

    /**
     * 根据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<>();
        List<TWarehousebillsfees> feesList = new ArrayList<>();
        List<TWarehousebillsfees> itemsList = new ArrayList<>();
        TWarehousebillsfees warehousebillsfees = new TWarehousebillsfees();
        warehousebillsfees.setfPid(fId);
        List<TWarehousebillsfees> warehouseFeesList = tWarehousebillsfeesMapper.selectTWarehousebillsfeesList(warehousebillsfees);
        for (TWarehousebillsfees fees : warehouseFeesList) {
            if (StringUtils.isNotNull(fees.getSrcId())) {
                itemsList.add(fees);
            } else {
                feesList.add(fees);
            }
        }
        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);
    }

    /**
     * 根据不同计费单位获取不同 计算库存明细数量
     *
     * @param item      库存明细
     * @param dictLabel 计费单位
     * @return 结果
     */
    public BigDecimal acquiredQuantity(Map<String, Object> item, Long dictLabel) {
        BigDecimal fQty = new BigDecimal(0);
        // 件数
        long boxNum = 1;
        // 毛重
        long grossWeight = 2;
        // 净重
        long netWeight = 3;
        // 尺码
        long size = 4;
        // 统一
        long fixed = 5;
        if (dictLabel.equals(boxNum)) {
            fQty = new BigDecimal(((Number) item.get("fQty")).doubleValue());
            return fQty.setScale(2, BigDecimal.ROUND_HALF_UP);
        } else if (dictLabel.equals(grossWeight)) {
            fQty = new BigDecimal(((Number) item.get("fGrossweight")).doubleValue());
        } else if (dictLabel.equals(netWeight)) {
            fQty = new BigDecimal(((Number) item.get("fNetweight")).doubleValue());
        } else if (dictLabel.equals(size)) {
            fQty = new BigDecimal(((Number) item.get("fVolumn")).doubleValue());
        } else if (dictLabel.equals(fixed)) {
            fQty = new BigDecimal(1);
        }
        //return fQty.setScale(2, BigDecimal.ROUND_HALF_UP);
        // 结果值除以1000 保留两位
        BigDecimal divisor = new BigDecimal("1000");
        BigDecimal result = fQty.divide(divisor, 2, BigDecimal.ROUND_HALF_UP);
        return result;
    }

    // 入库 收费明细 校验
    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 int deleteTWarehousebillsByIds(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.deleteTWarehousebillsByIds(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 getWarehouseInStockBillsNo(TWarehouseBills tWarehouseBills) {

        return null;
    }

    @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);// 审核通过时间清空
        tWarehouseBillsMapper.updateTWarehousebills(tWarehousebills);
        tWarehousebillsfeesMapper.warehouseFeesFollowUpdate(tWarehousebills.getfId(), 2L, new Date());
        if ("JSCCF".equals(tWarehousebills.getfBilltype())) {
            List<TWarehousebillsfees> feesList = tWarehousebillsfeesMapper.selectWarehousebillsfeesByPId(fId);
            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());
                    int i = tWhgenlegMapper.updateTWhgenleg(whgenleg);
                    if (i <= 0) {
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return AjaxResult.error("更新库存费用状态失败，请联系管理员");
                    }
                } else {
                    TWarehousebillsitems billsItem = new TWarehousebillsitems();
                    billsItem.setfId(wareItem.getSrcId());
                    billsItem.setfBilltype(wareItem.getfBilltype());
                    if (!"SJCK".equals(wareItem.getfBilltype())) {
                        billsItem.setfChargedate(wareItem.getfBillingDeadline());
                        tWarehousebillsitemsMapper.updateTWarehousebillsitems(billsItem);
                    } else {
                        billsItem.setfChargedate(wareItem.getfChargedate());
                    }
                    tWarehousebillsitemsMapper.agreementApprovalRejected(billsItem);
                }
            }
        }
        return AjaxResult.success();
    }

    /**
     * 撤销入账
     *
     * @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 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); //撤销状态
        tWarehouseBillsMapper.updateTWarehousebills(tWarehousebills);
        tEnclosureMapper.deleteByFPid(tWarehousebills.getfId());
        tWarehousebillsfeesMapper.deleteByFPid(tWarehousebills.getfId());
        JSONArray warehouseJSON = JSONArray.parseArray(warehousebillsitems);
        List<TWarehousebillsitems> warehousebillsitemsList = JSONObject.parseArray(warehouseJSON.toJSONString(), TWarehousebillsitems.class);
        if (StringUtils.isNotEmpty(warehousebillsitemsList)) {
            int i = 1;
            for (TWarehousebillsitems wb : warehousebillsitemsList) {
                // 查询库存总账
                TWhgenleg tWhgenle = queryTWhgenleg(tWarehousebills, wb);
                if ("SJRKRevoke".equals(billsType)) { // 撤销 入库
                    if (wb.getfIsInventory().equals(0L)) {
                        if (StringUtils.isNotNull(tWhgenle) && (wb.getfQty() <= tWhgenle.getfQtyblc())) { // 非空 且 撤销数 <= 结余数
                            updateTWhgenlegData(wb, tWhgenle.getfId(), billsType);
                        } else { // 撤销数>结余数
                            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                            return AjaxResult.error("第" + i + "行撤销数大于库存结余数");
                        }
                    }
                    wb.setfBillstatus(10L);
                } else if ("SJCKRevoke".equals(billsType)) { // 撤销出库
                    if (StringUtils.isNotNull(tWhgenle)) { // 非空
                        updateTWhgenlegData(wb, tWhgenle.getfId(), billsType);
                    } else {
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return AjaxResult.error("第" + i + "行未查询到库存信息");
                    }
                    wb.setfBillstatus(10L);
                } else if ("CKDBRevoke".equals(billsType)) { // 调拨 撤销
                    Long warehouselocid = wb.getfWarehouselocid();// 原货仓库
                    Long transferWarehouselocid = wb.getfTransferWarehouselocid(); // 新仓库
                    //  1、新货权方撤销入库
                    // 查询库存总账
                    wb.setfWarehouselocid(transferWarehouselocid);
                    TWhgenleg tWhgenle1 = queryTWhgenleg(tWarehousebills, wb);
                    if (StringUtils.isNotNull(tWhgenle1) && (wb.getfQty() <= tWhgenle1.getfQtyblc())) {
                        updateTWhgenlegData(wb, tWhgenle1.getfId(), "SJRKRevoke");
                    } else {
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return AjaxResult.error("第" + i + "行撤销数大于库存结余数");
                    }
                    //  2、原货权方撤销出库
                    // 查询库存总账
                    wb.setfWarehouselocid(warehouselocid);
                    TWhgenleg tWhgenle2 = queryTWhgenleg(tWarehousebills, wb);
                    updateTWhgenlegData(wb, tWhgenle2.getfId(), "SJCKRevoke");
                    wb.setfBillstatus(10L);
                } else if ("HQZYRevoke".equals(billsType)) { // 货转撤销
                    Long fCorpid = tWarehousebills.getfCorpid();// 原货权方
                    Long fTocorpid = tWarehousebills.getfTocorpid(); // 新货权方
                    //  1、新货权方撤销入库
                    // 查询库存总账
                    tWarehousebills.setfCorpid(fTocorpid);
                    TWhgenleg tWhgenle1 = queryTWhgenleg(tWarehousebills, wb);
                    if (StringUtils.isNotNull(tWhgenle1) && (wb.getfQty() <= tWhgenle1.getfQtyblc())) {
                        updateTWhgenlegData(wb, tWhgenle1.getfId(), "SJRKRevoke");
                    } else {
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        return AjaxResult.error("第" + i + "行撤销数大于库存结余数");
                    }
                    //  2、原货权方撤销出库
                    // 查询库存总账
                    tWarehousebills.setfCorpid(fCorpid);
                    TWhgenleg tWhgenle2 = queryTWhgenleg(tWarehousebills, wb);
                    updateTWhgenlegData(wb, tWhgenle2.getfId(), "SJCKRevoke");
                    wb.setfBillstatus(1L);
                }
                i++;
                wb.setUpdateBy(loginUser.getUser().getUserName());
                wb.setUpdateTime(new Date());
                if (tWarehousebillsitemsMapper.updateTWarehousebillsitems(wb) <= 0) {
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    return AjaxResult.error("新增库存明细失败");
                }
            }
        }
        //  附件添加
        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);
            }
        }
        return AjaxResult.success();
    }

    /**
     * 添加 库存明细状态
     *
     * @param wbItem
     * @param status
     * @param loginUser
     */
    public void insertTWarehousebillsLog(TWarehousebillsitems wbItem, Long status, LoginUser loginUser) {
        // 添加状态log
        TWarehousebillsLog tWarehousebillsLog = new TWarehousebillsLog();
        tWarehousebillsLog.setfPid(wbItem.getfPid());
        tWarehousebillsLog.setfItmeid(wbItem.getfId());
        tWarehousebillsLog.setfItmestatus(status);
        tWarehousebillsLog.setCreateTime(new Date());
        tWarehousebillsLog.setCreateBy(loginUser.getUser().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, BigDecimal.ROUND_HALF_UP);
    }

    /**
     * 判断  是否允许 入库
     *
     * @param fId
     */
    public int calculation(Long fId, BigDecimal fGrossweight) {
        // 仓库库容
        TWarehouse tWarehouse = tWarehouseMapper.selectTWarehouseById(fId);
        // 毛重公斤转化为吨
        fGrossweight = fGrossweight.divide(new BigDecimal(1000), 0, BigDecimal.ROUND_HALF_UP);
        // 总账使用
        List<Map<String, Object>> whouseList = tWhgenlegMapper.selectWareHouseListWhouse(fId);
        if (whouseList != null && whouseList.size() > 0) {
            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;// 库容小于入库数
            }
        }
    }

}
