package com.unis.crk.cplbusiness.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import com.alibaba.fastjson.JSON;
import com.unis.crk.aop.SystemLog;
import com.unis.crk.common.service.IDeleteDataRecordService;
import com.unis.crk.cplbusiness.entity.*;
import com.unis.crk.cplbusiness.mapper.DataKcglCplxckcDefaultMapper;
import com.unis.crk.cplbusiness.service.IDataKcglCplfcbgzDefaultService;
import com.unis.crk.cplbusiness.service.IDataKcglCplkcswDefaultService;
import com.unis.crk.cplbusiness.service.IDataKcglCplxckcDefaultService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.unis.crk.enums.EditStatus;
import com.unis.crk.enums.StoreWorkType;
import com.unis.crk.utils.ResultUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import com.unis.crk.cplbusiness.entity.vo.DataKcglCplxckcDefaultVo;

/**
 * <p>
 * 成品粮形成库存 服务实现类
 * </p>
 *
 * @author TangSong
 * @since 2022-03-21
 */
@Service
public class DataKcglCplxckcDefaultServiceImpl extends ServiceImpl<DataKcglCplxckcDefaultMapper, DataKcglCplxckcDefault> implements IDataKcglCplxckcDefaultService {

    @Resource
    private DataKcglCplxckcDefaultMapper dataKcglCplxckcDefaultMapper;
    @Autowired
    private IDataKcglCplfcbgzDefaultService dataKcglCplfcbgzDefaultService;
    @Autowired
    private IDataKcglCplkcswDefaultService dataKcglCplkcswDefaultService;
    @Autowired
    private IDeleteDataRecordService deleteDataRecordService;

    private static String CPL_RK= "cpl_rk"; // 成品粮入库环节编号
    private static String CPL_CK = "cpl_ck"; // 成品粮出库环节编号
    private static String CPL_QCKC = "cpl_qc"; // 成品粮期初库存

    private static String CPL_KCBD_YC = "cpl_kcbd_yc";	// 成品粮库存变动 移仓
    private static String CPL_KCBD_XZBH = "cpl_kcbd_xzbh";	// 成品粮库存变动 性质变化
    //针对业务库存变动
    private static String CPL_KCBD_RK = "cpl_kcbd_rk"; 	// 成品粮库存变动 入库
    private static String CPL_KCBD_CK = "cpl_kcbd_ck";	// 成品粮库存变动 出库
    private static String CPL_KCBD_PC = "cpl_kcbd_pc";	// 库存变动 平仓
    private static String CPL_KCBD_SY = "cpl_kcbd_sy";	// 成品粮库存变动 移仓
    private static String CPL_KCBD_CFRK = "cpl_kcbd_cfrk";	// 成品粮库存变动 商品拆分入库
    private static String CPL_KCBD_CFCK = "cpl_kcbd_cfck";	// 成品粮库存变动 商品拆分出库
    private static String CPL_KCBD_ZHRK = "cpl_kcbd_zhrk";	// 成品粮库存变动 商品拆分入库
    private static String CPL_KCBD_ZHCK = "cpl_kcbd_zhck";	// 成品粮库存变动 商品拆分出库
    @SystemLog(module = "成品库存", methods = "库存",uploadName = "cpl.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.KcbdXz) {  //性质变化
                    boolean a1 = deleteStockDetail(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.CplZhRk || workType == StoreWorkType.CplZhCk ||workType == StoreWorkType.CplCfRk || workType == StoreWorkType.CplCfCk ||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>> findPageVoBgtz(DataKcglCplxckcDefaultVo pageQuery) {
        //条形查询器
        QueryWrapper<DataKcglCplxckcDefault> queryWrapper = new QueryWrapper<>();
        if(StringUtils.isNotBlank(pageQuery.getUnitId())){
            queryWrapper.eq("xc.unitid",pageQuery.getUnitId());
        }

        if(StringUtils.isNotBlank(pageQuery.getSjjlspmc())){
            queryWrapper.like("xc.sjjlspmc", ResultUtil.getQueryWrapperformat(pageQuery.getSjjlspmc()));
        }
        if(StringUtils.isNotBlank(pageQuery.getCh())){
            queryWrapper.like("xc.ch", ResultUtil.getQueryWrapperformat(pageQuery.getCh()));
        }
        if(StringUtils.isNotBlank(pageQuery.getHwh())){
            queryWrapper.like("xc.hwh", ResultUtil.getQueryWrapperformat(pageQuery.getHwh()));
        }
        if (StringUtils.isNotBlank(pageQuery.getYwsjStart()) && StringUtils.isNotBlank(pageQuery.getYwsjEnd())){
            queryWrapper.apply(" DATE_FORMAT(ifnull(xc.cjsj,NOW()),'%Y-%m-%d') >=  '"+pageQuery.getYwsjStart()+"' AND DATE_FORMAT(ifnull(xc.cjsj,NOW()),'%Y-%m-%d') <= '"+pageQuery.getYwsjEnd()+" 23:59:59'");
        }
        queryWrapper.orderByDesc("xc.cjsj");
        //分页相关
        Page<DataKcglCplxckcDefault> p =new Page<>(pageQuery.getPage(),pageQuery.getLimit());
        IPage<Map<String,Object>> page =dataKcglCplxckcDefaultMapper.findPageVoBgtz(p,queryWrapper);
        List<Map<String, Object>> records = page.getRecords();
        for (Map<String, Object> s:records) {
            String cazylx = s.get("cazylx").toString();
            if("cpl_rk".equals(cazylx)){
                s.put("cazylx","入库");
            }else if("cpl_ck".equals(cazylx)){
                s.put("cazylx","出库");
            }else if("cpl_qc".equals(cazylx)){
                s.put("cazylx","期初");
            }else if("cpl_kcbd_sy".equals(cazylx)){
                s.put("cazylx","盘点益");
            }
            else if("cpl_kcbd_ck".equals(cazylx)){
                s.put("cazylx","盘点损");
            }
        }
        return page;
    }

    /**
     * 删除库存明细，库存明细的子表通过数据库外键级联删除
     *
     * @param dataId
     *          入库称皮重/出库称毛重id
     * @return true:删除成功 false:删除失败
     * @throws Exception
     */
    @SystemLog(module = "成品库存", methods = "库存",uploadName = "cpl.kcbd")
    private boolean deleteStockDetail(String unitId, String dataId,
                                      StoreWorkType workType,EditStatus...editStatus) throws Exception {
        // 查询出要删除的库存信息
        CplStore store = getStoreInfo(dataId);
        CplFcbgzStore fcbgzStore = getFcStoreInfo(dataId, editStatus);
        //处理形成分库保管账与库存实物
        if (!deductStore(unitId, dataId, workType, store,fcbgzStore,editStatus)) {
            return false;
        }
        DataKcglCplxckcDefault dataKcglCplxckcDefault = dataKcglCplxckcDefaultMapper.selectById(dataId);
        // 删除库存明细
//        String sql = SqpMapUtil.getSql("DELETE_STOCK");
        if (!super.removeById(dataId)) {
            return false;
        }
        deleteDataRecordService.save(dataId,"data_kcgl_cplxckc_default",dataKcglCplxckcDefault.getUnitid(),new Date());
        // 冲抵库存
        return true;
    }
    /**
     * 冲抵库存
     * 修改与删除数量时，要将原来的形成库存删除，修改时会新增加一条形成库存
     * 所以要 修改与删除时，都进行删除操作
     * 分仓保管账  进行物理删除
     * 实物库存  则是通过查询五个口径得到相应数据进行修改，在实物库存为0时，删除这条数据
     * @param dataId
     *          入库称皮重/出库称毛重id
     * @param workType
     *          作业方式
     * @param store
     *          库存对象
     * @return
     * @throws Exception
     */
    @SystemLog(module = "成品库存", methods = "库存",uploadName = "cpl.kcbd")
    private boolean deductStore(String unitId, String dataId,
                                StoreWorkType workType, CplStore store, CplFcbgzStore fcbgzStore, EditStatus...editStatus) throws Exception {
        DataKcglCplfcbgzDefault dataKcglFcbgzDefault  = dataKcglCplfcbgzDefaultService.getById(dataId);

        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+"'";
            if (dataKcglFcbgzDefault != null ) { //表示是修改操作
                //将此条数据ModifyDate之后的数据进行kcsl的修改
                String lkbm = store.getLkbm(); //粮库编码
                String ch =  store.getCf(); //仓房
                String hwh = store.getHwh(); //货位
                String pz = store.getPz();//粮食品种
                String zy = store.getZy();//摘要
                String lsxz = store.getLsxz();//粮食性质
                String gg = store.getGg();//规格
                Double sl = dataKcglFcbgzDefault.getZcsl()-dataKcglFcbgzDefault.getSrsl();
                Double srsl = dataKcglFcbgzDefault.getSrsl();
                Double zcsl = dataKcglFcbgzDefault.getZcsl();
                Double zje = sl*fcbgzStore.getFsdj()/Double.parseDouble(gg); //变动数量*发生单价/规格
                String date =  DateUtil.format(dataKcglFcbgzDefault.getRcrq(),JSON.DEFFAULT_DATE_FORMAT);
//                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 (!dataKcglCplfcbgzDefaultService.updateFcbgzByWrapper(unitId,sl,zje,dataId,dataKcglFcbgzDefault))
                    return false;
            }
        }
        //删除分仓保管账
//        String sql = String.format(SqpMapUtil.getSql("DELETE_FCBGZ"),  dataId);
        if (!dataKcglCplfcbgzDefaultService.removeById(dataId))
            return false;
        //TODO 删除仓库保管账
        deleteDataRecordService.save(dataId,"data_kcgl_cplfcbgz_default",dataKcglFcbgzDefault.getUnitid(),new Date());
        fcbgzStore.setSaveFcbgz(true); //处理分库保管账数据
        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= dataKcglCplkcswDefaultService.changeKCSW(unitId,  dataId, store, fcbgzStore,store.getInNum(), false);
            if (!flag) {
                return flag;
            }
        } else { //出库
            store.setInNum(0.0);
            store.setOutNum(-store.getOutNum());  //将出库的值加上
            // 实物库存
            flag= dataKcglCplkcswDefaultService.changeKCSW(unitId,  dataId, store,fcbgzStore, -store.getOutNum(), false);
        }
        return flag;
        //修改时间
    }
    /**
     * 创建入仓库存明细
     *
     * @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";

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

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

        //得到形成库存与库存相关信息
        CplStore 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 = dataKcglCplfcbgzDefaultService.changeFCBGZ(loginName, unitId, dataId, store,fcbgzStore,"");
        if (!boolean1) {
            return boolean1;
        }
        //分库保管账已处理完毕
        fcbgzStore.setSaveFcbgz(true);
        // 实物库存
        boolean1 = dataKcglCplkcswDefaultService.changeKCSW(unitId,  dataId, store,fcbgzStore, store.getInNum(), false);
        if (!boolean1) {
            return boolean1;
        }
        //修改时间
        return true;
    }
    /**
     * 创建出库库存明细
     *
     * @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;
        // 查出分库保管账信息，如果是新增，则不存在

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

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

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

        /// 生成分仓保管账 ts 2018-05-11
        Boolean boolean1  = dataKcglCplfcbgzDefaultService.changeFCBGZ(loginName, unitId, dataId, store,fcbgzStore,"");
        if (!boolean1) {
            return false;
        }
        //分库保管账已处理完毕
        fcbgzStore.setSaveFcbgz(true);
        // 实物库存
        return dataKcglCplkcswDefaultService.changeKCSW(unitId,  dataId, store, fcbgzStore,-store.getOutNum(), false);
    }
    /**
     * 创建期初库存保存时 仓库明细
     * @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";

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

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

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

        // 生成分仓保管账 ts 2018-05-11
        Boolean boolean1  = dataKcglCplfcbgzDefaultService.changeFCBGZ(loginName, unitId, dataId, store,fcbgzStore,"");
        if (!boolean1) {
            return boolean1;
        }
        //分库保管账已处理完毕
        fcbgzStore.setSaveFcbgz(true);
        // 实物库存
        return  dataKcglCplkcswDefaultService.changeKCSW(unitId,  dataId, store,fcbgzStore, store.getInNum(), false);
    }
    /**
     *    创建库存变动保存时 仓库明细 业务
     * @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";
        //得到原始分库保管账信息
        CplFcbgzStore fcbgzStore = getFcStoreInfo(dataId, editStatus);
        CplFcbgzStore fcbgzStore_1 = getFcStoreInfo(reverseDataId, editStatus);
        if (editStatus == EditStatus.Modified) { // 修改
            // 删除原来的库存明细
            if (workType == StoreWorkType.KcbdRk) { //调增
                if(!deleteStockDetail(unitId, dataId,StoreWorkType.In,editStatus)){
                    return false;
                }
            }else if (workType == StoreWorkType.KcbdCk || workType == StoreWorkType.KcbdPc) { //调减 平仓损益（调减）
                if(!deleteStockDetail(unitId, dataId,StoreWorkType.Out,editStatus)){
                    return false;
                }
            }else if (workType == StoreWorkType.KcbdYc || workType == StoreWorkType.KcbdXz) { //移仓,性质变化操作，A 出 B入
//                deleteStockDetail(unitId, dataId, StoreWorkType.Out);
                if(!deleteStockDetail(unitId, dataId,StoreWorkType.Out,editStatus)){
                    return false;
                }
//                deleteStockDetail(unitId, reverseDataId, StoreWorkType.In);
                if(!deleteStockDetail(unitId, dataId,StoreWorkType.Out,editStatus)){
                    return false;
                }
            }
        }

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

        if(workType == StoreWorkType.KcbdRk) {
            type = CPL_KCBD_RK;
            cazylx = StoreWorkType.In;
        } else if(workType == StoreWorkType.KcbdCk) {
            type = CPL_KCBD_CK;
            cazylx = StoreWorkType.Out;
        }else if(workType == StoreWorkType.KcbdPc) {
            type = CPL_KCBD_PC;
            cazylx = StoreWorkType.Out;
        } else if(workType == StoreWorkType.KcbdYc) {
            type = CPL_KCBD_SY;
            cazylx = StoreWorkType.Out;
        }else if(workType == StoreWorkType.KcbdXz ) {
            cazylx = StoreWorkType.Out;
            type = CPL_KCBD_XZBH;
        }else if(workType == StoreWorkType.CplCfRk ) {
            cazylx = StoreWorkType.In;
            type = CPL_KCBD_CFRK;
        }else if(workType == StoreWorkType.CplCfCk ) {
            cazylx = StoreWorkType.Out;
            type = CPL_KCBD_CFCK;
        }else if(workType == StoreWorkType.CplZhRk ) {
            cazylx = StoreWorkType.In;
            type = CPL_KCBD_ZHRK;
        }else if(workType == StoreWorkType.CplZhCk ) {
            cazylx = StoreWorkType.Out;
            type = CPL_KCBD_ZHCK;
        }
        // 生成库存明细
        int i = dataKcglCplxckcDefaultMapper.addKcbdStock(dataId, loginName,
                flowName, cazylx.value(), type);
        if (i != 1) //未成功写入一条数据
            return false;

        // 获取库存信息
        double stockNum = 0;
        CplStore store = getStoreInfo(dataId);
//        double stockNum = store.getStoreNum();
        if(workType == StoreWorkType.KcbdRk ) {
            stockNum = store.getInNum();

        } else if(workType == StoreWorkType.CplCfCk ||workType == StoreWorkType.CplZhCk ||workType == StoreWorkType.KcbdCk || workType == StoreWorkType.KcbdPc || workType == StoreWorkType.KcbdYc || workType == StoreWorkType.KcbdXz) {
            stockNum = -store.getOutNum();
        }
        // 生成分仓保管账
        boolean boolean1 =  dataKcglCplfcbgzDefaultService.changeFCBGZ(loginName, unitId, dataId, store,fcbgzStore,"");
        if (!boolean1) {
            return boolean1;
        }
        // 实物库存
        boolean1 =  dataKcglCplkcswDefaultService.changeKCSW(unitId,  dataId, store,fcbgzStore, stockNum, false);
        if (!boolean1) {
            return boolean1;
        }
        if(workType == StoreWorkType.KcbdYc ||workType == StoreWorkType.CplCfRk  || workType ==StoreWorkType.CplZhRk) { // 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 = dataKcglCplxckcDefaultMapper.addKcbdYcStock(reverseDataId,dataId, loginName,
                    flowName, StoreWorkType.In.value(), type);
            if (i != 1) //未成功写入一条数据
                return false;
            CplStore iNStore = getStoreInfo(reverseDataId);
            double iStockNum = iNStore.getInNum();

            // 生成分仓保管账
            boolean1 = dataKcglCplfcbgzDefaultService.changeFCBGZ(loginName, unitId, reverseDataId, iNStore,fcbgzStore_1,"");
            if (!boolean1) {
                return boolean1;
            }
            // 实物库存
            boolean1 = dataKcglCplkcswDefaultService.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 = dataKcglCplxckcDefaultMapper.addKcbdXzbhStock(reverseDataId,dataId, loginName,
                    flowName, StoreWorkType.In.value(), type);
            if (i != 1) //未成功写入一条数据
                return false;
            CplStore iNStore = getStoreInfo(reverseDataId);
            double iStockNum = iNStore.getInNum();

            // 生成分仓保管账
            boolean1 = dataKcglCplfcbgzDefaultService.changeFCBGZ(loginName, unitId, reverseDataId, iNStore,fcbgzStore_1,"");
            if (!boolean1) {
                return boolean1;
            }
            // 实物库存
            boolean1 =  dataKcglCplkcswDefaultService.changeKCSW(unitId, reverseDataId, iNStore, fcbgzStore_1,iStockNum, false);
            if (!boolean1) {
                return boolean1;
            }
        }
        return  true;
    }
    /**
     * 获取成品粮库存信息
     *
     * @param dataId
     *          库存明细id
     * @return 库存对象
     */
    @SuppressWarnings("unchecked")
    private CplStore getStoreInfo(String dataId) {
        CplStore store = new CplStore();

        // 查询当前出入库数量等信息
//        String sql = String.format(SqpMapUtil.getSql("QUERY_STOCK_DETAIL"), dataId);
//        List<Map<String, Object>> list = dataKcglKcswDefaultService.queryStockDetail(dataId);
        DataKcglCplxckcDefault dataKcglCplxckcDefault = super.getById(dataId);
        if (dataKcglCplxckcDefault != null) {
            store.setCrkdh(dataKcglCplxckcDefault.getCrkdh());
            store.setLkbm(dataKcglCplxckcDefault.getUnitid());
            store.setCf(dataKcglCplxckcDefault.getCh()); //仓房
            store.setHwh(dataKcglCplxckcDefault.getHwh());//货位
            store.setLsxz(dataKcglCplxckcDefault.getXz()); //性质

            store.setPp(dataKcglCplxckcDefault.getSjjlppbh()); //品牌
            store.setPz(dataKcglCplxckcDefault.getSjjlpzbh()); //品种
            store.setMxpz(dataKcglCplxckcDefault.getSjjlspmcbh()); //实际军粮商品名称编号/明细品种
            store.setScpc(dataKcglCplxckcDefault.getScpc());//批次
            store.setGg(dataKcglCplxckcDefault.getGg()); //规格
            String ywlx = dataKcglCplxckcDefault.getYwlx(); //作业类型 1，入库 5期初，3出库
            Double inNum = 0.0;
            Double outNum = 0.0;
            if ("1".equals(ywlx) || "5".equals(ywlx)){ // 入库，期初库存
                inNum = dataKcglCplxckcDefault.getSjjlsl();
            }else if ("3".equals(ywlx) ){ //出库
                outNum = dataKcglCplxckcDefault.getSjjlsl();
            }
            store.setInNum(inNum);
            store.setOutNum(outNum);
            store.setKcdj(dataKcglCplxckcDefault.getDj()); //单价
            //不能取得单价，使用平均单价
            if (dataKcglCplxckcDefault.getDj() == null || dataKcglCplxckcDefault.getDj() <=0.0) {
                //设置默认单位0.0
                store.setKcdj(0.0);

                QueryWrapper<DataKcglCplkcswDefault> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("unitid", dataKcglCplxckcDefault.getUnitid());
                queryWrapper.eq("ch", dataKcglCplxckcDefault.getCh());
                queryWrapper.eq("hwh", dataKcglCplxckcDefault.getHwh());
                queryWrapper.eq("xz", dataKcglCplxckcDefault.getXz());
                queryWrapper.eq("sjjlppbh", dataKcglCplxckcDefault.getSjjlppbh()); //品牌
                queryWrapper.eq("sjjlpzbh", dataKcglCplxckcDefault.getSjjlpzbh()); //品种
                queryWrapper.eq("sjjlspmcbh", dataKcglCplxckcDefault.getSjjlspmcbh());//明细品种
                queryWrapper.eq("scpc", dataKcglCplxckcDefault.getScpc());//生产批次
                queryWrapper.eq("gg", dataKcglCplxckcDefault.getGg());//规格
                queryWrapper.last("limit 1"); //得到一条
                DataKcglCplkcswDefault kcglCplkcswDefault = dataKcglCplkcswDefaultService.getOne(queryWrapper);
                if (kcglCplkcswDefault != null) {
                    store.setStoreNum(kcglCplkcswDefault.getKcsl());
                    //库存总金额
                    store.setKczje(kcglCplkcswDefault.getZje());
                    //库存件数
                    store.setKcjs(kcglCplkcswDefault.getJs());
                    //库存单价
                    if (store.getKcdj() <= 0.0) {
                        try { //成品粮单价=金额/件数
                            store.setKcdj(NumberUtil.div(store.getKczje(), store.getKcjs()));
                        } catch (Exception e) {
                            store.setKcdj(0.0);
                        }

                    }
                }
            }else {
                dataKcglCplxckcDefault.setDj(0.0); //设置单价为0
            }
        }


        return store;
    }
    /**
     * 获取分库保管账信息
     *
     * @param dataId
     *          库存明细id
     * @return 库存对象
     */
    @SuppressWarnings("unchecked")
    private CplFcbgzStore getFcStoreInfo(String dataId, EditStatus...editStatus) {
        CplFcbgzStore fcbgzStore = new CplFcbgzStore();
//        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);
        DataKcglCplfcbgzDefault cplfcbgzDefault = dataKcglCplfcbgzDefaultService.getById(dataId);
        if (cplfcbgzDefault != null) {
            fcbgzStore.setEditStatus(EditStatus.Modified); //设置为修改
            //查询分库保管账中的信息
            fcbgzStore.setFcbgzKcsl(cplfcbgzDefault.getKcsl());
            fcbgzStore.setFcbgzSrsl(cplfcbgzDefault.getSrsl());
            fcbgzStore.setFcbgzZcsl(cplfcbgzDefault.getZcsl());
            fcbgzStore.setFcbgzRq(DateUtil.format(cplfcbgzDefault.getRcrq(),JSON.DEFFAULT_DATE_FORMAT));
            fcbgzStore.setZje(cplfcbgzDefault.getJe());
            fcbgzStore.setFsdj(cplfcbgzDefault.getFsdj());
            fcbgzStore.setFsje(cplfcbgzDefault.getFsje());
        }
        if (editStatus.length == 1 ) {
            fcbgzStore.setEditStatus(editStatus[0]);
        }

        return fcbgzStore;
    }
    /**
     * 按照条件查询成品粮形成库存信息
     * @param pageQuery
     * @throws Exception
     */
    @Override
    public IPage<Map<String,Object>> findPageVo(DataKcglCplxckcDefaultVo pageQuery){
        {
            //条形查询器
            QueryWrapper<DataKcglCplxckcDefault> queryWrapper = new QueryWrapper<>();
            //分页相关
            Page<DataKcglCplxckcDefault> p =new Page<>(pageQuery.getPage(),pageQuery.getLimit());

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


}
