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

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.unis.crk.aop.SystemLog;
import com.unis.crk.business.kcgl.entity.DataKcglFcbgzDefault;
import com.unis.crk.business.kcgl.entity.DataKcglQckcDefault;
import com.unis.crk.common.service.IDeleteDataRecordService;
import com.unis.crk.cplbusiness.entity.DataKcglCplfcbgzDefault;
import com.unis.crk.cplbusiness.entity.DataKcglCplqckcDefault;
import com.unis.crk.cplbusiness.mapper.DataKcglCplqckcDefaultMapper;
import com.unis.crk.cplbusiness.service.IDataKcglCplfcbgzDefaultService;
import com.unis.crk.cplbusiness.service.IDataKcglCplqckcDefaultService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.unis.crk.cplbusiness.service.IDataKcglCplxckcDefaultService;
import com.unis.crk.enums.EditStatus;
import com.unis.crk.enums.StoreWorkType;
import com.unis.crk.utils.ResultUtil;
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 org.apache.commons.lang.StringUtils;

import java.util.Date;
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.DataKcglCplqckcDefaultVo;
/**
 * <p>
 * 成品粮期初 服务实现类
 * </p>
 *
 * @author TangSong
 * @since 2022-03-21
 */
@Service
public class DataKcglCplqckcDefaultServiceImpl extends ServiceImpl<DataKcglCplqckcDefaultMapper, DataKcglCplqckcDefault> implements IDataKcglCplqckcDefaultService {

    @Resource
    private DataKcglCplqckcDefaultMapper dataKcglCplqckcDefaultMapper;

    @Autowired
    private IDataKcglCplxckcDefaultService dataKcglCplxckcDefaultService;
    @Autowired
    private IDataKcglCplfcbgzDefaultService dataKcglCplfcbgzDefaultService;
    @Autowired
    private IDeleteDataRecordService deleteDataRecordService;
    /**
     *保存成品粮期初
     * @param qckc 成品粮期初业务数据
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public JSONObject saveQckc(DataKcglCplqckcDefault qckc)throws  Exception {
            JSONObject jsonObject = new JSONObject();
            jsonObject.set("success",false);
            qckc.setCjsj(new Date());// 使用当前时间
            if (StringUtils.isBlank(qckc.getBuilder())){
                qckc.setBuilder(qckc.getUnitid());
                qckc.setEditor(qckc.getUnitid());
            }
            if (StrUtil.isBlank(qckc.getXz())){
                qckc.setXz("952751"); //默认值
            }
            //保存数据
            if (!super.saveOrUpdate(qckc)){
                throw new RuntimeException("保存成品粮期初库存失败");
            }
            String matherId = qckc.getDataId();
            String unitId = qckc.getUnitid();
            String loginName = qckc.getBuilder();//创建人
            //保存库存相关数据
            EditStatus editStatus = EditStatus.New;
            Boolean b = dataKcglCplxckcDefaultService.makeStockDetail(matherId, unitId, loginName, editStatus, StoreWorkType.QCKC);
            if (!b) {
                throw new RuntimeException("保存仓储数据失败");
            }
            jsonObject.set("success", true);
            jsonObject.set("msg", "保存成功");
            return jsonObject;
    }

    /**
     *修改成品粮期初
     * @param qckc 成品粮期初业务数据
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public JSONObject updateQckc(DataKcglCplqckcDefault qckc)throws  Exception{
        JSONObject jsonObject = new JSONObject();
        jsonObject.set("success",false);
        if (StrUtil.isBlank(qckc.getXz())){
            qckc.setXz("952751"); //默认值
        }
        //保存数据
        if (!super.saveOrUpdate(qckc)){
            throw new RuntimeException("保存成品粮期初库存失败");
        }
        String matherId = qckc.getDataId();
        String unitId = qckc.getUnitid();
        String loginName = qckc.getBuilder();//创建人
        //保存库存相关数据
        EditStatus editStatus = EditStatus.Modified;
        Boolean b = dataKcglCplxckcDefaultService.makeStockDetail(matherId, unitId, loginName, editStatus, StoreWorkType.QCKC);
        if (!b) {
            throw new RuntimeException("保存仓储数据失败");
        }
        jsonObject.set("success", true);
        jsonObject.set("msg", "修改成功");
        return jsonObject;
    }
    /**
     *删除成品粮期初数据
     * @param id 成品粮期初主键尖
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public JSONObject deleteQckc(String id) throws  Exception {
            JSONObject jsonObject = new JSONObject();
            jsonObject.set("success",false);
            //得到对象
            DataKcglCplqckcDefault qckc = super.getById(id);
            if (qckc == null) {
                jsonObject.set("msg", "此数据已被删除");
                return jsonObject;
            }
            //检验库存
            jsonObject  = kcsw_delete(qckc);
            if(!jsonObject.getBool("success")){
                throw new RuntimeException(jsonObject.getStr("msg"));
            }
            //保存数据
            if (!super.removeById(id)){
                throw new RuntimeException("删除期初库存失败");
            }
            String matherId = qckc.getDataId();
            String unitId = qckc.getUnitid();
            String loginName = qckc.getBuilder();//创建人
            //保存库存相关数据
            EditStatus editStatus = EditStatus.Deleted;
            Boolean b = dataKcglCplxckcDefaultService.makeStockDetail(matherId, unitId, loginName, editStatus, StoreWorkType.QCKC);
            if (!b) {
                throw new RuntimeException("保存仓储数据失败");
            }
            deleteDataRecordService.save(id,"data_kcgl_cplqckc_default",qckc.getUnitid(),new Date());
            jsonObject.set("success", true);
            jsonObject.set("msg", "删除成功");
            return jsonObject;
    }

    /**
     * 按照条件查询成品粮期初信息
     * @param pageQuery
     * @throws Exception
     */
    @Override
    public IPage<Map<String,Object>> findPageVo(DataKcglCplqckcDefaultVo pageQuery){
        //条形查询器
        QueryWrapper<DataKcglCplqckcDefault> queryWrapper = new QueryWrapper<>();
        if(StringUtils.isNotBlank(pageQuery.getUnitId())){
            queryWrapper.eq("a.unitId",pageQuery.getUnitId());
        }
        if(StringUtils.isNotBlank(pageQuery.getSjjlpzbh())){
            queryWrapper.eq("a.sjjlpzbh",pageQuery.getSjjlpzbh());
        }
        if(StringUtils.isNotBlank(pageQuery.getSjjlspmc())){
            queryWrapper.like("a.sjjlspmc", ResultUtil.getQueryWrapperformat(pageQuery.getSjjlspmc()));
        }
        if (StringUtils.isNotBlank(pageQuery.getJysjStart()) && StringUtils.isNotBlank(pageQuery.getJysjEnd())){
            queryWrapper.apply(" DATE_FORMAT(ifnull(a.rq,NOW()),'%Y-%m-%d') >=  '"+pageQuery.getJysjStart()+"' AND DATE_FORMAT(ifnull(a.rq,NOW()),'%Y-%m-%d') <= '"+pageQuery.getJysjEnd()+" 23:59:59'");

        }
        queryWrapper.orderByDesc("a.rq");
        //分页相关
        Page<DataKcglCplqckcDefault> p =new Page<>(pageQuery.getPage(),pageQuery.getLimit());

        IPage<Map<String,Object>> page = dataKcglCplqckcDefaultMapper.selectMyMapsPage(p,queryWrapper);
        return page;
    }
    private JSONObject kcsw_delete(DataKcglCplqckcDefault qckc){
        JSONObject jsonObject = new JSONObject();
        jsonObject.set("success",false);
        String ch = qckc.getCh(); //仓房
        String hwh = qckc.getHwh(); //货位
        String hwxz = qckc.getXz();//性质
        String pp = qckc.getSjjlppbh(); //品牌
        String pz = qckc.getSjjlpzbh(); //品种
        String mxpz = qckc.getSjjlspmcbh(); //明细品种
        String scpc = qckc.getScpc(); //生产批次
        String gg = qckc.getGg(); //规格
        String unitId = qckc.getUnitid();

        String date =  DateUtil.format(qckc.getRq(),JSON.DEFFAULT_DATE_FORMAT);
        Double editZl = 0-qckc.getKcsl(); //变动数量
        //查询分库保管中变动数量
        QueryWrapper<DataKcglCplfcbgzDefault> fcbgzWrapper = new QueryWrapper<>();
        fcbgzWrapper.eq("unitId", unitId);
        fcbgzWrapper.eq("ch", ch);
        fcbgzWrapper.eq("hwh", hwh);
        fcbgzWrapper.eq("xz", hwxz);
        fcbgzWrapper.eq("sjjlppbh", pp);
        fcbgzWrapper.eq("sjjlpzbh", pz);
        fcbgzWrapper.eq("sjjlspmcbh", mxpz);
        fcbgzWrapper.eq("scpc", scpc);
        fcbgzWrapper.eq("gg", gg);
        fcbgzWrapper.ge("rcrq", date);
        fcbgzWrapper.lt("kcsl+" + editZl, 0); //修改后的库存数量小于0
        fcbgzWrapper.ne("dataId", qckc.getDataId());
        fcbgzWrapper.orderByDesc("rcrq");
        if (dataKcglCplfcbgzDefaultService.list(fcbgzWrapper).size() > 0) {
            jsonObject.set("msg", "不可操作，库存数量变为负数");
            return jsonObject;
        }
        jsonObject.set("success",true);
        return jsonObject;
    }
}
