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.common.service.IDeleteDataRecordService;
import com.unis.crk.cplbusiness.entity.*;
import com.unis.crk.cplbusiness.mapper.DataCrkywCplckFlt001Mapper;
import com.unis.crk.cplbusiness.service.*;
import com.unis.crk.enums.EditStatus;
import com.unis.crk.enums.StoreWorkType;
import com.unis.crk.utils.FunUtils;
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 static cn.hutool.core.text.CharSequenceUtil.hasBlank;

/**
 * <p>
 * 成品粮出库从表 服务实现类
 * </p>
 *
 * @author TangSong
 * @since 2022-04-08
 */
@Service
public class DataCrkywCplckFlt001ServiceImpl extends ServiceImpl<DataCrkywCplckFlt001Mapper, DataCrkywCplckFlt001> implements IDataCrkywCplckFlt001Service {

    @Resource
    private DataCrkywCplckFlt001Mapper dataCrkywCplckFlt001Mapper;
    @Autowired
    private IDataKcglCplxckcDefaultService dataKcglCplxckcDefaultService;
    @Autowired
    private IDataKcglCplfcbgzDefaultService dataKcglCplfcbgzDefaultService;
    @Autowired
    private IDataKcglCplkcswDefaultService dataKcglCplkcswDefaultService;
    @Autowired
    private IDataCrkywCpltzdxxDefaultService dataCrkywCpltzdxxDefaultService;
    @Autowired
    private IDataCrkywCpltzdxxFlt001Service dataCrkywCpltzdxxFlt001Service;
    @Autowired
    private IDataCrkywCplckDefaultService dataCrkywCplckDefaultService;
    @Autowired
    private IDeleteDataRecordService deleteDataRecordService;

    @Override
    @SystemLog(module = "成品通知单", methods = "修改",uploadName = "cpl.tzd")
    public JSONObject saveFlt(DataCrkywCplckFlt001 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 loginName = flt001.getBuilder();//创建人
        String matherId = flt001.getDataId();
        String unitId = flt001.getUnitid();

        jsonObject1 = isOutWarehouseCapacity(flt001.getDataId(),0-flt001.getSjjlsl());
        if (!jsonObject1.getBool("success")) {
            throw new Exception(jsonObject1.get("msg").toString());
        }
        //保存库存相关数据
        EditStatus editStatus = EditStatus.New;
        Boolean b = dataKcglCplxckcDefaultService.makeStockDetail(matherId,unitId,loginName,editStatus,StoreWorkType.Out);
        if (!b) {
            throw new RuntimeException(flt001.getSjjlspmc()+":保存仓储数据失败");
        }

        //更新通知单
        String ddcbid = flt001.getDdcbid();
        if(!hasBlank(ddcbid)){
            DataCrkywCpltzdxxFlt001 byId = dataCrkywCpltzdxxFlt001Service.getById(ddcbid);
            if (byId != null) {
                Double sysl = byId.getSysl();
                Double wcsl = byId.getWcsl();
                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(DataCrkywCplckFlt001 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("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()+":修改成品粮从表出库失败");
        }
        jsonObject1 = isOutWarehouseCapacity(flt001.getDataId(),editZl);
        if (!jsonObject1.getBool("success")) {
            throw new Exception(jsonObject1.get("msg").toString());
        }
        Boolean b = dataKcglCplxckcDefaultService.makeStockDetail(dataId, unitid, builder, editStatus, StoreWorkType.Out);
        if (!b) {
            throw new RuntimeException(flt001.getSjjlpzmc()+":保存仓储数据失败");
        }

        String ddcbid = flt001.getDdcbid();
        if(!hasBlank(ddcbid)){
            DataCrkywCpltzdxxFlt001 byId = dataCrkywCpltzdxxFlt001Service.getById(ddcbid);
            if (byId != null){
                Double sysl = byId.getSysl();
                Double wcsl = byId.getWcsl();
                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);
        //得到对象
        DataCrkywCplckFlt001 entity = super.getById(id);
        if (entity == null) {
            jsonObject.set("msg", "此数据已被删除");
            return jsonObject;
        }
        String ddcbid = entity.getDdcbid();
        Double sjjlsl = entity.getSjjlsl();

        JSONObject jsonObject1 = beforEditOrDelete(entity.getDataId(), false);//判断库存
        if (jsonObject1.get("success").equals("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;
        }
        deleteDataRecordService.save(id,"data_crkyw_cplck_flt_001",entity.getUnitid(),new Date());
        //更新库存相关数据
        String unitid = entity.getUnitid();
        EditStatus editStatus = EditStatus.Deleted;
        Boolean b = dataKcglCplxckcDefaultService.makeStockDetail(id, unitid, entity.getBuilder(), editStatus, StoreWorkType.Out);
        if (!b) {
            jsonObject.set("msg", entity.getSjjlspmc()+":删除仓储数据失败");
            throw new RuntimeException(entity.getSjjlspmc()+":删除仓储数据失败");
        }
        if(!hasBlank(ddcbid)){
            DataCrkywCpltzdxxFlt001 byId = dataCrkywCpltzdxxFlt001Service.getById(ddcbid);
            if (byId != null){
                Double sysl = byId.getSysl();
                Double wcsl = byId.getWcsl();
                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 zcsl = dataKcglCplfcbgzDefault.getZcsl();
            Double srsl = dataKcglCplfcbgzDefault.getSrsl();
            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 ? (oldZl-Double.valueOf(zl) ) :  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 { //表示新增
           /* Double editZl;
            //得到新重量
            Double zl = super.getById(dataId).getSjjlsl();
            editZl = zl;

            jsonObject.set("editZl", editZl);*/
        }
        return jsonObject;
    }

    // 出库仓容判断
    public JSONObject isOutWarehouseCapacity(String dataId,Double editZl){
        JSONObject jsonObject = new JSONObject();
        jsonObject.set("success", false);
        DataCrkywCplckFlt001 flt001  = super.getById(dataId);
        DataCrkywCplckDefault dataCrkywCplckDefault  = dataCrkywCplckDefaultService.getById(flt001.getMainDataId());
        String sjjlpzbh = flt001.getSjjlpzbh();//品种编号
        String sjjlppbh = flt001.getSjjlppbh();//品牌编号
        String sjjlspmcbh = flt001.getSjjlspmcbh();//商品名称编号
        String scpc = flt001.getScpc();//生产批次
        String xz = flt001.getXz();//性质
        String ch = dataCrkywCplckDefault.getCh();//仓房
        String hw = dataCrkywCplckDefault.getHwh();//货位
        String gg = flt001.getGg();//规格
        String jldw = flt001.getJldw();//计量单位

        QueryWrapper<DataKcglCplkcswDefault> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("unitid", flt001.getUnitid());
        queryWrapper.eq("ch", ch);
        queryWrapper.eq("hwh", hw);
        queryWrapper.eq("sjjlpzbh", sjjlpzbh);
        queryWrapper.eq("xz", xz);
        queryWrapper.eq("sjjlppbh", sjjlppbh);
        queryWrapper.eq("sjjlspmcbh", sjjlspmcbh);
        queryWrapper.eq("scpc", scpc);
        queryWrapper.eq("gg", gg);
        List<DataKcglCplkcswDefault> dataKcglCplkcswDefaults  =dataKcglCplkcswDefaultService.list(queryWrapper);
        if ( dataKcglCplkcswDefaults.size() == 1){
            DataKcglCplkcswDefault kcglCplkcswDefault = dataKcglCplkcswDefaults.get(0);
            if (kcglCplkcswDefault.getKcsl()+editZl < 0){
                jsonObject.set("msg",flt001.getSjjlspmc()+":库存为"+dataKcglCplkcswDefaults.get(0).getKcsl()+"，不能出库");
                return  jsonObject;
            }
        }else{
            jsonObject.set("msg",flt001.getSjjlspmc()+":库存为0，不能出库");
            return  jsonObject;
        }
        jsonObject.set("success",true);
        return  jsonObject;
    }
}
