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

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.aop.SystemLog;
import com.unis.crk.business.kcgl.entity.DataKcglFcbgzDefault;
import com.unis.crk.business.kcgl.entity.DataKcglKcswDefault;
import com.unis.crk.business.kcgl.entity.FcbgzStore;
import com.unis.crk.business.kcgl.entity.Store;
import com.unis.crk.business.kcgl.entity.vo.DataKcglKcswDefaultVo;
import com.unis.crk.business.kcgl.mapper.DataKcglKcswDefaultMapper;
import com.unis.crk.business.kcgl.service.IDataKcglFcbgzDefaultService;
import com.unis.crk.business.kcgl.service.IDataKcglKcswDefaultService;
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 DataKcglKcswDefaultServiceImpl extends ServiceImpl<DataKcglKcswDefaultMapper, DataKcglKcswDefault> implements IDataKcglKcswDefaultService {

    @Resource
    private DataKcglKcswDefaultMapper dataKcglKcswDefaultMapper;
    @Autowired
    private IDataKcglFcbgzDefaultService dataKcglFcbgzDefaultService;
    @Autowired
    private IDeleteDataRecordService deleteDataRecordService;
    /**
     * 按照条件查询库存管理-库存实物表信息
     * @param pageQuery
     * @throws Exception
     */
    @Override
    public IPage<Map<String,Object>> findPageVo(DataKcglKcswDefaultVo pageQuery){
        {
        //条形查询器
        QueryWrapper<DataKcglKcswDefault> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(pageQuery.getBizNo())){
        queryWrapper.like("bizNo",pageQuery.getBizNo());
        }
        //分页相关
        Page<DataKcglKcswDefault> p =new Page<>(pageQuery.getPage(),pageQuery.getLimit());

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

    @Override
    @SystemLog(module = "原粮库存", methods = "库存",uploadName = "yuliang.kcbd")
    public boolean changeKCSW(String unitId, String selectDataId, Store store, FcbgzStore fcbgzStore, Double stockNum, boolean byBeginning) {

        String lkbm = store.getLkbm(); //粮库编码
        String ch =  store.getCf(); //仓房
        String hwh = store.getHwh(); //货位
        String pz = store.getPz();//粮食品种
        String lsxz = store.getLsxz();//粮食性质
        EditStatus editStatus = fcbgzStore.getEditStatus();
        // 生成实物库存，首先检查实物库存是否存在，如果存在，直接更新，如果不存在则新增一条实物库存
//        String sql = String.format(SqpMapUtil.getSql("QUERY_STOCK_SUM"), unitId,
//                lkbm, ch, hwh, pz, lsxz);
        List<Map<String, Object>> list = dataKcglKcswDefaultMapper.queryStockSum( unitId,
                 ch, hwh, pz, lsxz);
        if (list.size() > 0) {
            if (list.size() != 1) { //表示满足条件的实物库存不止一条
                return false;
            }
            //修改实物前要检测是实物库存的  库存数量在修改后是否大于0 如果大于0 则修改， 小于0 或者等于0 则删除本条数据
            Double kcsl = Double.parseDouble(list.get(0).get("kcsl").toString()); //得到库存数量
            String dataId = list.get(0).get("dataid").toString();
            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) { //保存库存实物删除记录
                        deleteDataRecordService.saveKcsw(dataId,unitId,new Date());
                    }
                    return flag;
                }
            }
            // 修改实物库存数量
//            sql = String.format(SqpMapUtil.getSql("UPDATE_STORE_BY_BIZ"), stockNum,
//                    unitId, lkbm, ch, hwh, pz, lsxz);
            int i = dataKcglKcswDefaultMapper.updateStoreByBiz(stockNum, unitId, ch, hwh, pz, lsxz);
            if (i < 0)
                return false;
        } else {
            // 新增实物库存
//            sql = String.format(SqpMapUtil.getSql("ADD_STORE_BY_XCKC"), stockNum,
//                    selectDataId);
            if (dataKcglKcswDefaultMapper.addStoreByXckc(stockNum,selectDataId) <0 )
                return false;
        }

        return true;

    }
//    private boolean UpdateWrapper(String unitId, String cf, String hwh, String pz, String lsxz)
    @Override
    public List<Map<String, Object>> queryStockDetail(String dataId) {
        return dataKcglKcswDefaultMapper.queryStockDetail(dataId);
    }

    @Override
    public List<Map<String, Object>> queryStockSum(String unitId, String cf, String hwh, String pz, String lsxz) {
        return dataKcglKcswDefaultMapper.queryStockSum(unitId,cf,hwh,pz,lsxz);
    }

    /**
     * 修改库存实物入仓时间为最后一次修改时间
     * @param unitId
     * @param selectDataId
     * @param store
     * @param workType
     * @return
     */
    @SuppressWarnings("unchecked")
    public boolean updateKcswRcsj(String unitId, String selectDataId,Store store,StoreWorkType workType) {
//        String dqVersion = BaseAction.getSql("dqVersion");
//        //天津地区使用第一次入库时间
//        if(StringUtils.isNotBlank(dqVersion) && "tj".equals(dqVersion)){
//            return true;
//        }
        //不更新rq字段
        if (StringUtils.isBlank(unitId)){
            return  true;
        }
        String ch =  store.getCf(); //仓房
        String hwh = store.getHwh(); //货位
        String pz = store.getPz();//粮食品种
        String lsxz = store.getLsxz();//粮食性质

//        String sql = String.format(SqpMapUtil.getSql("QUERY_FCBGZ_RQ"),FunUtils.DATE_FORMAT_LONG, unitId,
//                ch, hwh, pz, lsxz);
        QueryWrapper<DataKcglFcbgzDefault> queryWrapper  = new QueryWrapper<>();
        queryWrapper.eq("unitId",unitId);
        queryWrapper.eq("ch",ch);
        queryWrapper.eq("hwh",hwh);
        queryWrapper.eq("pz",pz);
        queryWrapper.eq("hwxz",lsxz);
        queryWrapper.orderByDesc("ModifyDate");
        queryWrapper.last( " limit 0,1");
        DataKcglFcbgzDefault dataKcglFcbgzDefault = dataKcglFcbgzDefaultService.getOne(queryWrapper,false);

        if (dataKcglFcbgzDefault != null ) { //表示还有分库保管账数据
//            String rq = list.get(0).get("rq").toString();
//            sql = String.format(SqpMapUtil.getSql("UPDATE_RCSJ_BY_BIZ"), rq,
//                    unitId, lkbm, ch, hwh, pz, lsxz);
//            if (!this.executeUpdate(sql))
            UpdateWrapper<DataKcglKcswDefault> 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("rq", dataKcglFcbgzDefault.getRq());
            updateWrapper.set("UPDATE_TIME", null);
            if(!super.update(updateWrapper))
                return false;
        }
        return true;
    }
}
