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

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import com.alibaba.fastjson.JSON;
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.cplbusiness.entity.CplFcbgzStore;
import com.unis.crk.cplbusiness.entity.CplStore;
import com.unis.crk.cplbusiness.entity.DataKcglCplfcbgzDefault;
import com.unis.crk.cplbusiness.entity.vo.DataKcglCplfcbgzDefaultVo;
import com.unis.crk.cplbusiness.mapper.DataKcglCplfcbgzDefaultMapper;
import com.unis.crk.cplbusiness.service.IDataKcglCplfcbgzDefaultService;
import com.unis.crk.enums.EditStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
 * <p>
 * 成品粮分仓保管账 服务实现类
 * </p>
 *
 * @author TangSong
 * @since 2022-03-21
 */
@Service
public class DataKcglCplfcbgzDefaultServiceImpl extends ServiceImpl<DataKcglCplfcbgzDefaultMapper, DataKcglCplfcbgzDefault> implements IDataKcglCplfcbgzDefaultService {

    @Resource
    private DataKcglCplfcbgzDefaultMapper dataKcglCplfcbgzDefaultMapper;



    /**
     *修改成品粮分仓保管账
     * @param param 成品粮分仓保管账业务数据
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public JSONObject update(DataKcglCplfcbgzDefault param){
        return null;
    }
    /**
     *删除成品粮分仓保管账数据
     * @param id 成品粮分仓保管账主键尖
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public JSONObject delete(String id){
        return null;
        }

    /**
     * 按照条件查询成品粮分仓保管账信息
     * @param pageQuery
     * @throws Exception
     */
    @Override
    public IPage<Map<String,Object>> findPageVo(DataKcglCplfcbgzDefaultVo pageQuery){
        {
        //条形查询器
        QueryWrapper<DataKcglCplfcbgzDefault> queryWrapper = new QueryWrapper<>();
        //分页相关
        Page<DataKcglCplfcbgzDefault> p =new Page<>(pageQuery.getPage(),pageQuery.getLimit());

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

    @Override
    public Boolean changeFCBGZ(String userName, String unitId, String selectDataId, CplStore store, CplFcbgzStore fcbgzStore, String bz) {
        {
            String lkbm = store.getLkbm(); //粮库编码
            String ch =  store.getCf(); //仓房
            String hwh = store.getHwh(); //货位
            String lsxz = store.getLsxz();//粮食性质
            String pp = store.getPp(); //品牌
            String pz = store.getPz();//粮食品种
            String mxpz = store.getMxpz(); //明细品种
            String scpc = store.getScpc(); //生产批次
            String gg  = store.getGg(); //规格

            Double kcdj = store.getKcdj(); //库存单价 都使用库存单位
            double inNum = store.getInNum(); //入库数量
            double outNum = store.getOutNum(); //出库数量
            EditStatus editStatus = fcbgzStore.getEditStatus(); //修改还是新增
            Date date_ = new Date();
            // 生成分仓保管帐
            Double kcsl = 0.0;
            Double zje = 0.0;//总金额，累计金额
            Double fsje = 0.0;//发生金额
            Double fsdj = 0.0;//发生单价
            List<Map<String, Object>> list = null;
            if (editStatus == editStatus.New) {

//            sql = String.format(SqpMapUtil.getSql("QUERY_FCBGZ"), unitId, lkbm,
//                    ch, hwh, pz, lsxz);
//            list = findBySql(sql);
                QueryWrapper<DataKcglCplfcbgzDefault> fcbgzQueryWrapper = new QueryWrapper<>();
                fcbgzQueryWrapper.eq("unitId",unitId);
                fcbgzQueryWrapper.eq("ch",ch);
                fcbgzQueryWrapper.eq("hwh",hwh);
//            fcbgzQueryWrapper.eq("zy",zy);
                fcbgzQueryWrapper.eq("xz",lsxz);
                fcbgzQueryWrapper.eq("sjjlppbh",pp);
                fcbgzQueryWrapper.eq("sjjlpzbh",pz);
                fcbgzQueryWrapper.eq("sjjlspmcbh",mxpz);
                fcbgzQueryWrapper.eq("scpc",scpc);
                fcbgzQueryWrapper.eq("gg",gg);
                fcbgzQueryWrapper.orderByDesc("rcrq"); //按rq倒序得到最后一条业务数据
                fcbgzQueryWrapper.last("limit 1");
                DataKcglCplfcbgzDefault cplFcbgzDefault = super.getOne(fcbgzQueryWrapper);
                if (cplFcbgzDefault != null) { //表示有库存数量，进行库存数量的累积
                    Object oldKcsl = cplFcbgzDefault.getKcsl();
                    Object oldZje = cplFcbgzDefault.getJe();
//                Object oldFsje = dataKcglFcbgzDefault.getFsje();
                    if(ObjectUtil.isEmpty(oldKcsl)){
                        kcsl=0.0;
                    }else{
                        kcsl = Double.parseDouble(oldKcsl.toString()); //得到库存数量
                    }
                    if(ObjectUtil.isEmpty(oldZje)){
                        zje=0.0;
                    }else{
                        zje = Double.parseDouble(oldZje.toString()); //得到原始总金额
                    }
//                if(ObjectUtil.isEmpty(oldFsje)){
//                    fsje=0.0;
//                }else{
//                    fsje = Double.parseDouble(oldFsje.toString()); //得到原始发生金额
//                }

                }
            }else {
                //得到当前数据库存相关，只有一条数据
                kcsl = fcbgzStore.getFcbgzKcsl();
                zje = fcbgzStore.getZje();
                fsje = fcbgzStore.getFsje(); //原始发生金额
                fsdj =fcbgzStore.getFsdj();

            }
            Double bdsl = (inNum-fcbgzStore.getFcbgzSrsl()-(outNum-fcbgzStore.getFcbgzZcsl() )); //变动数量
            Double newFsje = Math.abs((inNum-outNum))*kcdj/Double.parseDouble(gg); //绝对值（入库数量-出库数量）*目前
            if (inNum-outNum > 0){ //表示是入库
                zje= zje-fsje+newFsje;
            }else{ //表示出库
                zje= zje+fsje-newFsje;
            }
            if (inNum < 0 || outNum < 0){ //入库数量或者出库数量小于0，直接报错，不让保存
                return false;
            }
            int i = dataKcglCplfcbgzDefaultMapper.addFfcbgz(userName, inNum,
                    outNum, bdsl+kcsl,zje,selectDataId);
            boolean ret = i == 1; //成功写入一条数据
            if (!ret) return  false;
            //修改以后的分库保管数据
            DataKcglCplfcbgzDefault cplFcbgzDefault = super.getById(selectDataId);
            if (cplFcbgzDefault != null) { //表示是修改操作
                //将此条数据rq之后的数据进行kcsl，zje的修改
                Double sl =  bdsl;

                String date =  DateUtil.format(cplFcbgzDefault.getRcrq(),JSON.DEFFAULT_DATE_FORMAT);

                UpdateWrapper<DataKcglCplfcbgzDefault> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("unitid",unitId);
                updateWrapper.eq("ch",ch);
                updateWrapper.eq("hwh",hwh);
                updateWrapper.eq("xz",lsxz);
                updateWrapper.eq("sjjlppbh",pp);
                updateWrapper.eq("sjjlpzbh",pz);
                updateWrapper.eq("sjjlspmcbh",mxpz);
                updateWrapper.eq("scpc",scpc);
                updateWrapper.eq("gg",scpc);
                // updateWrapper.set("zy",zy);
                updateWrapper.ge("rcrq",date);
                updateWrapper.ne("dataId",selectDataId);
//            updateWrapper.set("kcsl","kcsl+("+sl+")");
                updateWrapper.setSql("updateTime=null,kcsl=kcsl+"+sl+",je=je+"+(newFsje-fsje)); //
                //更新此条数据之后的库存数量，库存总金额
                super.update(updateWrapper);

            }
            return ret;
        }
    }


    @Override
    public boolean updateFcbgzByWrapper(String unitId,Double sl,Double zje ,String dataId, DataKcglCplfcbgzDefault dataKcglFcbgzDefault) {
//          update  data_kcgl_fcbgz_default  set kcsl =kcsl+(${sl}),zje =zje+(${zje})	WHERE unitId=#{unitId}  AND ifnull(ch,'')=#{ch} AND ifnull(hwh,'')=#{hwh} AND ifnull(pz,'')=#{pz} AND ifnull(hwxz,'')=#{hwxz}
//     and rq >= #{rq}   AND DataID != #{dataId}
        String ch =  dataKcglFcbgzDefault.getCh(); //仓房
        String hwh = dataKcglFcbgzDefault.getHwh(); //货位
        String lsxz = dataKcglFcbgzDefault.getXz();//粮食性质
        String pp = dataKcglFcbgzDefault.getSjjlppbh(); //品牌
        String pz = dataKcglFcbgzDefault.getSjjlpzbh();//粮食品种
        String mxpz = dataKcglFcbgzDefault.getSjjlspmcbh(); //明细品种
        String scpc = dataKcglFcbgzDefault.getScpc(); //生产批次
        String gg  = dataKcglFcbgzDefault.getGg(); //规格
        String date =  DateUtil.format(dataKcglFcbgzDefault.getRcrq(),JSON.DEFFAULT_DATE_FORMAT);

        UpdateWrapper<DataKcglCplfcbgzDefault> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("unitid",unitId);
        updateWrapper.eq("ch",ch);
        updateWrapper.eq("hwh",hwh);
        updateWrapper.eq("xz",lsxz);
        updateWrapper.eq("sjjlppbh",pp);
        updateWrapper.eq("sjjlpzbh",pz);
        updateWrapper.eq("sjjlspmcbh",mxpz);
        updateWrapper.eq("scpc",scpc);
        updateWrapper.eq("gg",scpc);
        updateWrapper.ge("rcrq",date);
        updateWrapper.ne("dataId",dataId);
        updateWrapper.setSql("updateTime=null,kcsl=kcsl+"+sl+",je=  je+"+zje); //
         super.update(updateWrapper);
        return true;
    }



}
