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

import cn.hutool.core.date.DateUtil;
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.SystemCountryLog;
import com.unis.crk.aop.SystemLog;
import com.unis.crk.basic.entity.BasicEnum;
import com.unis.crk.basic.service.IBasicEnumService;
import com.unis.crk.business.kcgl.entity.DataKcglFcbgzDefault;
import com.unis.crk.business.kcgl.entity.DataKcglKcbdDefault;
import com.unis.crk.business.kcgl.entity.DataKcglKcswDefault;
import com.unis.crk.business.kcgl.entity.vo.DataKcglKcbdDefaultVo;
import com.unis.crk.business.kcgl.mapper.DataKcglKcbdDefaultMapper;
import com.unis.crk.business.kcgl.service.IDataKcglFcbgzDefaultService;
import com.unis.crk.business.kcgl.service.IDataKcglKcbdDefaultService;
import com.unis.crk.business.kcgl.service.IDataKcglKcswDefaultService;
import com.unis.crk.business.kcgl.service.IDataKcglXckcDefaultService;
import com.unis.crk.common.service.IDeleteDataRecordService;
import com.unis.crk.enums.EditStatus;
import com.unis.crk.enums.StoreWorkType;
import com.unis.crk.utils.ResultUtil;
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 2022-02-07
 */
@Service
public class DataKcglKcbdDefaultServiceImpl extends ServiceImpl<DataKcglKcbdDefaultMapper, DataKcglKcbdDefault> implements IDataKcglKcbdDefaultService {

    @Resource
    private DataKcglKcbdDefaultMapper dataKcglKcbdDefaultMapper;
    @Autowired
    private IBasicEnumService basicEnumService;
    @Autowired
    private IDataKcglXckcDefaultService dataKcglXckcDefaultService;
    @Autowired
    private IDataKcglFcbgzDefaultService dataKcglFcbgzDefaultService;
    @Autowired
    private IDataKcglKcswDefaultService dataKcglKcswDefaultService;
    @Autowired
    private IDeleteDataRecordService deleteDataRecordService;
    /**
     *保存库存管理-库存变动
     * @param kcbd 库存管理-库存变动业务数据
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
//    @SystemLog(module = "原粮库存变动", methods = "库存",uploadName = "yuliang.kcbd")
    @SystemCountryLog(module = "原粮库存变动", methods = "新增",uploadName = "yuliang.kcbd")
    public JSONObject saveKcbd(DataKcglKcbdDefault kcbd){
        JSONObject jsonObject = operationBefore(kcbd,"add");
        if (!jsonObject.getBool("success")){
            jsonObject.remove("type");
            return  jsonObject;
        }
        //保存业务数据
        kcbd.setSytelInfoID("2c9180847060449e017061e8d03203fe"); //样式id
        kcbd.setPeriodID("12"); //期间id
        kcbd.setDeptID(kcbd.getUnitID());//部门id
        kcbd.setRoundID(0); //舍位id
        if (StringUtils.isBlank(kcbd.getBuilder())){
            kcbd.setBuilder(kcbd.getUnitID());
            kcbd.setEditor(kcbd.getUnitID());
        }
        //保存数据
        if (!super.saveOrUpdate(kcbd)){
            throw new RuntimeException("保存库存变动失败");
        }
        String matherId = kcbd.getDataID();
        String unitId = kcbd.getUnitID();
        String loginName = kcbd.getBuilder();//创建人
        StoreWorkType workType = StoreWorkType.valueOf(jsonObject.getShort("type"));
        //保存库存相关数据
        EditStatus editStatus = EditStatus.New;
        Boolean b = dataKcglXckcDefaultService.makeStockDetail(matherId, unitId, loginName, editStatus, workType);
        if (!b) {
            throw new RuntimeException("保存仓储数据失败");
        }
        jsonObject.set("success", true);
        jsonObject.set("dataId", kcbd.getDataID());
        jsonObject.set("bddh",kcbd.getBddh());
        jsonObject.set("msg", "保存成功");
        return jsonObject;
    }
    /**
     *修改库存管理-库存变动
     * @param kcbd 库存管理-库存变动业务数据
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
//    @SystemLog(module = "原粮库存变动", methods = "库存",uploadName = "yuliang.kcbd")
    @SystemCountryLog(module = "原粮库存变动", methods = "修改",uploadName = "yuliang.kcbd")
    public JSONObject update(DataKcglKcbdDefault kcbd){
            JSONObject jsonObject = operationBefore(kcbd,"update");
            if (!jsonObject.getBool("success")){
                jsonObject.remove("type");
                return  jsonObject;
            }
            //保存数据
            if (!super.saveOrUpdate(kcbd)){
                throw new RuntimeException("修改库存变动失败");
            }
            String matherId = kcbd.getDataID();
            String unitId = kcbd.getUnitID();
            String loginName = kcbd.getBuilder();//创建人
            //保存库存相关数据
            EditStatus editStatus = EditStatus.Modified;
            StoreWorkType workType = StoreWorkType.valueOf(jsonObject.getShort("type"));
            Boolean b = dataKcglXckcDefaultService.makeStockDetail(matherId, unitId, loginName, editStatus,workType );
            if (!b) {
                throw new RuntimeException("保存仓储数据失败");
            }
            jsonObject.set("success", true);
            jsonObject.set("dataId", kcbd.getDataID());
            jsonObject.set("bddh",kcbd.getBddh());
            jsonObject.set("msg", "修改成功");
            return jsonObject;
    }
    /**
     *删除库存管理-库存变动数据
     * @param id 库存管理-库存变动主键尖
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
//    @SystemLog(module = "原粮库存变动", methods = "库存",uploadName = "yuliang.kcbd")
    @SystemCountryLog(module = "原粮库存变动", methods = "删除",uploadName = "yuliang.kcbd")
    public JSONObject delete(String id){
                JSONObject jsonObject = new JSONObject();
                jsonObject.set("success",false);
                //得到对象
                DataKcglKcbdDefault kcbd = super.getById(id);
                if (kcbd == null) {
                    jsonObject.set("msg", "此数据已被删除");
                    return jsonObject;
                }
                 jsonObject = operationBefore(kcbd,"delete");
                if (!jsonObject.getBool("success")){
                    jsonObject.remove("type");
                    return  jsonObject;
                }
                //删除数据
                if (!super.removeById(id)){
                    throw new RuntimeException("删除库存变动失败");
                }
                String matherId = kcbd.getDataID();
                String unitId = kcbd.getUnitID();
                String loginName = kcbd.getBuilder();//创建人
                //保存库存相关数据
                EditStatus editStatus = EditStatus.Deleted;
                StoreWorkType workType = StoreWorkType.valueOf(jsonObject.getShort("type"));
                Boolean b = dataKcglXckcDefaultService.makeStockDetail(matherId, unitId, loginName, editStatus, workType);
                if (!b) {
                    throw new RuntimeException("保存仓储数据失败");
                }
        //保存删除数据记录
        deleteDataRecordService.save(id,"data_kcgl_kcbd_default",unitId,new Date());

                jsonObject.set("success", true);
                //上报国家局
                jsonObject.set("dataId", kcbd.getDataID());
                jsonObject.set("unitId",unitId);
                jsonObject.set("bddh",kcbd.getBddh());
                jsonObject.set("bdfs",kcbd.getBdfs());
                jsonObject.set("msg", "删除成功");
                return jsonObject;
        }

    /**
     * 按照条件查询库存管理-库存变动信息
     * @param pageQuery
     * @throws Exception
     */
    @Override
    public IPage<Map<String,Object>> findPageVo(DataKcglKcbdDefaultVo pageQuery){
        {
        //条形查询器
        QueryWrapper<DataKcglKcbdDefault> queryWrapper = new QueryWrapper<>();
            if (StringUtils.isNotBlank(pageQuery.getUnitId())){
                queryWrapper.eq("DATA_KCGL_KCBD_DEFAULT.unitId",pageQuery.getUnitId());
            }
            if (StringUtils.isNotBlank(pageQuery.getBddh())){
                queryWrapper.like("DATA_KCGL_KCBD_DEFAULT.bddh", ResultUtil.getQueryWrapperformat(pageQuery.getBddh()));
            }
            if (StringUtils.isNotBlank(pageQuery.getCfmc())){
                queryWrapper.like("DATA_KCGL_KCBD_DEFAULT.cfmc",ResultUtil.getQueryWrapperformat(pageQuery.getCfmc()));
            }
            if (StringUtils.isNotBlank(pageQuery.getPz())){
                queryWrapper.eq("DATA_KCGL_KCBD_DEFAULT.pz",pageQuery.getPz());
            }
            if (StringUtils.isNotBlank(pageQuery.getXz())){
                queryWrapper.eq("DATA_KCGL_KCBD_DEFAULT.xz",pageQuery.getXz());
            }
            if (StringUtils.isNotBlank(pageQuery.getDj())){
                queryWrapper.eq("DATA_KCGL_KCBD_DEFAULT.dj",pageQuery.getDj());
            }
            if (StringUtils.isNotBlank(pageQuery.getYwfssjStart()) && StringUtils.isNotBlank(pageQuery.getYwfssjEnd())) {
                queryWrapper.apply(" DATE_FORMAT(ifnull(DATA_KCGL_KCBD_DEFAULT.ywfssj,NOW()),'%Y-%m-%d') >=  '" + pageQuery.getYwfssjStart() + "' AND DATE_FORMAT(ifnull(DATA_KCGL_KCBD_DEFAULT.ywfssj,NOW()),'%Y-%m-%d') <= '" + pageQuery.getYwfssjEnd() + " 23:59:59'");
            }
            //分页相关
        Page<DataKcglKcbdDefault> p =new Page<>(pageQuery.getPage(),pageQuery.getLimit());

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

    }

    @Override
    public Map<String, Object> getOneKcbd(String id) {
        return dataKcglKcbdDefaultMapper.getOneKCbd(id);
    }

    @Override
    public Map<String, Object> getKcInfo(String cfid, String hwid, String unitId) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.set("success",false);
        jsonObject.set("pz","");
        jsonObject.set("mxpz","");
        jsonObject.set("xz","");
        jsonObject.set("dj","");
        jsonObject.set("kcsl",0.0);
        QueryWrapper<DataKcglKcswDefault> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ch",cfid);
        queryWrapper.eq("hwh",hwid);
        queryWrapper.eq("unitId",unitId);
        queryWrapper.last("limit 0,1");
        //未查询到此货位库存数据
        DataKcglKcswDefault kcsw = dataKcglKcswDefaultService.getOne(queryWrapper);
        if (kcsw == null){
            return  jsonObject;
        }
        //查询产地和生产年份 ,得到分库保管账第一条数据
        QueryWrapper<DataKcglFcbgzDefault> queryWrapper_fcbgz = new QueryWrapper<>();
        queryWrapper_fcbgz.eq("ch",cfid);
        queryWrapper_fcbgz.eq("hwh",hwid);
        queryWrapper_fcbgz.eq("unitId",unitId);
        queryWrapper_fcbgz.last(" limit 0,1");
        queryWrapper_fcbgz.orderByDesc("rq");
        DataKcglFcbgzDefault fcbgz = dataKcglFcbgzDefaultService.getOne(queryWrapper_fcbgz);
        if (fcbgz == null){
            return  jsonObject;
        }
        jsonObject.set("pz",kcsw.getPz());
        jsonObject.set("pzValue",basicEnumService.getById(kcsw.getPz()).getEnumName());
        jsonObject.set("mxpz",kcsw.getMxpz());
        jsonObject.set("xz",kcsw.getHwxz());
        jsonObject.set("xzValue",basicEnumService.getById(kcsw.getHwxz()).getEnumName());
        jsonObject.set("dj",kcsw.getDj());
        jsonObject.set("kcsl",kcsw.getKcsl());
        jsonObject.set("cd",fcbgz.getHwcd());
        jsonObject.set("scnf",fcbgz.getScnf());

        jsonObject.set("success",true);
        return jsonObject;
    }

    private JSONObject operationBefore(DataKcglKcbdDefault kcbd,String operationType){
        JSONObject jsonObject = new JSONObject();
        jsonObject.set("success",false);
        String bdfsId = kcbd.getBdfs(); //变动方式id
        BasicEnum basicEnum = basicEnumService.getById(bdfsId);
        if (basicEnum == null){
            jsonObject.set("msg","变动方式不存在");
            return  jsonObject;
        }
        String bdfs = StringUtils.substring(basicEnum.getEnumCode(),0,1); //得到第一个数字；
        StoreWorkType type = null;
        if("0".equals(bdfs)) {	// 入库
            type = StoreWorkType.KcbdRk;
        } else if("1".equals(bdfs) || "5".equals(bdfs) ) {
            type = StoreWorkType.KcbdCk;
        } else if("2".equals(bdfs)) {
            type = StoreWorkType.KcbdYc;
        }else if("3".equals(bdfs)) {
            type = StoreWorkType.KcbdXz;
        }else if("4".equals(bdfs)) {
            type = StoreWorkType.KcbdPc;
        }
        jsonObject.set("type",type.value());
        /*//得到变动数量
        Integer bdsl = kcbd.getBdsl();
        if ("update".equals(operationType)){
            DataKcglKcbdDefault kcbd_old = super.getById(kcbd.getDataID());
            bdsl = bdsl-kcbd_old.getBdsl(); //新数量-旧数量
        }
        if("1".equals(bdfs) || "4".equals(bdfs)) {	// 出库  平仓
        }*/
        //
        if (!"add".equals(operationType)){
            QueryWrapper<DataKcglFcbgzDefault> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("unitId",kcbd.getUnitID());
            queryWrapper.eq("ch",kcbd.getCfid());
            queryWrapper.eq("hwh",kcbd.getHwid());
            queryWrapper.eq("pz",kcbd.getPz());
            queryWrapper.eq("hwxz",kcbd.getXz());
            //使用创建时间
            String date =  DateUtil.format(kcbd.getBuildDate(),"yyyy-MM-dd HH:mm:ss");
            queryWrapper.ge("rq",date);
            queryWrapper.ne("dataId",kcbd.getDataID());
            queryWrapper.last("limit 1");
            DataKcglFcbgzDefault dataKcglFcbgzDefault = dataKcglFcbgzDefaultService.getOne(queryWrapper);
            if(dataKcglFcbgzDefault != null){
                jsonObject.set("msg", "此条变动数据后已做出入库操作，不可操作");
                return jsonObject;
            }
        }
        jsonObject.set("success",true);
        return  jsonObject;
    }


}
