package com.unis.crk.business.kcgl.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.unis.crk.aop.SystemLog;
import com.unis.crk.business.kcgl.entity.DataKcglFcbgzDefault;
import com.unis.crk.business.kcgl.entity.DataKcglXckcDefault;
import com.unis.crk.business.kcgl.entity.FcbgzStore;
import com.unis.crk.business.kcgl.entity.Store;
import com.unis.crk.business.kcgl.entity.vo.DataKcglXckcDefaultVo;
import com.unis.crk.business.kcgl.mapper.DataKcglXckcDefaultMapper;
import com.unis.crk.business.kcgl.service.IDataKcglFcbgzDefaultService;
import com.unis.crk.business.kcgl.service.IDataKcglKcswDefaultService;
import com.unis.crk.business.kcgl.service.IDataKcglXckcDefaultService;
import com.unis.crk.common.service.IDeleteDataRecordService;
import com.unis.crk.enums.EditStatus;
import com.unis.crk.enums.StoreWorkType;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
 * <p>
 * 库存管理-形成库存表 服务实现类
 * </p>
 *
 * @author TangSong
 * @since 2021-10-11
 */
@Service
public class DataKcglXckcDefaultServiceImpl extends ServiceImpl<DataKcglXckcDefaultMapper, DataKcglXckcDefault> implements IDataKcglXckcDefaultService {

    @Resource
    private DataKcglXckcDefaultMapper dataKcglXckcDefaultMapper;
    @Autowired
    private IDataKcglFcbgzDefaultService dataKcglFcbgzDefaultService;
    @Autowired
    private IDataKcglKcswDefaultService dataKcglKcswDefaultService;
    @Autowired
    private IDeleteDataRecordService deleteDataRecordService;

    private static String RK_CPZ = "5"; // 入库称皮重环节编号
    private static String CK_CMZ = "11"; // 出入称毛重环节编号
    private static String QCKC = "qc"; // 期初库存

    private static String KCBD_XZBH = "kcbd_xzbh";	// 库存变动 性质变化
    //针对业务库存变动
    private static String KCBD_PY = "kcbd_py"; 	// 库存变动 盘盈
    private static String KCBD_PK = "kcbd_pk";	// 库存变动 盘亏
    private static String KCBD_PC = "kcbd_pc";	// 库存变动 平仓
    private static String KCBD_YC = "kcbd_yc";	// 库存变动 移仓
    /**
     * 按照条件查询库存管理-形成库存表信息
     * @param pageQuery
     * @throws Exception
     */
    @Override
    public IPage<Map<String,Object>> findPageVo(DataKcglXckcDefaultVo pageQuery){
        {
            //条形查询器
            QueryWrapper<DataKcglXckcDefault> queryWrapper = new QueryWrapper<>();
            if (StringUtils.isNotBlank(pageQuery.getBizNo())){
                queryWrapper.like("bizNo",pageQuery.getBizNo());
            }
            //分页相关
            Page<DataKcglXckcDefault> p =new Page<>(pageQuery.getPage(),pageQuery.getLimit());

            IPage<Map<String,Object>> page = dataKcglXckcDefaultMapper.selectMyMapsPage(p,queryWrapper);
            return page;
        }
    }

    @SystemLog(module = "原粮库存", methods = "库存",uploadName = "yuliang.kcbd")
    public boolean makeStockDetail(String dataId, String unitId, String loginName,
                                   EditStatus editStatus, StoreWorkType workType) {
        if (StoreWorkType.InStore == workType
                || workType == StoreWorkType.SiampleStore) {
            return false;
        }
        boolean rtn = false;


        try {

            if (editStatus == EditStatus.Deleted) { // 删除库存
                String reverseDataId = new StringBuilder(dataId).reverse().toString();
                if(workType == StoreWorkType.KcbdYc) {  //库存变动移仓
                    boolean a1 = deleteStockDetail(unitId, dataId, StoreWorkType.Out,editStatus); //A移出
                    boolean b2 = deleteStockDetail(unitId, reverseDataId, StoreWorkType.In,editStatus); //B移入
                    return a1 && b2;
                }
                if(workType == StoreWorkType.Cpljgdj) { //成品粮加工登记
                    boolean yl = deleteStockDetail(unitId, dataId, StoreWorkType.Out,editStatus); //A移出
                    boolean cpl = deleteStockDetail(unitId, reverseDataId, StoreWorkType.In,editStatus); //B移入
                    return yl && cpl;
                }
                if( workType == StoreWorkType.KcbdXz) {  //性质变化
                    boolean a1 = deleteStockDetail_xzbd(unitId, dataId, StoreWorkType.Out,editStatus); //A移出
                    boolean b2 = deleteStockDetail(unitId, reverseDataId, StoreWorkType.In,editStatus); //B移入
                    return a1 && b2;
                }
                return deleteStockDetail(unitId, dataId, workType,editStatus);
            } else if (editStatus == EditStatus.New
                    || editStatus == EditStatus.Modified) { // 新增或修改
                if (workType == StoreWorkType.In) //入库
                    rtn = makeStockDetailOfIn(dataId, unitId, loginName, editStatus);
                else if (workType == StoreWorkType.Out) //出库
                    rtn = makeStockDetailOfOut(dataId, unitId, loginName,editStatus);
                else if (workType == StoreWorkType.QCKC) //期初
                    rtn = makeStockDetailOfQckc(dataId, unitId, loginName,editStatus);
                else if (workType == StoreWorkType.KcbdRk || workType == StoreWorkType.KcbdCk || workType == StoreWorkType.KcbdYc || workType == StoreWorkType.KcbdXz ||  workType == StoreWorkType.KcbdPc)	// 库存变动
                    rtn = makeStockDetailOfKcbd(dataId, unitId, loginName, editStatus, workType);

            }else {
                return true;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return false;
        }
        return rtn;
    }

    @Override
    public IPage<Map<String, Object>> findPageBgtz(DataKcglXckcDefaultVo pageQuery) {
        QueryWrapper<DataKcglXckcDefault> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("xc.UnitID",pageQuery.getUnitId());
        if(StringUtils.isNotBlank(pageQuery.getCh())){
            queryWrapper.eq("fc.ch",pageQuery.getCh());
        }
        if(StringUtils.isNotBlank(pageQuery.getHwh())){
            queryWrapper.eq("fc.hwh",pageQuery.getCh());
        }
        if(StringUtils.isNotBlank(pageQuery.getBizNo())){
            queryWrapper.like("xc.bizno",pageQuery.getBizNo());
        }
        if (StringUtils.isNotBlank(pageQuery.getYwsjStart()) && StringUtils.isNotBlank(pageQuery.getYwsjEnd())){
            queryWrapper.apply(" DATE_FORMAT(ifnull(fc.rq,NOW()),'%Y-%m-%d') >=  '"+pageQuery.getYwsjStart()+"' AND DATE_FORMAT(ifnull(fc.rq,NOW()),'%Y-%m-%d') <= '"+pageQuery.getYwsjEnd()+" 23:59:59'");
        }
        queryWrapper.orderByDesc("fc.rq");
        Page<DataKcglXckcDefault> p =new Page<>(pageQuery.getPage(),pageQuery.getLimit());
        IPage<Map<String, Object>> pageBgtz = dataKcglXckcDefaultMapper.findPageBgtz(p, queryWrapper);
        List<Map<String, Object>> records = pageBgtz.getRecords();
        for (Map<String, Object> s:records
        ) {
            String cazylx = s.get("cazylx").toString();
            if("1".equals(cazylx)){
                s.put("cazylx","入仓");
            }else if("2".equals(cazylx)){
                s.put("cazylx","仓内存储");
            }else if("3".equals(cazylx)){
                s.put("cazylx","出仓");
            }else if("4".equals(cazylx)){
                s.put("cazylx","简易存储");
            }else if("5".equals(cazylx)){
                s.put("cazylx","期初库存");
            }else if("10".equals(cazylx)){
                s.put("cazylx","性质变化");
            }else if("12".equals(cazylx)){
                s.put("cazylx","库存变动入库");
            }else if("13".equals(cazylx)){
                s.put("cazylx","库存变动出库");
            }else if("14".equals(cazylx)){
                s.put("cazylx","库存变动损益(移仓操作)");
            }else if("15".equals(cazylx)){
                s.put("cazylx","库存变动性质变化");
            }else if("16".equals(cazylx)){
                s.put("cazylx","库存变动平仓");
            }else if("17".equals(cazylx)){
                s.put("cazylx","成品粮加工登记");
            }
        }
        return pageBgtz;
    }

    /**
     *    创建库存变动保存时 仓库明细 业务
     * @author hzq
     * 2018-10-29
     * @param dataId      期初始库存数据id
     * @param unitId 单位ID
     * @param loginName 登陆人
     * @return true:创建成功 false:创建失败
     */
    private boolean makeStockDetailOfKcbd(String dataId, String unitId, String loginName, EditStatus editStatus, StoreWorkType workType) throws Exception {
        // 形成库存中，原粮dataId与成品粮dataId是反转的
        String reverseDataId = new StringBuilder(dataId).reverse().toString();
        // 检验项 先空着
        String flowName = "noname";
        //得到原始分库保管账信息
        FcbgzStore fcbgzStore = getFcStoreInfo(dataId, editStatus);
        FcbgzStore fcbgzStore_1 = getFcStoreInfo(reverseDataId, editStatus);
        if (editStatus == EditStatus.Modified) { // 修改
            // 删除原来的库存明细
            if (workType == StoreWorkType.KcbdRk) { //调增
                deleteStockDetail(unitId, dataId, StoreWorkType.In);
            }else if (workType == StoreWorkType.KcbdCk || workType == StoreWorkType.KcbdPc) { //调减 平仓损益（调减）
                deleteStockDetail(unitId, dataId, StoreWorkType.Out);
            }else if (workType == StoreWorkType.KcbdYc || workType == StoreWorkType.KcbdXz) { //移仓,性质变化操作，A 出 B入
                deleteStockDetail(unitId, dataId, StoreWorkType.Out);
                deleteStockDetail(unitId, reverseDataId, StoreWorkType.In);
            }
        }

        // 库存变动的变动方式
        String type = "";
        StoreWorkType cazylx = null;

        if(workType == StoreWorkType.KcbdRk) {
            type = KCBD_PY;
            cazylx = StoreWorkType.In;
        } else if(workType == StoreWorkType.KcbdCk) {
            type = KCBD_PK;
            cazylx = StoreWorkType.Out;
        }else if(workType == StoreWorkType.KcbdPc) {
            type = KCBD_PC;
            cazylx = StoreWorkType.Out;
        } else if(workType == StoreWorkType.KcbdYc) {
            type = KCBD_YC;
            cazylx = StoreWorkType.Out;
        }else if(workType == StoreWorkType.KcbdXz ) {
            type = KCBD_XZBH;
            cazylx = StoreWorkType.Out;
        }
        // 生成库存明细
        int i = dataKcglXckcDefaultMapper.addKcbdStock(dataId, loginName,
                flowName, cazylx.value(), type);
        if (i != 1) //未成功写入一条数据
            return false;

        // 获取库存信息
        double stockNum = 0;
        Store store = getStoreInfo(dataId);
//        double stockNum = store.getStoreNum();
        if(workType == StoreWorkType.KcbdRk) {
            stockNum = store.getInNum();
        } else if(workType == StoreWorkType.KcbdCk || workType == StoreWorkType.KcbdPc) {
            stockNum = -store.getOutNum();
        } else if(workType == StoreWorkType.KcbdYc) {
            stockNum = -store.getOutNum();
        }else if(workType == StoreWorkType.KcbdXz) {
            stockNum = -store.getOutNum();
        }
        // 生成分仓保管账
        boolean boolean1 =  dataKcglFcbgzDefaultService.changeFCBGZ(loginName, unitId, dataId, store,fcbgzStore,"");
        if (!boolean1) {
            return boolean1;
        }
        // 实物库存
        boolean1 =  dataKcglKcswDefaultService.changeKCSW(unitId,  dataId, store,fcbgzStore, stockNum, false);
        if (!boolean1) {
            return boolean1;
        }
        if(workType == StoreWorkType.KcbdYc) { // B 入库数据
            // 生成库存明细
//            sql = String.format(SqpMapUtil.getSql("ADD_IN_STOCK_KCBD_CF2_YW"), reverseDataId, loginName,
//                    flowName, StoreWorkType.In, type, dataId);
//            if (!this.executeUpdate(sql))
//                return false;
            // 生成库存明细
            i = dataKcglXckcDefaultMapper.addKcbdYcStock(reverseDataId,dataId, loginName,
                    flowName, StoreWorkType.In.value(), type);
            if (i != 1) //未成功写入一条数据
                return false;
            Store iNStore = getStoreInfo(reverseDataId);
            double iStockNum = iNStore.getInNum();

            // 生成分仓保管账
            boolean1 = dataKcglFcbgzDefaultService.changeFCBGZ(loginName, unitId, reverseDataId, iNStore,fcbgzStore_1,"");
            if (!boolean1) {
                return boolean1;
            }
            // 实物库存
            boolean1 = dataKcglKcswDefaultService.changeKCSW(unitId, reverseDataId, iNStore, fcbgzStore_1,iStockNum, false);
            if (!boolean1) {
                return boolean1;
            }
        }
        if(workType == StoreWorkType.KcbdXz) { // B 发生变动后的性质
            // 生成库存明细
//            sql = String.format(SqpMapUtil.getSql("ADD_IN_STOCK_KCBD_XZBF_YW"), reverseDataId, loginName,
//                    flowName, StoreWorkType.In, type, dataId);
//            if (!this.executeUpdate(sql))
//                return false;
            i = dataKcglXckcDefaultMapper.addKcbdXzbhStock(reverseDataId,dataId, loginName,
                    flowName, StoreWorkType.In.value(), type);
            if (i != 1) //未成功写入一条数据
                return false;
            Store iNStore = getStoreInfo(reverseDataId);
            double iStockNum = iNStore.getInNum();

            // 生成分仓保管账
            boolean1 = dataKcglFcbgzDefaultService.changeFCBGZ(loginName, unitId, reverseDataId, iNStore,fcbgzStore_1,"");
            if (!boolean1) {
                return boolean1;
            }
            // 实物库存
            boolean1 =  dataKcglKcswDefaultService.changeKCSW(unitId, reverseDataId, iNStore, fcbgzStore_1,iStockNum, false);
            if (!boolean1) {
                return boolean1;
            }
        }
        return  true;
    }
    /**
     * 创建期初库存保存时 仓库明细
     * @author ts
     * 2018-05-11
     * @param dataId
     *   期初始库存数据id
     * @param unitId
     *          单位ID
     * @param loginName
     *          登陆人
     * @return true:创建成功 false:创建失败
     */
    private boolean makeStockDetailOfQckc(String dataId, String unitId, String loginName, EditStatus editStatus) throws Exception {

        String flowName = "noname";

        // 查出分库保管账信息，如果是新增，则不存在

        FcbgzStore fcbgzStore = getFcStoreInfo(dataId, editStatus);
        if (editStatus == EditStatus.Modified) { // 修改
            // 删除原来的库存明细
            deleteStockDetail(unitId, dataId,StoreWorkType.QCKC,editStatus);
        }
        int i = dataKcglXckcDefaultMapper.addQckcStock(dataId, loginName,
                flowName, StoreWorkType.QCKC.value(), QCKC);
        if (i != 1) //未成功写入一条数据
            return false;

        //得到形成库存与库存相关信息
        Store store = getStoreInfo(dataId);

        // 生成分仓保管账 ts 2018-05-11
        Boolean boolean1  = dataKcglFcbgzDefaultService.changeFCBGZ(loginName, unitId, dataId, store,fcbgzStore,"");
        if (!boolean1) {
            return boolean1;
        }
        //分库保管账已处理完毕
        fcbgzStore.setSaveFcbgz(true);
        // 实物库存
        boolean1 = dataKcglKcswDefaultService.changeKCSW(unitId,  dataId, store,fcbgzStore, store.getInNum(), false);
        if (!boolean1) {
            return boolean1;
        }
        //修改时间
        return dataKcglKcswDefaultService.updateKcswRcsj(unitId, dataId, store, StoreWorkType.QCKC);
    }
    /**
     * 创建入仓库存明细
     *
     * @param dataId
     *          入库称皮重数据id
     * @param unitId
     *          单位ID
     * @param loginName
     *          登陆人
     * @return true:创建成功 false:创建失败
     */
    @SuppressWarnings("unchecked")
    private boolean makeStockDetailOfIn(String dataId, String unitId,
                                        String loginName, EditStatus editStatus) throws Exception  {

        // 获取扣价比例和,无此计算，默认不扣价
        String sum = "0";
        String flowName = "noname";

        // 查出分库保管账信息，如果是新增，则不存在

        FcbgzStore fcbgzStore = getFcStoreInfo(dataId, editStatus);
        if (editStatus == EditStatus.Modified) { // 修改
            // 删除原来的库存明细
            deleteStockDetail(unitId, dataId,StoreWorkType.In,editStatus);
        }
        // 生成库存明细
//        sql = String.format(SqpMapUtil.getSql("ADD_IN_STOCK"), dataId, loginName,
//                sum, flowName, StoreWorkType.In.value(), RK_CPZ, dataId);
        int i = dataKcglXckcDefaultMapper.addInStock(dataId, loginName,
                sum, flowName, StoreWorkType.In.value(), RK_CPZ);
        if (i != 1) //未成功写入一条数据
            return false;

        //得到形成库存与库存相关信息
        Store store = getStoreInfo(dataId);
        // 生成库存明细子表 不生存库存明细 Ts 2021-05-08
//		sql = String.format(SqpMapUtil.getSql("ADD_IN_STOCK_LIST"), unitId,
//				loginName, dataId, dataId);
//		if (!this.executeUpdate(sql))
//			return false;

        // 生成分仓保管账 ts 2018-05-11
        Boolean boolean1 = true;
        boolean1 = dataKcglFcbgzDefaultService.changeFCBGZ(loginName, unitId, dataId, store,fcbgzStore,"");
        if (!boolean1) {
            return boolean1;
        }
        //分库保管账已处理完毕
        fcbgzStore.setSaveFcbgz(true);
        // 实物库存
        boolean1 = dataKcglKcswDefaultService.changeKCSW(unitId,  dataId, store,fcbgzStore, store.getInNum(), false);
        if (!boolean1) {
            return boolean1;
        }
        //修改时间
        return dataKcglKcswDefaultService.updateKcswRcsj(unitId, dataId, store, StoreWorkType.In);
    }

    /**
     * 创建出库库存明细
     *
     * @param dataId
     *          出库称毛重数据id
     * @param unitId
     *          单位ID
     * @param loginName
     *          登陆人
     * @return true:创建成功 false:创建失败
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    private boolean makeStockDetailOfOut(String dataId, String unitId,
                                         String loginName, EditStatus editStatus) throws Exception {
        String flowName = "noname";
        String sql;
        // 查出分库保管账信息，如果是新增，则不存在

        FcbgzStore fcbgzStore = getFcStoreInfo(dataId, editStatus);
        if (editStatus == EditStatus.Modified) { // 修改
            // 删除原来的库存明细
            deleteStockDetail(unitId, dataId, StoreWorkType.Out);
        }

        // 生成库存明细
//        sql = String.format(SqpMapUtil.getSql("ADD_OUT_STOCK"), dataId, loginName,
//                flowName, StoreWorkType.Out.value(), CK_CMZ, dataId);
//        if (!this.executeUpdate(sql))
        int i = dataKcglXckcDefaultMapper.addOutStock(dataId, loginName,
                flowName, StoreWorkType.Out.value(), CK_CMZ);
        if (i != 1) //未成功写入一条数据
            return false;

        //得到形成库存与库存相关信息
        Store store = getStoreInfo(dataId);

        /// 生成分仓保管账 ts 2018-05-11
        Boolean boolean1  = dataKcglFcbgzDefaultService.changeFCBGZ(loginName, unitId, dataId, store,fcbgzStore,"");
        if (!boolean1) {
            return false;
        }
        //分库保管账已处理完毕
        fcbgzStore.setSaveFcbgz(true);
        // 实物库存
        boolean1 = dataKcglKcswDefaultService.changeKCSW(unitId,  dataId, store, fcbgzStore,-store.getOutNum(), false);
        return boolean1;
    }
    /**
     * 删除库存明细，库存明细的子表通过数据库外键级联删除
     *
     * @param dataId
     *          入库称皮重/出库称毛重id
     * @return true:删除成功 false:删除失败
     * @throws Exception
     */
    @SystemLog(module = "原粮库存", methods = "删除",uploadName = "yuliang.kcbd")
    private boolean deleteStockDetail(String unitId, String dataId,
                                      StoreWorkType workType,EditStatus...editStatus) throws Exception {
        // 查询出要删除的库存信息
        Store store = getStoreInfo(dataId);
        FcbgzStore fcbgzStore = getFcStoreInfo(dataId, editStatus);
        //处理形成分库保管账与库存实物
        if (!deductStore(unitId, dataId, workType, store,fcbgzStore,editStatus)) {
            return false;
        }
        // 删除库存明细
//        String sql = SqpMapUtil.getSql("DELETE_STOCK");
        if (!super.removeById(dataId)) {
            return false;
        }
        deleteDataRecordService.saveXckc(dataId,unitId,new Date());
        // 冲抵库存
        return true;
    }
    /**
     * 删除库存明细，库存明细的子表通过数据库外键级联删除
     *
     * @param dataId
     *          入库称皮重/出库称毛重id
     * @return true:删除成功 false:删除失败
     * @throws Exception
     */
    private boolean deleteStockDetail_xzbd(String unitId, String dataId,
                                           StoreWorkType workType,EditStatus...editStatus) throws Exception {
        // 查询出要删除的库存信息
        Store store = getStoreInfo(dataId);
        FcbgzStore fcbgzStore = getFcStoreInfo(dataId, editStatus);
        // 冲抵库存
        boolean flag =  deductStore(unitId, dataId, workType, store,fcbgzStore,editStatus);
        if (!flag) {
            return false;
        }
        // 删除库存明细
        if (!super.removeById(dataId)) {
            return false;
        }

        //删除形成库存
        return true;
    }
    /**
     * 冲抵库存
     * 修改与删除数量时，要将原来的形成库存删除，修改时会新增加一条形成库存
     * 所以要 修改与删除时，都进行删除操作
     * 分仓保管账  进行物理删除
     * 实物库存  则是通过查询五个口径得到相应数据进行修改，在实物库存为0时，删除这条数据
     * @param dataId
     *          入库称皮重/出库称毛重id
     * @param workType
     *          作业方式
     * @param store
     *          库存对象
     * @return
     * @throws Exception
     */
    @SystemLog(module = "原粮库存", methods = "删除",uploadName = "yuliang.kcbd")
    private boolean deductStore(String unitId, String dataId,
                                StoreWorkType workType, Store store,FcbgzStore fcbgzStore,EditStatus...editStatus) throws Exception {

        if (editStatus.length == 1 && editStatus[0] == EditStatus.Deleted) {
//            String sql = " SELECT "+FunUtils.fn_ifnull()+"(srsl,0) as \"srsl\","+FunUtils.fn_ifnull()+"(zcsl,0) as \"zcsl\","+FunUtils.fn_ifnull()+"(zcsl-srsl,0) as \"sl\","+FunUtils.fn_FormatDate(FunUtils.DATE_FORMAT_LONG, "rq")+" as \"rq\" FROM data_kcgl_fcbgz_default where DataID = '"+dataId+"'";
            DataKcglFcbgzDefault dataKcglFcbgzDefault  = dataKcglFcbgzDefaultService.getById(dataId);
            if (dataKcglFcbgzDefault != null ) { //表示是修改操作
                //将此条数据ModifyDate之后的数据进行kcsl的修改
                String lkbm = store.getLkbm(); //粮库编码
                String ch =  store.getCf(); //仓房
                String hwh = store.getHwh(); //货位
                String pz = store.getPz();//粮食品种
                String lsxz = store.getLsxz();//粮食性质
                Double sl = dataKcglFcbgzDefault.getZcsl()-dataKcglFcbgzDefault.getSrsl();
                Double srsl = dataKcglFcbgzDefault.getSrsl();
                Double zcsl = dataKcglFcbgzDefault.getZcsl();
                String date =  DateUtil.format(dataKcglFcbgzDefault.getRq(),"yyyy-MM-dd HH:mm:ss");
//                String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(dataKcglFcbgzDefault.getRq());

                //在删除分库保管账之前，先将修改，删除数据之后的分库保管账数据，kcsl修改，保证业务的正常性
//                sql = "update  data_kcgl_fcbgz_default  set kcsl =kcsl+(%s),ljzcsl =ljzcsl-(%s),ljsrsl =ljsrsl-(%s)	WHERE unitId='%s' AND ifnull(lkbm,'') = '%s' AND ifnull(ch,'')='%s' AND ifnull(hwh,'')='%s' AND ifnull(pz,'')='%s' AND ifnull(hwxz,'')='%s' and rq >= '%s'   AND DataID != '%s' ";
//                sql = "update  data_kcgl_fcbgz_default  set kcsl =kcsl+(${sl}),ljzcsl =ljzcsl-(${zcsl}),ljsrsl =ljsrsl-(${srsl})	WHERE unitId=#{unitId}  AND ifnull(ch,'')=#{ch} AND ifnull(hwh,'')=#{hwh} AND ifnull(pz,'')=#{pz} AND ifnull(hwxz,'')=#{xz} and rq >= #{rq}   AND DataID != #{dataId} ";
//                sql = String.format(sql,sl,zcsl,srsl, unitId,
//                        ch, hwh, pz, lsxz,date,dataId);
                if (!dataKcglFcbgzDefaultService.updateFcbgzByWrapper(sl,zcsl,srsl, unitId,
                        ch, hwh, pz, lsxz,date,dataId))
                    return false;
            }
        }
        //删除分仓保管账
//        String sql = String.format(SqpMapUtil.getSql("DELETE_FCBGZ"),  dataId);
        if (!dataKcglFcbgzDefaultService.removeById(dataId))
            return false;
        //TODO 删除仓库保管账
        deleteDataRecordService.saveFcbgz(dataId,unitId,new Date());
        boolean flag = true;
        if (workType == StoreWorkType.In
                || workType == StoreWorkType.HcIn
                || workType == StoreWorkType.QCKC
                || workType == StoreWorkType.KcbdRk // 库存变动入库
        ) { //入库 火车入库 或者期初库存 都是数量增加 原理一致
            store.setInNum(-store.getInNum());  //将入库的值减上
            store.setOutNum(0.0);
            // 实物库存
            flag= dataKcglKcswDefaultService.changeKCSW(unitId,  dataId, store, fcbgzStore,store.getInNum(), false);
            if (!flag) {
                return flag;
            }
            if (editStatus != null && editStatus.length == 1) {
                if (editStatus[0] == EditStatus.Deleted) { //仅删除时
                    return dataKcglKcswDefaultService.updateKcswRcsj(unitId, dataId, store, workType);
                }
            }
        } else { //出库
            store.setInNum(0.0);
            store.setOutNum(-store.getOutNum());  //将出库的值加上
            // 实物库存
            flag= dataKcglKcswDefaultService.changeKCSW(unitId,  dataId, store,fcbgzStore, -store.getOutNum(), false);
        }
        return flag;
        //修改时间
    }

    /**
     * 获取库存信息
     *
     * @param dataId
     *          库存明细id
     * @return 库存对象
     */
    @SuppressWarnings("unchecked")
    private Store getStoreInfo(String dataId) {
        Store store = new Store();

        // 查询当前出入库数量等信息
//        String sql = String.format(SqpMapUtil.getSql("QUERY_STOCK_DETAIL"), dataId);
//        List<Map<String, Object>> list = dataKcglKcswDefaultService.queryStockDetail(dataId);
        DataKcglXckcDefault dataKcglXckcDefault = super.getById(dataId);
        if (dataKcglXckcDefault != null) {
            store.setWjh(dataKcglXckcDefault.getKybgh());
            store.setBizNo(dataKcglXckcDefault.getBizno());
            store.setCf(dataKcglXckcDefault.getSjcf());
            store.setHwh(dataKcglXckcDefault.getSjhw());

            store.setLkbm(dataKcglXckcDefault.getLkbh());
            store.setLsxz(dataKcglXckcDefault.getHwxz());
            store.setPz(dataKcglXckcDefault.getPz());
            String cazylx = dataKcglXckcDefault.getYwlx();
            Double inNum = 0.0;
            Double outNum = 0.0;
            Double inRealNum= new Double(0.0); // 入库实际数量
            Double outRealNum= new Double(0.0); // 出库实际数量
            if ("1".equals(cazylx) || "5".equals(cazylx)){
                inNum = dataKcglXckcDefault.getXxklhjz();
                inRealNum = dataKcglXckcDefault.getSjsl();
            }else if ("3".equals(cazylx) || "11".equals(cazylx) ){
                outNum = dataKcglXckcDefault.getXxklhjz();
                outRealNum = dataKcglXckcDefault.getSjsl();
            }
            store.setInNum(inNum);
            store.setOutNum(outNum);
            store.setInRealNum(inRealNum);
            store.setOutRealNum(outRealNum);
            // 根据查询到的库存明细查询在最近一次出入库的粮库编码，仓房、货位号、品种、粮食性质相同的粮食的库存数量
            List<Map<String, Object>>  list = dataKcglKcswDefaultService.queryStockSum(dataKcglXckcDefault.getUnitID(),store.getCf(),
                    store.getHwh(), store.getPz(), store.getLsxz());
            if (list.size() > 0) {
                store.setStoreNum(Double.parseDouble(String.valueOf(list.get(0).get(
                        "kcsl"))));
                store.setStoreRealNum(Double.parseDouble(String.valueOf(list.get(0).get(
                        "kcsjsl"))));
            }
        }


        return store;
    }
    /**
     * 获取分库保管账信息
     *
     * @param dataId
     *          库存明细id
     * @return 库存对象
     */
    @SuppressWarnings("unchecked")
    private FcbgzStore getFcStoreInfo(String dataId,EditStatus...editStatus) {
        FcbgzStore fcbgzStore = new FcbgzStore();
//        fcbgzStore.setFcbgzKcsl(0.0);
//        fcbgzStore.setFcbgzSrsl(0.0);
//        fcbgzStore.setFcbgzZcsl(0.0);

        // 查询当前出入库数量等信息
//        String sql = String.format(SqpMapUtil.getSql("QUERY_FCBGZ_BYID"), FunUtils.DATE_FORMAT_LONG,dataId);
        List<Map<String, Object>> list = dataKcglFcbgzDefaultService.queryFcbgzByid(dataId);
        if (list.size() > 0) {
            fcbgzStore.setEditStatus(EditStatus.Modified); //设置为修改
            //查询分库保管账中的信息
            fcbgzStore.setFcbgzKcsl(Double.parseDouble(String.valueOf(list.get(0).get(
                    "kcsl"))));
            fcbgzStore.setFcbgzSrsl(Double.parseDouble(String.valueOf(list.get(0).get(
                    "srsl"))));
            fcbgzStore.setFcbgzZcsl(Double.parseDouble(String.valueOf(list.get(0).get(
                    "zcsl"))));
            fcbgzStore.setFcbgzKcsjsl(Double.parseDouble(String.valueOf(list.get(0).get(
                    "kcsjsl"))));
            fcbgzStore.setFcbgzSrsjsl(Double.parseDouble(String.valueOf(list.get(0).get(
                    "srsjsl"))));
            fcbgzStore.setFcbgzZcsjsl(Double.parseDouble(String.valueOf(list.get(0).get(
                    "zcsjsl"))));
            fcbgzStore.setFcbgzLjsrsl(Double.parseDouble(String.valueOf(list.get(0).get(
                    "ljsrsl"))));
            fcbgzStore.setFcbgzLjzcsl(Double.parseDouble(String.valueOf(list.get(0).get(
                    "ljzcsl"))));
            fcbgzStore.setFcbgzLjsrsjsl(Double.parseDouble(String.valueOf(list.get(0).get(
                    "ljsrsjsl"))));
            fcbgzStore.setFcbgzLjzcsjsl(Double.parseDouble(String.valueOf(list.get(0).get(
                    "ljzcsjsl"))));
            fcbgzStore.setFcbgzRq(String.valueOf(list.get(0).get(
                    "rq")));
        }
        if (editStatus.length == 1 ) {
            fcbgzStore.setEditStatus(editStatus[0]);
        }

        return fcbgzStore;
    }
}
