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

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.unis.crk.aop.SystemLog;
import com.unis.crk.cplbusiness.entity.*;
import com.unis.crk.cplbusiness.mapper.DataCrkywCplrkFlt001Mapper;
import com.unis.crk.cplbusiness.service.*;
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 static cn.hutool.core.text.CharSequenceUtil.hasBlank;

/**
 * <p>
 * 成品粮入库从表 服务实现类
 * </p>
 *
 * @author TangSong
 * @since 2022-04-08
 */
@Service
public class DataCrkywCplrkFlt001ServiceImpl extends ServiceImpl<DataCrkywCplrkFlt001Mapper, DataCrkywCplrkFlt001> implements IDataCrkywCplrkFlt001Service {

    @Resource
    private DataCrkywCplrkFlt001Mapper dataCrkywCplrkFlt001Mapper;
    @Autowired
    private IDataKcglCplxckcDefaultService dataKcglCplxckcDefaultService;
    @Autowired
    private IDataKcglCplfcbgzDefaultService dataKcglCplfcbgzDefaultService;
    @Autowired
    private IDataCrkywCpltzdxxFlt001Service dataCrkywCpltzdxxFlt001Service;
    @Autowired
    private IDataCrkywCplrkDefaultService dataCrkywCplrkDefaultService;

    @Autowired
    private IDataCrkywCpltzdxxDefaultService dataCrkywCpltzdxxDefaultService;

    @Override
    @SystemLog(module = "成品通知单", methods = "修改",uploadName = "cpl.tzd")
    public JSONObject saveFlt(DataCrkywCplrkFlt001 flt001) throws Exception {
            JSONObject jsonObject = new JSONObject();
            jsonObject.set("success", false);

        if (StrUtil.isNotBlank(flt001.getDataId())){ //新增主键为空
            flt001.setDataId(null);
        }
        JSONObject jsonObject1 = beforEditOrDelete(flt001.getDataId(), false);//判断库存
        if (jsonObject1.get("success").equals("false")) {
                throw new Exception(jsonObject1.get("msg").toString());
            }
        flt001.setDeptId(flt001.getUnitid());//部门id
            if (StringUtils.isBlank(flt001.getBuilder())){
                flt001.setBuilder(flt001.getUnitid());
                flt001.setEditor(flt001.getUnitid());
            }
            //性质默认值
        if(StrUtil.isBlank(flt001.getXz())){
            flt001.setXz("952751");
        }
            //数量=件数*规格
        flt001.setSjjlsl(flt001.getJs()*Double.parseDouble(flt001.getGg()) );
            //金额=数理*单价
        flt001.setJe(flt001.getSjjlsl()*flt001.getDj());
            if (!super.saveOrUpdate(flt001)) { //
                throw new Exception(flt001.getSjjlspmc()+":保存成品粮入库从表失败");
            }
            Double sjjlsl = flt001.getSjjlsl();
            String matherId = flt001.getDataId();
            String unitId = flt001.getUnitid();
            String loginName = flt001.getBuilder();//创建人

            //保存库存相关数据
            EditStatus editStatus = EditStatus.New;
            Boolean b = dataKcglCplxckcDefaultService.makeStockDetail(matherId,unitId,loginName,editStatus,StoreWorkType.In);
            if (!b) {
                throw new RuntimeException(flt001.getSjjlspmc()+":保存仓储数据失败");
            }

            //更新通知单
            String ddcbid = flt001.getDdcbid();
            if(!hasBlank(ddcbid)){
                DataCrkywCpltzdxxFlt001 byId = dataCrkywCpltzdxxFlt001Service.getById(ddcbid);
                if (byId != null) {
                    Double wcsl = byId.getWcsl();
                    Double sysl = byId.getSysl();
                    if (sysl - sjjlsl < 0) {
                        jsonObject.set("msg", flt001.getSjjlspmc() + ":入库数量大于订单数量");
                        throw new RuntimeException(flt001.getSjjlspmc() + ":入库数量大于订单数量");
//                return jsonObject;
                    }

                    byId.setWcsl(wcsl + sjjlsl);//订单从表完成数量增加
                    byId.setSysl(sysl - sjjlsl);//修改订单从平剩余数量
                    dataCrkywCpltzdxxFlt001Service.updateById(byId);
                    //更新主表数量
                    String mainDataId = byId.getMainDataID();
                    DataCrkywCpltzdxxDefault main = dataCrkywCpltzdxxDefaultService.getById(mainDataId);
                    if (main != null){
                        main.setWcsl(main.getWcsl() + sjjlsl);//订单主表完成数量增加
                        main.setSysl(main.getSysl() - sjjlsl);//订单主表剩余数量
                        if(main.getSysl()==0){
                            main.setTsdzt("04");
                        }else{
                            main.setTsdzt("03");
                        }
                        dataCrkywCpltzdxxDefaultService.updateById(main);
                    }
                }
            }
            jsonObject.set("success", true);
            jsonObject.set("msg", "保存成功");
            return jsonObject;
    }

    @Override
    @SystemLog(module = "成品通知单", methods = "修改",uploadName = "cpl.tzd")
    public JSONObject updateFlt(DataCrkywCplrkFlt001 flt001) throws Exception {
        //保存库存相关数据
        JSONObject jsonObject = new JSONObject();
        jsonObject.set("success", false);
        JSONObject jsonObject1 = beforEditOrDelete(flt001.getDataId(), true);//判断库存
        Double editZl = jsonObject1.getDouble("editZl", 0.0); //负得扣量后净重
        if (jsonObject1.get("success").equals("false")) {
            jsonObject.set("success", "false");
            jsonObject.set("msg", jsonObject1.get("msg").toString());
            throw new Exception(jsonObject1.get("msg").toString());
        }
        String dataId = flt001.getDataId();
        String unitid = flt001.getUnitid();
        String builder = flt001.getBuilder();
        EditStatus editStatus = EditStatus.Modified;
        //数量=件数*规格
        flt001.setSjjlsl(flt001.getJs()*Double.parseDouble(flt001.getGg()) );
        //金额=数理*单价
        flt001.setJe(flt001.getSjjlsl()*flt001.getDj());
        if (!super.updateById(flt001)) { //修改成品粮入库
            throw new Exception(flt001.getSjjlpzmc()+":修改成品粮从表入库失败");
        }

        Boolean b = dataKcglCplxckcDefaultService.makeStockDetail(dataId, unitid, builder, editStatus, StoreWorkType.In);
        if (!b) {
            throw new RuntimeException(flt001.getSjjlpzmc()+":保存仓储数据失败");
        }

        String ddcbid = flt001.getDdcbid();
        if(!hasBlank(ddcbid)){
            DataCrkywCpltzdxxFlt001 byId = dataCrkywCpltzdxxFlt001Service.getById(ddcbid);
            if (byId != null){
                Double wcsl = byId.getWcsl();
                Double sysl = byId.getSysl();

                if(sysl-editZl<0){
                    throw new RuntimeException(flt001.getSjjlpzmc()+":入库数量大于订单数量");
                }

                byId.setWcsl(wcsl+editZl);//订单从表完成数量增加
                byId.setSysl(sysl-editZl);//修改订单从平剩余数量
                dataCrkywCpltzdxxFlt001Service.updateById(byId);
                //更新主表数量
                String mainDataId = byId.getMainDataID();
                DataCrkywCpltzdxxDefault main = dataCrkywCpltzdxxDefaultService.getById(mainDataId);
                if (main != null){
                    main.setWcsl(main.getWcsl() + editZl);//订单主表完成数量增加
                    main.setSysl(main.getSysl() - editZl);//订单主表剩余数量
                    if(main.getSysl()==0){
                        main.setTsdzt("04");
                    }else{
                        main.setTsdzt("03");
                    }
                    dataCrkywCpltzdxxDefaultService.updateById(main);
                }
            }
        }
        jsonObject.set("success", true);
        jsonObject.set("msg", "修改成功");
        return jsonObject;
    }

    @Override
    @SystemLog(module = "成品通知单", methods = "修改",uploadName = "cpl.tzd")
    public JSONObject deleteFlt(String id) throws Exception {
        JSONObject jsonObject = new JSONObject();
        jsonObject.set("success", false);
        //得到对象
        DataCrkywCplrkFlt001 entity = super.getById(id);
        if (entity == null) {
            jsonObject.set("msg", "此数据已被删除");
            return jsonObject;
        }
        JSONObject jsonObject1 = beforEditOrDelete(entity.getDataId(), false);//判断库存
        Double editZl = jsonObject1.getDouble("editZl", 0.0); //负得扣量后净重
        if (jsonObject1.get("success").equals("false")) {
            jsonObject.set("success", "false");
            jsonObject.set("msg", jsonObject1.get("msg").toString());
            throw new Exception(jsonObject1.get("msg").toString());
        }
        if (!super.removeById(id)) { //删除成品粮入库数据失败
            jsonObject.set("msg", entity.getSjjlspmc()+":删除成品粮从表入库数据失败");
            return jsonObject;
        }
        //更新库存相关数据
        String unitid = entity.getUnitid();
        EditStatus editStatus = EditStatus.Deleted;
        Boolean b = dataKcglCplxckcDefaultService.makeStockDetail(id, unitid, entity.getBuilder(), editStatus, StoreWorkType.In);
        if (!b) {
            jsonObject.set("msg", entity.getSjjlspmc()+":删除仓储数据失败");
            throw new RuntimeException(entity.getSjjlspmc()+":删除仓储数据失败");
        }
        String ddcbid = entity.getDdcbid();
        Double sjjlsl = entity.getSjjlsl();
        if(!hasBlank(ddcbid)){
            DataCrkywCpltzdxxFlt001 byId = dataCrkywCpltzdxxFlt001Service.getById(ddcbid);
            if (byId != null){
                Double wcsl = byId.getWcsl();
                Double sysl = byId.getSysl();
                byId.setWcsl(wcsl-sjjlsl);//订单从表完成数量减少
                byId.setSysl(sysl+sjjlsl);//修改订单从平剩余数量
                dataCrkywCpltzdxxFlt001Service.updateById(byId);
                //更新主表数量
                String mainDataId = byId.getMainDataID();
                DataCrkywCpltzdxxDefault main = dataCrkywCpltzdxxDefaultService.getById(mainDataId);
                if (main != null){
                    main.setWcsl(main.getWcsl() - sjjlsl);//订单主表完成数量增加
                    main.setSysl(main.getSysl() + sjjlsl);//订单主表剩余数量
                    if(main.getSysl()==0){
                        main.setTsdzt("04");
                    }else{
                        main.setTsdzt("03");
                    }
                    dataCrkywCpltzdxxDefaultService.updateById(main);
                }
            }
        }
        jsonObject.set("success", true);
        jsonObject.set("msg", "删除成功");
        return jsonObject;
    }

    /**
     * 检验是否超入库存数量
     * @param dataId
     * @param isUpdate
     * @return
     */
    public JSONObject beforEditOrDelete(String dataId, Boolean isUpdate) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.set("success", "true");
        jsonObject.set("editZl", 0.0);
        DataKcglCplfcbgzDefault dataKcglCplfcbgzDefault = dataKcglCplfcbgzDefaultService.getById(dataId);
        if (dataKcglCplfcbgzDefault != null) { //表示是修改、删除
            Double srsl = dataKcglCplfcbgzDefault.getSrsl();
            Double zcsl = dataKcglCplfcbgzDefault.getZcsl();
            Double oldZl = Math.abs(srsl - zcsl); //绝对值

            String sjjlpzbh = dataKcglCplfcbgzDefault.getSjjlpzbh();//品种编号
            String sjjlppbh = dataKcglCplfcbgzDefault.getSjjlppbh();//品牌编号
            String sjjlspmcbh = dataKcglCplfcbgzDefault.getSjjlspmcbh();//商品名称编号
            String scpc = dataKcglCplfcbgzDefault.getScpc();//生产批次
            String xz = dataKcglCplfcbgzDefault.getXz();//性质
            String ch = dataKcglCplfcbgzDefault.getCh();//仓房
            String hw = dataKcglCplfcbgzDefault.getHwh();//货位
            String gg = dataKcglCplfcbgzDefault.getGg();//规格
            String jldw = dataKcglCplfcbgzDefault.getJldw();//计量单位

            String date =  DateUtil.format(dataKcglCplfcbgzDefault.getRcrq(),"yyyy-MM-dd HH:mm:ss");
//            String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(dataKcglFcbgzDefault.getRq());
            Double editZl;
            //得到新重量

            Double zl = super.getById(dataId).getSjjlsl();
            editZl = isUpdate ? (Double.valueOf(zl) - oldZl) : (0.0 - Double.valueOf(oldZl)); //修改/删除

            jsonObject.set("editZl", editZl);
            QueryWrapper<DataKcglCplfcbgzDefault> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("unitid", dataKcglCplfcbgzDefault.getUnitid());
            queryWrapper.eq("ch", ch);
            queryWrapper.eq("hwh", hw);
            queryWrapper.eq("sjjlpzbh", sjjlpzbh);
            queryWrapper.eq("xz", xz);
            queryWrapper.ge("rcrq", date);
            queryWrapper.eq("sjjlppbh", sjjlppbh);
            queryWrapper.eq("sjjlspmcbh", sjjlspmcbh);
            queryWrapper.eq("scpc", scpc);
            queryWrapper.eq("gg", gg);
            queryWrapper.lt("kcsl+" + editZl, 0); //修改后的库存数量小于0
            queryWrapper.ne("dataId", dataId);
            queryWrapper.orderByDesc("rcrq");
            if (dataKcglCplfcbgzDefaultService.list(queryWrapper).size() > 0) {
                jsonObject.set("success", "false");
                jsonObject.set("msg", "不可操作，库存数量变为负数");
                return jsonObject;
            }
        } else { //表示新增
        }
        return jsonObject;
    }

}
