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

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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.DataKcglQckcDefault;
import com.unis.crk.business.kcgl.entity.vo.DataKcglQckcDefaultVo;
import com.unis.crk.business.kcgl.mapper.DataKcglQckcDefaultMapper;
import com.unis.crk.business.kcgl.service.IDataKcglFcbgzDefaultService;
import com.unis.crk.business.kcgl.service.IDataKcglKcswDefaultService;
import com.unis.crk.business.kcgl.service.IDataKcglQckcDefaultService;
import com.unis.crk.business.kcgl.service.IDataKcglXckcDefaultService;
import com.unis.crk.business.qcck.entity.DataCrkywCkcmzDefault;
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 org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Map;

/**
 * <p>
 * 库存管理-期初库存 服务实现类
 * </p>
 *
 * @author TangSong
 * @since 2021-12-21
 */
@Service
public class DataKcglQckcDefaultServiceImpl extends ServiceImpl<DataKcglQckcDefaultMapper, DataKcglQckcDefault> implements IDataKcglQckcDefaultService {

    @Resource
    private DataKcglQckcDefaultMapper dataKcglQckcDefaultMapper;

    @Autowired
    private IDataKcglKcswDefaultService dataKcglKcswDefaultService;
    @Autowired
    private IDataKcglXckcDefaultService dataKcglXckcDefaultService;
    @Autowired
    private IDataKcglFcbgzDefaultService dataKcglFcbgzDefaultService;
    @Autowired
    private IDeleteDataRecordService deleteDataRecordService;

    /**
     *保存库存管理-期初库存
     * @param qckc 库存管理-期初库存业务数据
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @SystemLog(module = "原粮期初", methods = "新增",uploadName = "yuliang.qc")
    public JSONObject saveQckc(DataKcglQckcDefault qckc) throws  Exception{
        JSONObject jsonObject = new JSONObject();
        jsonObject.set("success",false);
        //检验库存
        Boolean a = kcsw_add(qckc);
        if(!a){
            throw new RuntimeException("该仓房货位已被使用或该品种性质已存在该仓房货位中，不可添加");
        }
        qckc.setSytelInfoID("4028816964a5eeff0164a76caeab045f"); //样式id
        qckc.setPeriodID("12"); //期间id
        qckc.setDeptID(qckc.getUnitID());//部门id
        qckc.setRoundID(0); //舍位id
        qckc.setCjsj(new Date());// 使用当前时间
        if (StringUtils.isBlank(qckc.getBuilder())){
            qckc.setBuilder(qckc.getUnitID());
            qckc.setEditor(qckc.getUnitID());
        }
        //保存数据
        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 = dataKcglXckcDefaultService.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)
    @SystemLog(module = "原粮期初", methods = "修改",uploadName = "yuliang.qc")
    public JSONObject update(DataKcglQckcDefault qckc)throws  Exception{
        JSONObject jsonObject = new JSONObject();
        jsonObject.set("success",false);
        //检验库存
        jsonObject  = kcsw_update(qckc);
        if(!jsonObject.getBool("success")){
            throw new RuntimeException(jsonObject.getStr("msg"));
        }
        //保存数据
        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 = dataKcglXckcDefaultService.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)
    @SystemLog(module = "原粮期初", methods = "删除",uploadName = "yuliang.qc")
    public JSONObject delete(String id)throws  Exception{
        {
            JSONObject jsonObject = new JSONObject();
            jsonObject.set("success",false);
            //得到对象
            DataKcglQckcDefault 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 = dataKcglXckcDefaultService.makeStockDetail(matherId, unitId, loginName, editStatus, StoreWorkType.QCKC);
            if (!b) {
                throw new RuntimeException("保存仓储数据失败");
            }
            //保存删除数据记录
            deleteDataRecordService.save(id,"data_kcgl_qckc_default",unitId,new Date());
            jsonObject.set("success", true);
            jsonObject.set("msg", "删除成功");
            return jsonObject;
        }
     }

    /**
     * 按照条件查询库存管理-期初库存信息
     * @param pageQuery
     * @throws Exception
     */
    @Override
    public IPage<Map<String,Object>> findPageVo(DataKcglQckcDefaultVo pageQuery){
        //条形查询器
        QueryWrapper<DataKcglQckcDefault> queryWrapper = new QueryWrapper<>();
            if (StringUtils.isNotBlank(pageQuery.getUnitId())){
                queryWrapper.eq("DATA_KCGL_QCKC_DEFAULT.UnitId",pageQuery.getUnitId());
            }
            if (StringUtils.isNotBlank(pageQuery.getLspz())){
                queryWrapper.eq("DATA_KCGL_QCKC_DEFAULT.pz",pageQuery.getLspz());
            }
            if (StringUtils.isNotBlank(pageQuery.getRqStart()) && StringUtils.isNotBlank(pageQuery.getRqEnd())) {
                queryWrapper.apply(" DATE_FORMAT(ifnull(DATA_KCGL_QCKC_DEFAULT.rq,NOW()),'%Y-%m-%d') >=  '" + pageQuery.getRqStart() + "' AND DATE_FORMAT(ifnull(DATA_KCGL_QCKC_DEFAULT.rq,NOW()),'%Y-%m-%d') <= '" + pageQuery.getRqEnd() + " 23:59:59'");
            }
            queryWrapper.orderByDesc("DATA_KCGL_QCKC_DEFAULT.cjsj");
        //分页相关
        Page<DataKcglQckcDefault> p =new Page<>(pageQuery.getPage(),pageQuery.getLimit());

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

    @Override
    public Map<String, Object> getOneQckc(String id) {
        Map<String,Object> map = dataKcglQckcDefaultMapper.getOneQckc(id);

        return map;
    }

    private boolean kcsw_add(DataKcglQckcDefault qckc){
        String ch = qckc.getCh();
        String hwh = qckc.getHwh();
        String hwxz = qckc.getHwxz();
        String pz = qckc.getPz();
        String unitId = qckc.getUnitID();
        QueryWrapper<DataKcglKcswDefault> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ch",ch);
        queryWrapper.eq("hwh",hwh);
        queryWrapper.eq("unitId",unitId);
        queryWrapper.last("limit 1");
        //表示此仓房货位已有数据
        DataKcglKcswDefault one = dataKcglKcswDefaultService.getOne(queryWrapper);
        if (one != null){
            //表示此时与仓房货位的品种、性质不一致
            if (!StringUtils.equals(one.getHwxz(),hwxz) || !StringUtils.equals(one.getPz(),pz))
            return false;
        }
        return true;
    }
    private JSONObject kcsw_update(DataKcglQckcDefault qckc){
        JSONObject jsonObject = new JSONObject();
       /* String ch = qckc.getCh();
        String hwh = qckc.getHwh();
        String hwxz = qckc.getHwxz();
        String pz = qckc.getPz();
        String unitId = qckc.getUnitID();
        QueryWrapper<DataKcglQckcDefault> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ch",ch);
        queryWrapper.eq("hwh",hwh);
        queryWrapper.eq("unitId",unitId);
        //排除自己
        queryWrapper.ne("dataId",qckc.getDataID());
        queryWrapper.last("limit 1");
        //表示期初中此仓房货位已有数据
        DataKcglQckcDefault one = super.getOne(queryWrapper,false);
        if (one != null){
            jsonObject.set("msg","该仓房货位已被使用或该品种性质已存在该仓房货位中，不可修改");
            return jsonObject;
        }
        DataKcglQckcDefault oldQckc = super.getById(qckc.getDataID()); //得到以前重量

        String date =  DateUtil.format(qckc.getRc(),"yyyy-MM-dd HH:mm:ss");
        Double editZl = qckc.getKcsl()-oldQckc.getKcsl(); //变动数量
        //查询分库保管中变动数量
        QueryWrapper<DataKcglFcbgzDefault> fcbgzWrapper = new QueryWrapper<>();
        fcbgzWrapper.eq("unitId", unitId);
        fcbgzWrapper.eq("ch", ch);
        fcbgzWrapper.eq("hwh", hwh);
        fcbgzWrapper.eq("pz", pz);
        fcbgzWrapper.eq("hwxz", hwxz);
        fcbgzWrapper.ge("rq", date);
        fcbgzWrapper.lt("kcsl+" + editZl, 0); //修改后的库存数量小于0
        fcbgzWrapper.ne("dataId", qckc.getDataID());
        fcbgzWrapper.orderByDesc("rq");
        if (dataKcglFcbgzDefaultService.list(fcbgzWrapper).size() > 0) {
            jsonObject.set("msg", "当前仓房有其它业务，不可操作");
            return jsonObject;
        }
        jsonObject.set("success",true);*/
        jsonObject.set("success",false);
        DataKcglQckcDefault oldQckc = super.getById(qckc.getDataID()); //得到以前数据
        QueryWrapper<DataKcglFcbgzDefault> fcbgzWrapper = new QueryWrapper<>();
        fcbgzWrapper.eq("unitId", oldQckc.getUnitID());
        fcbgzWrapper.eq("hwh", oldQckc.getHwh());
        if (dataKcglFcbgzDefaultService.list(fcbgzWrapper).size() > 1) {
            jsonObject.set("msg", "当前货位有其它业务，不可操作");
            return jsonObject;
        }
        jsonObject.set("success",true);
        return jsonObject;
    }
    private JSONObject kcsw_delete(DataKcglQckcDefault qckc){
        JSONObject jsonObject = new JSONObject();
        jsonObject.set("success",false);
        DataKcglQckcDefault oldQckc = super.getById(qckc.getDataID()); //得到以前数据
        QueryWrapper<DataKcglFcbgzDefault> fcbgzWrapper = new QueryWrapper<>();
        fcbgzWrapper.eq("hwh", oldQckc.getHwh());
        fcbgzWrapper.eq("unitId", oldQckc.getUnitID());
        if (dataKcglFcbgzDefaultService.list(fcbgzWrapper).size() > 1) {
            jsonObject.set("msg", "当前货位有其它业务，不可操作!");
            return jsonObject;
        }
        jsonObject.set("success",true);
        /*String ch = qckc.getCh();
        String hwh = qckc.getHwh();
        String hwxz = qckc.getHwxz();
        String pz = qckc.getPz();
        String unitId = qckc.getUnitID();

        String date =  DateUtil.format(qckc.getRc(),"yyyy-MM-dd HH:mm:ss");
        Double editZl = 0-qckc.getKcsl(); //变动数量
        //查询分库保管中变动数量
        QueryWrapper<DataKcglFcbgzDefault> fcbgzWrapper = new QueryWrapper<>();
        fcbgzWrapper.eq("unitId", unitId);
        fcbgzWrapper.eq("ch", ch);
        fcbgzWrapper.eq("hwh", hwh);
        fcbgzWrapper.eq("pz", pz);
        fcbgzWrapper.eq("hwxz", hwxz);
        fcbgzWrapper.ge("rq", date);
        fcbgzWrapper.lt("kcsl+" + editZl, 0); //修改后的库存数量小于0
        fcbgzWrapper.ne("dataId", qckc.getDataID());
        fcbgzWrapper.orderByDesc("rq");
        if (dataKcglFcbgzDefaultService.list(fcbgzWrapper).size() > 0) {
            jsonObject.set("msg", "不可操作，库存数量变为负数");
            return jsonObject;
        }
        jsonObject.set("success",true);*/
        return jsonObject;
    }
}
