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

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
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.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.DataKcglFcbgzDefaultVo;
import com.unis.crk.business.kcgl.mapper.DataKcglFcbgzDefaultMapper;
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.mapper.BillnonewgjjMapper;
import com.unis.crk.common.service.IDeleteDataRecordService;
import com.unis.crk.enums.EditStatus;
import com.unis.crk.utils.FunUtils;
import com.unis.crk.utils.SqpMapUtil;
import org.apache.commons.lang.StringUtils;
import org.bouncycastle.jcajce.provider.symmetric.Salsa20;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
 * <p>
 * 库存管理-分库保管账表 服务实现类
 * </p>
 *
 * @author TangSong
 * @since 2021-10-11
 */
@Service
public class DataKcglFcbgzDefaultServiceImpl extends ServiceImpl<DataKcglFcbgzDefaultMapper, DataKcglFcbgzDefault> implements IDataKcglFcbgzDefaultService {

    @Resource
    private DataKcglFcbgzDefaultMapper dataKcglFcbgzDefaultMapper;

    @Autowired
    IDataKcglXckcDefaultService dataKcglXckcDefaultService;

    @Resource
    private BillnonewgjjMapper billnonewgjjMapper;
    /**
     * 按照条件查询库存管理-分库保管账表信息
     * @param pageQuery
     * @throws Exception
     */
    @Override
    public IPage<Map<String,Object>> findPageVo(DataKcglFcbgzDefaultVo pageQuery){
        {
        //条形查询器
        QueryWrapper<DataKcglFcbgzDefault> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(pageQuery.getBizNo())){
        queryWrapper.like("bizNo",pageQuery.getBizNo());
        }
        //分页相关
        Page<DataKcglFcbgzDefault> p =new Page<>(pageQuery.getPage(),pageQuery.getLimit());

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

    @Override
    public boolean updateFcbgzByWrapper(Double sl, Double zcsl, Double srsl, String unitId, String ch, String hwh, String pz, String lsxz, String date, String dataId) {
        return dataKcglFcbgzDefaultMapper.updateFcbgzByWrapper(sl,zcsl,srsl, unitId,
                ch, hwh, pz, lsxz,date,dataId) >= 0;
    }

    @Override
    public List<Map<String, Object>> queryFcbgzByid(String dataId) {
        return dataKcglFcbgzDefaultMapper.queryFcbgzByid(dataId);
    }

    @SuppressWarnings("unchecked")
    public boolean changeFCBGZ(String userName, String unitId, String dataId, Store store, FcbgzStore fcbgzStore, String bz) throws Exception {
        String ch =  store.getCf(); //仓房
        String hwh = store.getHwh(); //货位
        String pz = store.getPz();//粮食品种
        String lsxz = store.getLsxz();//粮食性质
        double inNum = store.getInNum(); //入库数量
        double outNum = store.getOutNum(); //出库数量
        double inrealNum = store.getInRealNum(); //入库实际数量
        double outrealNum = store.getOutRealNum(); //出库实际数量
        EditStatus editStatus = fcbgzStore.getEditStatus(); //修改还是新增
        Date date_ = new Date();
        // 生成分仓保管帐
        Double kcsl = 0.0;
        Double kcsjsl = 0.0;//庫存實際數量
        Double ljsrsl = 0.0;//累计收入数量
        Double ljzcsl = 0.0;//累计支出数量
        Double ljsrsjsl = 0.0;//累计收入实际数量
        Double ljzcsjsl = 0.0;//累计支出实际数量
        List<Map<String, Object>> list = null;
        if (editStatus == editStatus.New) {
            //得到形成库存中rcrq做为查询条件,因为补录数据rq会是中间数据
            DataKcglXckcDefault dataKcglXckcDefault = dataKcglXckcDefaultService.getById(dataId);
            String rqcq =  DateUtil.format(dataKcglXckcDefault.getRcrq(),"yyyy-MM-dd HH:mm:ss");
//            sql = String.format(SqpMapUtil.getSql("QUERY_FCBGZ"), unitId, lkbm,
//                    ch, hwh, pz, lsxz);
//            list = findBySql(sql);
            QueryWrapper<DataKcglFcbgzDefault> fcbgzQueryWrapper = new QueryWrapper<>();
            fcbgzQueryWrapper.eq("unitId",unitId);
            fcbgzQueryWrapper.eq("ch",ch);
            fcbgzQueryWrapper.eq("hwh",hwh);
            fcbgzQueryWrapper.eq("pz",pz);
            //小于等于
            fcbgzQueryWrapper.le("rq",rqcq);
            fcbgzQueryWrapper.eq("hwxz",lsxz);
            fcbgzQueryWrapper.orderByDesc("rq"); //按rq倒序得到最后一条业务数据
            fcbgzQueryWrapper.last("limit 1");
            DataKcglFcbgzDefault dataKcglFcbgzDefault = super.getOne(fcbgzQueryWrapper,false);
            if (dataKcglFcbgzDefault != null) { //表示有库存数量，进行库存数量的累积
                Double oldKcsl = dataKcglFcbgzDefault.getKcsl();
                Double oldLjsrsl = dataKcglFcbgzDefault.getLjsrsl();
                Double oldLjzcsl =dataKcglFcbgzDefault.getLjzcsl();
                Double oldKcsjsl = dataKcglFcbgzDefault.getKcsjsl();
                Double oldLjsrsjsl = dataKcglFcbgzDefault.getLjsrsjsl();
                Double oldLjzcsjsl = dataKcglFcbgzDefault.getLjzcsjsl();
                if (ObjectUtil.isEmpty(oldKcsl)) {
                    kcsl = 0.0;
                }else {
                    kcsl = oldKcsl;
                }
                if (ObjectUtil.isEmpty(oldLjsrsl)) {
                    ljsrsl = 0.0;
                }
                if (ObjectUtil.isEmpty(oldLjzcsl)) {
                    ljzcsl = 0.0;
                }
                if (ObjectUtil.isEmpty(oldKcsjsl)) {
                    kcsjsl = kcsl;					//如果实际数量为零，设为和库存数量一致，达到初始化的目的
                }else {
                    kcsjsl = dataKcglFcbgzDefault.getKcsjsl();
                }
                if (ObjectUtil.isEmpty(oldLjsrsjsl)) {
                    ljsrsjsl = 0.0;
                }
                if (ObjectUtil.isEmpty(oldLjzcsjsl)) {
                    ljzcsjsl = 0.0;
                }

            }
        }else {
            //得到当前数据库存相关，只有一条数据
            kcsl = fcbgzStore.getFcbgzKcsl();
            kcsjsl = fcbgzStore.getFcbgzKcsjsl();
            ljsrsl = fcbgzStore.getFcbgzLjsrsl();
            ljzcsl = fcbgzStore.getFcbgzLjzcsl();
            ljsrsjsl = fcbgzStore.getFcbgzLjsrsjsl();
            ljzcsjsl = fcbgzStore.getFcbgzLjzcsjsl();


        }
        Double bdsl = (inNum-fcbgzStore.getFcbgzSrsl()-(outNum-fcbgzStore.getFcbgzZcsl() )); //变动数量
        if (inNum < 0 || outNum < 0 || bdsl+kcsl < 0 ){
            return  false;
        }
//        System.out.println((inNum-fcbgzStore.getFcbgzSrsl()-(outNum-fcbgzStore.getFcbgzZcsl() ))+kcsl);
        //修改时新库存数量 = 入库旧值-入库新值-(出库旧值-出库新值)+库存旧值 Ts 2021-04-08
//        sql = String.format(SqpMapUtil.getSql("ADD_FCBGZ"), userName, inNum,
//                outNum, (inNum-fcbgzStore.getFcbgzSrsl()-(outNum-fcbgzStore.getFcbgzZcsl() ))+kcsl,userName,ljsrsl+inNum,ljzcsl+outNum,  dataId);
        int i = dataKcglFcbgzDefaultMapper.addFfcbgz(userName, inNum,
                outNum, bdsl+kcsl,
                ljsrsl + (inNum - fcbgzStore.getFcbgzSrsl()),
                ljzcsl + (outNum-fcbgzStore.getFcbgzZcsl()),
                inrealNum,
                outrealNum,
                (inrealNum - fcbgzStore.getFcbgzSrsjsl() - (outrealNum - fcbgzStore.getFcbgzZcsjsl())) + kcsjsl,
                ljsrsjsl + (inrealNum - fcbgzStore.getFcbgzSrsjsl()),
                ljzcsjsl + (outrealNum - fcbgzStore.getFcbgzZcsjsl()),
                dataId);
        boolean ret = i == 1; //成功写入一条数据
        if (!ret) return  false;
        //新增补录或者修改操作处理此条数据后的分库保管数据
//        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+"'";
//        list  = this.findBySql(sql);
        DataKcglFcbgzDefault dataKcglFcbgzDefault = super.getById(dataId);
        //保存月结单数据
        if (!changeYJD(dataId,store)){
            return  false;
        }
        if (dataKcglFcbgzDefault != null) { //表示是修改操作
            //将此条数据rq之后的数据进行kcsl，zje的修改
            Double sl =  bdsl;

            String date =  DateUtil.format(dataKcglFcbgzDefault.getRq(),"yyyy-MM-dd HH:mm:ss");

            UpdateWrapper<DataKcglFcbgzDefault> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("unitId",unitId);
            updateWrapper.eq("ch",ch);
            updateWrapper.eq("hwh",hwh);
            updateWrapper.eq("pz",pz);
            updateWrapper.eq("hwxz",lsxz);
           // updateWrapper.set("zy",zy);
            updateWrapper.ge("rq",date);
            updateWrapper.ne("dataId",dataId);
//            updateWrapper.set("kcsl","kcsl+("+sl+")");
//            updateWrapper.set("UPDATE_TIME",null);
            updateWrapper.setSql("UPDATE_TIME=null,kcsl=kcsl+"+sl); //
            //更新此条数据之后的库存数量
            super.update(updateWrapper);

        }
        return ret;
    }

    /**
     * 创建入库和出库月结单
     * hzq 2018-11-07
     *
     * @param dataId
     * @param store 用他获取五个口径
     * @param
     * @return
     */
    public boolean changeYJD(String dataId, Store store)  {
        String cf = null;	// 仓房
        String hwh = null;	// 货位号
        String lkbm = null;	// 粮库编码
        String lkmc = null;	// 粮库名称
        String lsxz = null;	// 粮食性质
        String pz = null;	// 品种
        double inNum = store.getInNum(); //入库数量
        double outNum = store.getOutNum(); //出库数量
//		    double stockNum = store.getStoreNum(); //库存数量
//		    double stockje = store.getStoreJe(); //库存金额
        double kcdj = 0.0; //单价

        //在库存变动时无单价

        if(store != null) {
            cf = store.getCf();
            hwh = store.getHwh();
            lkbm = store.getLkbm();
            lsxz = store.getLsxz();
            pz = store.getPz();
            lkmc = store.getLkmc();
        }
        Calendar now = Calendar.getInstance();
        int year = now.get(Calendar.YEAR);
        int month = now.get(Calendar.MONTH) + 1;
        String currentDataSql = String.format(SqpMapUtil.getSql("QUERY_MONTH_DATA"), pz, lsxz, cf, hwh, lkbm, year,month);

        List<Map<String, Object>> currentDataList = billnonewgjjMapper.findBySql(currentDataSql);
        if (currentDataList.size() == 0) {/*可能是修改当前DataId数据*/
            currentDataList = billnonewgjjMapper.findBySql(String.format(SqpMapUtil.getSql("QUERY_MONTH_DATA_ID"),dataId));
        }
        if (currentDataList.size() > 0) {
            //表示当天已经有数据了

            double todayQckc = Double.parseDouble(currentDataList.get(0).get("qckc").toString());
            double todayQmkc = Double.parseDouble(currentDataList.get(0).get("qmkc").toString());
            double todayZje = Double.parseDouble(currentDataList.get(0).get("zje").toString());
            double newQmkc =inNum-outNum + todayQmkc;
            double zje = (inNum-outNum)*kcdj +todayZje;
            String updateSql = String.format(SqpMapUtil.getSql("UPDATE_YJD"),inNum,outNum,newQmkc,zje, hwh, cf, pz, lsxz, lkbm,year,month);
             billnonewgjjMapper.executeUpdate(updateSql);

            return true;
        } else {
            // 只有新增的时候，才会查询上次数据
            int preYear=year;
            int preMonth=month;
            if (preMonth==1) {
                preYear=preYear-1;
                preMonth=12;
            }else {
                preMonth=preMonth-1;
            }
            String preKCDataSql = String.format(SqpMapUtil.getSql("QUERY_PRE_YJD_DATA"), pz, lsxz, cf, hwh, lkbm,preYear,preMonth);
            List<Map<String, Object>> preDataList = billnonewgjjMapper.findBySql(preKCDataSql);
            double qckc = 0.0;
            double qmkc = 0.0;
            if (preDataList.size() > 0) {
                // 取上一次期初库存 与 期末库存 值
                qckc = Double.parseDouble(preDataList.get(0).get("qckc").toString());
                qmkc = Double.parseDouble(preDataList.get(0).get("qmkc").toString());
            }
            // 期初库存等于上次期末库存的值，期末库存根据入库或出库来计算
            double newQckc = qmkc;
            double newQmkc = inNum-outNum + qmkc;
            double zje = newQmkc*kcdj;
            boolean addResult = false;
            String addSql = String.format(SqpMapUtil.getSql("ADD_YJD"), inNum,outNum,newQckc,newQmkc,year,month,zje,dataId
            );
             billnonewgjjMapper.executeUpdate(addSql);
            return true;
        }

    }
}
