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

import com.unis.crk.aop.SystemLog;
import com.unis.crk.common.service.IDeleteDataRecordService;
import com.unis.crk.cplbusiness.entity.CplFcbgzStore;
import com.unis.crk.cplbusiness.entity.CplStore;
import com.unis.crk.cplbusiness.entity.DataKcglCplkcswDefault;
import com.unis.crk.cplbusiness.entity.DataKcglCplxckcDefault;
import com.unis.crk.cplbusiness.mapper.DataKcglCplkcswDefaultMapper;
import com.unis.crk.cplbusiness.service.IDataKcglCplkcswDefaultService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.unis.crk.enums.EditStatus;
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 org.springframework.transaction.annotation.Transactional;
import cn.hutool.json.JSONObject;
import javax.annotation.Resource;
import com.unis.crk.cplbusiness.entity.vo.DataKcglCplkcswDefaultVo;
/**
 * <p>
 * 成品粮库存实物 服务实现类
 * </p>
 *
 * @author TangSong
 * @since 2022-03-21
 */
@Service
public class DataKcglCplkcswDefaultServiceImpl extends ServiceImpl<DataKcglCplkcswDefaultMapper, DataKcglCplkcswDefault> implements IDataKcglCplkcswDefaultService {

    @Resource
    private DataKcglCplkcswDefaultMapper dataKcglCplkcswDefaultMapper;
    @Autowired
    private IDeleteDataRecordService deleteDataRecordService;


    /**
     *修改成品粮库存实物
     * @param param 成品粮库存实物业务数据
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public JSONObject update(DataKcglCplkcswDefault 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(DataKcglCplkcswDefaultVo pageQuery){
        {
        //条形查询器
        QueryWrapper<DataKcglCplkcswDefault> queryWrapper = new QueryWrapper<>();
            //分页相关
            if(StringUtils.isNotBlank(pageQuery.getUnitId())){
                queryWrapper.eq("a.unitId",pageQuery.getUnitId());
            }
            if(StringUtils.isNotBlank(pageQuery.getSjjlspmc())){
                queryWrapper.like("a.sjjlspmc",pageQuery.getSjjlspmc());
            }
            if(StringUtils.isNotBlank(pageQuery.getSjjlpzbh())){
                queryWrapper.eq("a.sjjlpzbh",pageQuery.getSjjlpzbh());
            }
            if(StringUtils.isNotBlank(pageQuery.getSjjlppbh())){
                queryWrapper.eq("a.sjjlppbh",pageQuery.getSjjlppbh());
            }
            if(StringUtils.isNotBlank(pageQuery.getCh())){
                queryWrapper.eq("a.ch",pageQuery.getCh());
            }
        //分页相关
        Page<DataKcglCplkcswDefault> p =new Page<>(pageQuery.getPage(),pageQuery.getLimit());

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

    @Override
    @SystemLog(module = "成品库存", methods = "库存",uploadName = "cpl.kcbd")
    public Boolean changeKCSW(String unitId, String selectDataId, CplStore store, CplFcbgzStore fcbgzStore, Double stockNum, boolean byBeginning) {
        {

            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 fsdj = fcbgzStore.getFsdj(); //发生单价
            Double kcdj = store.getKcdj(); //发生单价
            EditStatus editStatus = fcbgzStore.getEditStatus();
            // 生成实物库存，首先检查实物库存是否存在，如果存在，直接更新，如果不存在则新增一条实物库存
//        String sql = String.format(SqpMapUtil.getSql("QUERY_STOCK_SUM"), unitId,
//                lkbm, ch, hwh, pz, lsxz);
//            List<Map<String, Object>> list = dataKcglCplkcswDefaultMapper.queryStockSum( unitId,
//                    ch, hwh, pz, lsxz);
            QueryWrapper<DataKcglCplkcswDefault> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("unitid",unitId);
            queryWrapper.eq("ch",ch);
            queryWrapper.eq("hwh",hwh);
            queryWrapper.eq("xz",lsxz);
            queryWrapper.eq("sjjlppbh",pp);
            queryWrapper.eq("sjjlpzbh",pz);
            queryWrapper.eq("sjjlspmcbh",mxpz);
            queryWrapper.eq("scpc",scpc);
            queryWrapper.eq("gg",gg);
            queryWrapper.last("limit 1");
            DataKcglCplkcswDefault kcglCplkcswDefault = super.getOne(queryWrapper);
            if (kcglCplkcswDefault != null) {
                //修改实物前要检测是实物库存的  库存数量在修改后是否大于0 如果大于0 则修改， 小于0 或者等于0 则删除本条数据
                Double kcsl = kcglCplkcswDefault.getKcsl(); //得到库存数量
                Double js = kcglCplkcswDefault.getJs(); //得到库存件数
                Double zje = kcglCplkcswDefault.getZje(); //得到总金额
                String dataId = kcglCplkcswDefault.getDataId();
                if (kcsl+stockNum < 1.0) { // stockNum 在入库为正，出库时为负，所以直接相加即可,因存在小数舍位情况
                    if (editStatus != EditStatus.Modified || (editStatus == EditStatus.Modified && fcbgzStore.getSaveFcbgz())) { //为负数则直接删除
//                    boolean flag = executeUpdate(String.format(SqpMapUtil.getSql("DELETE_STOCK_KCSW"),dataId));
                        boolean flag = super.removeById(dataId);
//                    if (flag) { //保存库存实物删除记录
                    if (flag) { //保存库存实物删除记录
                       deleteDataRecordService.save(dataId,"data_kcgl_cplkcsw_default",kcglCplkcswDefault.getUnitid(),new Date());
                    }
                        return flag;
                    }
                }
                // 修改实物库存数量
//            sql = String.format(SqpMapUtil.getSql("UPDATE_STORE_BY_BIZ"), stockNum,
//                    unitId, lkbm, ch, hwh, pz, lsxz);
//                UPDATE data_kcgl_kcsw_default SET kcsl=kcsl + (${stockNum}),zje=zje + (${fsje}),ModifyDate=NOW(),UPDATE_TIME=null
//		WHERE  unitId=#{unitId}
//		AND ifnull(ch,'')=#{ch} AND ifnull(hwh,'')=#{hwh} AND ifnull(pz,'')=#{pz} AND ifnull(hwxz,'')=#{hwxz}
                kcglCplkcswDefault.setKcsl(kcsl+stockNum);
                Double stockJs = stockNum/Double.parseDouble(gg); //变动件数
                kcglCplkcswDefault.setJs(js+stockJs);
                kcglCplkcswDefault.setZje(zje+(stockNum*kcdj/Double.parseDouble(gg))); // 金额 = 数量*单价/规格
                kcglCplkcswDefault.setUpdateTime(null);
                kcglCplkcswDefault.setModifyDate(new Date());
                if (!super.updateById(kcglCplkcswDefault))   return false;
            } else {
                // 新增实物库存
//            sql = String.format(SqpMapUtil.getSql("ADD_STORE_BY_XCKC"), stockNum,
//                    selectDataId);
                // 金额 = 数量*单价/规格
                if (stockNum < 0 ){ //新增的库存数量小于0，直接报错，不让保存
                    return false;
                }
                if (dataKcglCplkcswDefaultMapper.addStoreByXckc(stockNum,stockNum*kcdj/Double.parseDouble(gg),selectDataId) <0 )
                    return false;
            }

            return true;

        }
    }

    @Override
    public List<Map<String, Object>> getKcswInfoBySpbh(String hwh, String spbh, String gg) {
        return  dataKcglCplkcswDefaultMapper.getKcswInfoBySpbh(hwh,spbh,gg);
    }

    @Override
    public List<Map<String, Object>> getKcswInfoByHwh(String hwh) {
        return  dataKcglCplkcswDefaultMapper.getKcswInfoByHwh(hwh);
    }

    /**
     * 根据商品编号，规格查询库存对应的仓房相关信息
     *
     * @param unitid
     * @param ppbh
     * @param pzbh
     * @param spbh
     * @param gg
     * @return
     */
    @Override
    public List<Map<String, Object>> getChInfo(String unitid, String ppbh, String pzbh, String spbh, String gg) {
        return dataKcglCplkcswDefaultMapper.getChInfo(unitid,ppbh,pzbh,spbh,gg);
    }

    /**
     * 根据仓房查询库存对应的库存相关信息
     *
     * @param ch
     * @return
     */
    @Override
    public List<Map<String, Object>> getKcswInfoByCh(String ch) {
        return  dataKcglCplkcswDefaultMapper.getKcswInfoByCh(ch);
    }

    /**
     * 得到仓房信息以及库存总件数
     *
     * @param unitid
     * @return
     */
    @Override
    public List<Map<String, Object>> getChSumInfo(String unitid) {
        return  dataKcglCplkcswDefaultMapper.getChSumInfo(unitid);
    }

    @Override
    public IPage<Map<String, Object>> findPageKcyj(DataKcglCplkcswDefaultVo pageQuery) {
        //条形查询器
        QueryWrapper<DataKcglCplkcswDefault> queryWrapper = new QueryWrapper<>();
        if(StringUtils.isNotBlank(pageQuery.getUnitId())){
            queryWrapper.eq("kc.unitid",pageQuery.getUnitId());
        }
        if(StringUtils.isNotBlank(pageQuery.getSjjlspmc())){
            queryWrapper.like("kc.sjjlspmc", ResultUtil.getQueryWrapperformat(pageQuery.getSjjlspmc()));
        }
        if(StringUtils.isNotBlank(pageQuery.getCh())){
            queryWrapper.like("kc.ch", ResultUtil.getQueryWrapperformat(pageQuery.getCh()));
        }
        if(StringUtils.isNotBlank(pageQuery.getHwh())){
            queryWrapper.like("kc.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("kc.cjsj");
        //分页相关
        Page<DataKcglCplkcswDefault> p =new Page<>(pageQuery.getPage(),pageQuery.getLimit());
        IPage<Map<String,Object>> page =dataKcglCplkcswDefaultMapper.findPageKcyj(p,queryWrapper);
        return page;
    }

}
