package org.jeecg.modules.fbsInventory.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.util.InterfaceConnUtils;
import org.jeecg.modules.fbsInventory.entity.FbsInventory;
import org.jeecg.modules.fbsInventory.mapper.FbsInventoryMapper;
import org.jeecg.modules.fbsInventory.service.IFbsInventoryService;
import org.jeecg.modules.fbsMomOrder.service.IFbsMomOrderService;
import org.jeecg.modules.pulldate.entity.PullDate;
import org.jeecg.modules.pulldate.service.IPullDateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Description: 存库档案
 * @author： jeecg-boot
 * @date：   2020-10-16
 * @version： V1.0
 */
@Service
@DS("multi-datasource1")
@Transactional
public class FbsInventoryServiceImpl extends ServiceImpl<FbsInventoryMapper, FbsInventory> implements IFbsInventoryService {

    @Resource
    FbsInventoryMapper fbsInventoryMapper;

    @Resource
    IPullDateService iPullDateService;

    @Resource
    IFbsMomOrderService iFbsMomOrderService;

    @Override
    public List<FbsInventory> getInventoryGetByOrderId(String moId) {
        return fbsInventoryMapper.getInventoryGetByOrderId(moId);
    }

    @Override
    public List<Map<String,Object>> getStockList(){
        return fbsInventoryMapper.getStockList();
    }

    @Override
    public Map<String,Object> getAllStockList(){
        List<Map<String,Object>> mapList = fbsInventoryMapper.getAllStockList();
        Map<String,Object> map = new HashMap<>();
        if(mapList.size() > 0){
            for (Map<String,Object> m:mapList){
                map.put(m.get("materialName").toString(),m.get("realStockSum"));
            }
        }
        return map;
    }

    @Override
    public List<FbsInventory> getListByIds(List<String> stringList) {
        LambdaQueryWrapper<FbsInventory> fbsInventoryLambdaQueryWrapper=new LambdaQueryWrapper<>();
        fbsInventoryLambdaQueryWrapper.in(FbsInventory::getCinvcode,stringList);
        return fbsInventoryMapper.selectList(fbsInventoryLambdaQueryWrapper);
    }

    @Override
    public String getByInvCode(String invCode) {
        return fbsInventoryMapper.getByInvCode(invCode);
    }

    @Override
    public int updateCInvDefine13(String standardWorkingHoursZ, String invCode) {
        return fbsInventoryMapper.updateCInvDefine13(standardWorkingHoursZ,invCode);
    }

    @Override
    public List<FbsInventory> getDrawingCode(String moCode) {
        return fbsInventoryMapper.getDrawingCode(moCode);
    }

    @Override
    public FbsInventory getInventory(String cInvCode) {
        return fbsInventoryMapper.getInventory(cInvCode);
    }

    @Override
    @DS("master")
    public void addSAPInventory(Long start,Long end) {

        //传入参数
        String jsonSting="{\"TIMELIMIT\":{\"ST\":\""+start+"\",\"ET\":\""+end+"\"},\"COMMON_INFO_REQ\":{\"API_NO\":\"KANB00007\",\"GUID\":\""+UUID.randomUUID().toString()+"\",\"USERID\":\"USERNAME\"}}";
        JSONObject jsonObjectP=JSONObject.parseObject(JSONObject.parse(jsonSting).toString());
        //获取接收数据
        JSONObject jsonObjectResults= InterfaceConnUtils.doPost(jsonObjectP,"");
        //判断是否接收成功
        if(jsonObjectResults.getJSONObject("STATUS").get("TYPE").toString().equals("S")){
            List<Map<String,Object>> addlistInventory=new ArrayList<>();//储存所有的存货
            //接收成功
            JSONArray jsonArray=jsonObjectResults.getJSONArray("ITEMS");
            //循环获取
            for(int a=0;a<jsonArray.size();a++) {
                JSONObject jsonObject=jsonArray.getJSONObject(a);
                Map<String,Object> mapInventory=new LinkedHashMap<>();
                mapInventory.put("id",UUID.randomUUID().toString());
                mapInventory.put("cInvCode",String.valueOf(jsonObject.get("CINVCODE")));//存货编码
                mapInventory.put("cInvName",String.valueOf(jsonObject.get("CINVNAME")));//存货名称
                mapInventory.put("iSafeNum",getDecimalNew(String.valueOf(jsonObject.get("ISAFENUM"))));//安全库存量
                mapInventory.put("cInvCCode",String.valueOf(jsonObject.get("CINVCCODE")));//存货大类编码
                mapInventory.put("cInvStd",String.valueOf(jsonObject.get("CINVSTD")));//规格型号
                String BPROPERTYCHECK=String.valueOf(jsonObject.get("BPROPERTYCHECK"));
                if(StringUtils.isNotBlank(BPROPERTYCHECK)){
                    mapInventory.put("bPropertyCheck","1");//是质检
                }else{
                    mapInventory.put("bPropertyCheck","0");//不是质检
                }
                mapInventory.put("cInvCName",String.valueOf(jsonObject.get("CINVCNAME")));//存货大类名称
                mapInventory.put("isSerialNumber",String.valueOf(jsonObject.get("ISSERIALNUMBER")));//是否启用序列号
                SimpleDateFormat sdf =   new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
                mapInventory.put("create_time",sdf.format(new Date()));//创建时间
                mapInventory.put("pull_date",end+"");//拉取时间
                addlistInventory.add(mapInventory);
            }
            //判断获取到数据则进行新增
            if(addlistInventory.size()>0){
                //先进行删除
                this.baseMapper.deleteSAPInventory(addlistInventory);
                //再进行新增
                this.baseMapper.addSAPInventory(addlistInventory);
            }
        }
    }

    @Override
    @DS("master")
    public void addSAPCurrentStock(Long start,Long end) {
        //传入参数
        String jsonSting="{\"COMMON_INFO_REQ\":{\"API_NO\":\"KANB00005\",\"GUID\":\""+UUID.randomUUID().toString()+"\",\"USERID\":\"USERNAME\"}}";
        JSONObject jsonObjectP=JSONObject.parseObject(JSONObject.parse(jsonSting).toString());
        //获取接收数据
        JSONObject jsonObjectResults= InterfaceConnUtils.doPost(jsonObjectP,"");
        //判断是否接收成功
        if(jsonObjectResults.getJSONObject("STATUS").get("TYPE").toString().equals("S")){
            //接收成功
            JSONArray jsonArray=jsonObjectResults.getJSONArray("ITEMS");
            List<Map<String,Object>> addList=new ArrayList<>();//储存所有的库存存量数据
            //循环获取
            for(int a=0;a<jsonArray.size();a++) {
                JSONObject jsonObject=jsonArray.getJSONObject(a);
                Map<String,Object> map=new LinkedHashMap<>();
                map.put("id",UUID.randomUUID().toString());
                map.put("iQuantity",getDecimalNew(String.valueOf(jsonObject.get("IQUANTITY"))));//结存数量
                String CWHCODE=String.valueOf(jsonObject.get("CWHCODE"));//仓库编码
                map.put("cWhCode",cWhCode(CWHCODE));//仓库编码
//                map.put("cWhCode",String.valueOf(jsonObject.get("CWHCODE")));//仓库编码
                map.put("cWhName",String.valueOf(jsonObject.get("CWHNAME")));//仓库名称
                map.put("WBS",String.valueOf(jsonObject.get("WBS")));//wbs
                map.put("cVenCode",String.valueOf(jsonObject.get("CVENCODE")));//供应商编码
                map.put("cInvCode",String.valueOf(jsonObject.get("CINVCODE")));//存货编码
                SimpleDateFormat sdf =   new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
                map.put("create_time",sdf.format(new Date()));//创建时间
                map.put("pull_date",end+"");//拉取时间
                addList.add(map);
            }
            //判断获取到数据则进行新增
            if(addList.size()>0){
                //先进行删除
                this.baseMapper.deleteSAPCurrentStock();
                //再进行新增
                this.baseMapper.addSAPCurrentStock(addList);
            }
        }
    }

    @Override
    @DS("master")
    public void addSAPRdrecord10MainAndItems(Long start,Long end) {
        //传入参数
        String jsonSting="{\"TIMELIMIT\":{\"ST\":\""+start+"\",\"ET\":\""+end+"\"},\"COMMON_INFO_REQ\":{\"API_NO\":\"KANB00006\",\"GUID\":\""+UUID.randomUUID().toString()+"\",\"USERID\":\"USERNAME\"}}";
        JSONObject jsonObjectP=JSONObject.parseObject(JSONObject.parse(jsonSting).toString());
        //获取接收数据
        JSONObject jsonObjectResults= InterfaceConnUtils.doPost(jsonObjectP,"");
        //判断是否接收成功
        if(jsonObjectResults.getJSONObject("STATUS").get("TYPE").toString().equals("S")){
            //接收成功
            JSONArray jsonArray=jsonObjectResults.getJSONArray("OUTPUT");
            List<Map<String,Object>> addMainList=new ArrayList<>();//储存所有的产成品主表数据
            List<Map<String,Object>> addItemList=new ArrayList<>();//存储所有的产成品子表数据
            //循环获取
            for(int a=0;a<jsonArray.size();a++) {
                JSONObject jsonObjectMain=jsonArray.getJSONObject(a);//主表对象
                //主表
                Map<String,Object> mapMain=new LinkedHashMap<>();
                mapMain.put("ID",String.valueOf(jsonObjectMain.get("ID")));//主表标识
//                mapMain.put("cWhCode",String.valueOf(jsonObjectMain.get("CWHCODE")));//仓库编码
                String CWHCODE=String.valueOf(jsonObjectMain.get("CWHCODE"));//仓库编码
                mapMain.put("cWhCode",cWhCode(CWHCODE));//仓库编码
                mapMain.put("cWhName",String.valueOf(jsonObjectMain.get("CWHNAME")));//仓库名称
                SimpleDateFormat sdf =   new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
                if(StringUtils.isNotBlank(String.valueOf(jsonObjectMain.get("DDATE")))){
                    try {
                        String ddate=String.valueOf(jsonObjectMain.get("DDATE"));
                        ddate=ddate+" 00:00:00";
                        mapMain.put("dDate",sdf.parse( ddate ));//单据时间
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }else {
                        mapMain.put("dDate",null);//单据时间
                }
                mapMain.put("create_time",sdf.format(new Date()));//创建时间
                mapMain.put("pull_date",end+"");//拉取时间
                addMainList.add(mapMain);
                //子表

                JSONArray jsonArrayItems=jsonObjectMain.getJSONArray("ITEMS");
                for(int b=0;b<jsonArrayItems.size();b++){
                    JSONObject jsonObjectItem=jsonArrayItems.getJSONObject(b);//子表对象
                    Map<String,Object> mapItem=new LinkedHashMap<>();
                    mapItem.put("cInvCode",String.valueOf(jsonObjectItem.get("CINVCODE")));//供应商编码
                    mapItem.put("ID",String.valueOf(jsonObjectItem.get("ID")));
                    mapItem.put("cBatch",String.valueOf(jsonObjectItem.get("CBATCH")));//批号
                    mapItem.put("iQuantity",getDecimalNew(String.valueOf(jsonObjectItem.get("IQUANTITY"))));//数量
                    mapItem.put("create_time",sdf.format(new Date()));//创建时间
                    mapItem.put("pull_date",end+"");//拉取时间
                    addItemList.add(mapItem);
                }

            }
            //判断获取到数据则进行新增
            //保存主表
            if(addMainList.size()>0){
                //先删除存在的数据
                this.baseMapper.deleteSAPRdrecord10(addMainList);//删除主表
                this.baseMapper.deleteSAPRdrecords10(addMainList);//删除子表
                //再进行新增
                fbsInventoryMapper.addSAPRdrecord10(addMainList);
            }
            //保存子表
            if(addItemList.size()>0){
                fbsInventoryMapper.addSAPRdrecords10(addItemList);
            }

        }
    }

    @Override
    @DS("master")
    public void addSAPVendor(Long start,Long end) {
        //传入参数
        String jsonSting="{\"TIMELIMIT\":{\"ST\":\""+start+"\",\"ET\":\""+end+"\"},\"COMMON_INFO_REQ\":{\"API_NO\":\"KANB00008\",\"GUID\":\""+UUID.randomUUID().toString()+"\",\"USERID\":\"USERNAME\"}}";
        JSONObject jsonObjectP=JSONObject.parseObject(JSONObject.parse(jsonSting).toString());
        //获取接收数据
        JSONObject jsonObjectResults= InterfaceConnUtils.doPost(jsonObjectP,"");
        //判断是否接收成功
        if(jsonObjectResults.getJSONObject("STATUS").get("TYPE").toString().equals("S")){
            //接收成功
            JSONArray jsonArray=jsonObjectResults.getJSONArray("ITEMS");
            List<Map<String,Object>> addList=new ArrayList<>();//储存所有的供应商数据
            //循环获取
            for(int a=0;a<jsonArray.size();a++) {
                JSONObject jsonObject=jsonArray.getJSONObject(a);//供应商对象
                Map<String,Object> map=new LinkedHashMap<>();
                map.put("id",UUID.randomUUID().toString());
                map.put("cVenCode",String.valueOf(jsonObject.get("CVENCODE")));//供应商编码
                map.put("cMemo",String.valueOf(jsonObject.get("CMEMO")));//备注
                map.put("cVenName",String.valueOf(jsonObject.get("CVENNAME")));//供应商名称
                SimpleDateFormat sdf =   new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
                map.put("create_time",sdf.format(new Date()));//创建时间
                map.put("pull_date",end+"");//拉取时间
                addList.add(map);
            }
            //判断获取到数据则进行新增
            if(addList.size()>0){
                //先删除存在的
                this.baseMapper.deleteSAPVendor(addList);
                //再新增
                this.baseMapper.addSAPVendor(addList);
            }
        }
    }

    @Override
    @DS("master")
    public void addSAPPO_PoMainAndItems(Long start,Long end) {
        //传入参数
        String jsonSting="{\"TIMELIMIT\":{\"ST\":\""+start+"\",\"ET\":\""+end+"\"},\"COMMON_INFO_REQ\":{\"API_NO\":\"KANB00009\",\"GUID\":\""+UUID.randomUUID().toString()+"\",\"USERID\":\"USERNAME\"}}";
        JSONObject jsonObjectP=JSONObject.parseObject(JSONObject.parse(jsonSting).toString());
        //获取接收数据
        JSONObject jsonObjectResults= InterfaceConnUtils.doPost(jsonObjectP,"");
        //判断是否接收成功
        if(jsonObjectResults.getJSONObject("STATUS").get("TYPE").toString().equals("S")){
            //接收成功
            JSONArray jsonArray=jsonObjectResults.getJSONArray("OUTPUT");
            List<Map<String,Object>> addMainList=new ArrayList<>();//储存所有的采购订单主表数据
            List<Map<String,Object>> addItemList=new ArrayList<>();//存储所有的采购订单子表数据
            SimpleDateFormat sdf =   new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
            //循环获取
            for(int a=0;a<jsonArray.size();a++) {
                JSONObject jsonObjectMain=jsonArray.getJSONObject(a);//主表对象
                //主表
                Map<String,Object> mapMain=new LinkedHashMap<>();
                mapMain.put("id",UUID.randomUUID().toString());//主键
                if(StringUtils.isNotBlank(String.valueOf(jsonObjectMain.get("DPODATE")))){
                    try {
                        String DPODATE=String.valueOf(jsonObjectMain.get("DPODATE"));
                        DPODATE=DPODATE+" 00:00:00";
                        mapMain.put("dPODate",sdf.parse( DPODATE ));//单据时间
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }else {
                    mapMain.put("dPODate",null);//单据时间
                }
                mapMain.put("cVenCode",String.valueOf(jsonObjectMain.get("CVENCODE")));//供应商编码
                mapMain.put("POID",String.valueOf(jsonObjectMain.get("POID")));//主表标识
                mapMain.put("create_time",sdf.format(new Date()));//创建时间
                mapMain.put("pull_date",end+"");//拉取时间
                addMainList.add(mapMain);
                //子表
                JSONArray jsonArrayItems=jsonObjectMain.getJSONArray("ITEMS");
                for(int b=0;b<jsonArrayItems.size();b++){
                    JSONObject jsonObjectItem=jsonArrayItems.getJSONObject(b);//子表对象
                    Map<String,Object> mapItem=new LinkedHashMap<>();
                    mapItem.put("ID",UUID.randomUUID().toString());//主键
                    mapItem.put("SAPID",String.valueOf(jsonObjectItem.get("ID")));//SAP采购订单子表主键（行号）
                    if(StringUtils.isNotBlank(String.valueOf(jsonObjectItem.get("DARRIVEDATE")))){
                        try {
                            String DPODATE=String.valueOf(jsonObjectItem.get("DARRIVEDATE"));
                            DPODATE=DPODATE+" 00:00:00";
                            mapItem.put("dArriveDate",sdf.parse( DPODATE ));//计划到货日期
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                    }else {
                        mapItem.put("dArriveDate",null);//计划到货日期
                    }
                    mapItem.put("cInvCode",String.valueOf(jsonObjectItem.get("CINVCODE")));//存货编码
                    mapItem.put("iQuantity",getDecimalNew(String.valueOf(jsonObjectItem.get("IQUANTITY"))));//数量
                    mapItem.put("cItemName",String.valueOf(jsonObjectItem.get("CITEMNAME")));//项目名称
                    mapItem.put("POID",String.valueOf(jsonObjectItem.get("POID")));//采购订单主表标识
                    mapItem.put("iReceivedQTY",getDecimalNew(String.valueOf(jsonObjectItem.get("IRECEIVEDQTY"))));//累计到货数量
                    mapItem.put("iArrQTY",getDecimalNew(String.valueOf(jsonObjectItem.get("IARRQTY"))));//到货数量
                    mapItem.put("freceivedqty",getDecimalNew(String.valueOf(jsonObjectItem.get("FRECEIVEDQTY"))));//合格品入库数量
                    mapItem.put("create_time",sdf.format(new Date()));//创建时间
                    mapItem.put("pull_date",end+"");//拉取时间
                    addItemList.add(mapItem);
                }

            }
            //判断获取到数据则进行新增
            //保存主表
            if(addMainList.size()>0){
                //先删除
                this.baseMapper.deleteSAPPoPomain(addMainList);//删除主表数据
                this.baseMapper.deleteSAPPoPodetails(addMainList);//删除子表数据
                //再新增
                fbsInventoryMapper.addSAPPoPomain(addMainList);
            }
            //保存子表
            if(addItemList.size()>0){
                fbsInventoryMapper.addSAPPoPodetails(addItemList);
            }

        }
    }

    @Override
    @DS("master")
    public void addSAPPuArrivalvouch(Long start,Long end) {
        //传入参数
        String jsonSting="{\"TIMELIMIT\":{\"ST\":\""+start+"\",\"ET\":\""+end+"\"},\"COMMON_INFO_REQ\":{\"API_NO\":\"KANB00011\",\"GUID\":\""+UUID.randomUUID().toString()+"\",\"USERID\":\"USERNAME\"}}";
        JSONObject jsonObjectP=JSONObject.parseObject(JSONObject.parse(jsonSting).toString());
        //获取接收数据
        JSONObject jsonObjectResults= InterfaceConnUtils.doPost(jsonObjectP,"");
        //判断是否接收成功
        if(jsonObjectResults.getJSONObject("STATUS").get("TYPE").toString().equals("S")){
            //接收成功
            JSONArray jsonArray=jsonObjectResults.getJSONArray("OUTPUT");
            List<Map<String,Object>> addMainList=new ArrayList<>();//储存所有的采购到货主表数据
            List<Map<String,Object>> addItemList=new ArrayList<>();//存储所有的采购到货子表数据
            SimpleDateFormat sdf =   new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
            //循环获取
            for(int a=0;a<jsonArray.size();a++) {
                JSONObject jsonObjectMain=jsonArray.getJSONObject(a);//主表对象
                //主表
                Map<String,Object> mapMain=new LinkedHashMap<>();
                mapMain.put("idd",UUID.randomUUID().toString());//主键
                if(StringUtils.isNotBlank(String.valueOf(jsonObjectMain.get("DDATE")))){
                    try {
                        String DPODATE=String.valueOf(jsonObjectMain.get("DDATE"));
                        DPODATE=DPODATE+" 00:00:00";
                        mapMain.put("dDate",sdf.parse( DPODATE ));//单据时间
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }else {
                    mapMain.put("dDate",null);//单据时间
                }
                mapMain.put("ID",String.valueOf(jsonObjectMain.get("ID")));//采购到货单主表标识
                mapMain.put("cVenCode",String.valueOf(jsonObjectMain.get("CVENCODE")));//供应商编码
                mapMain.put("create_time",sdf.format(new Date()));//创建时间
                mapMain.put("pull_date",end+"");//拉取时间
                addMainList.add(mapMain);
                //子表
                JSONArray jsonArrayItems=jsonObjectMain.getJSONArray("ITEMS");
                for(int b=0;b<jsonArrayItems.size();b++){
                    JSONObject jsonObjectItem=jsonArrayItems.getJSONObject(b);//子表对象
                    Map<String,Object> mapItem=new LinkedHashMap<>();
                    mapItem.put("Autoid",UUID.randomUUID().toString());//主键
                    mapItem.put("ID",String.valueOf(jsonObjectItem.get("ID")));//采购到货主表ID
                    mapItem.put("fRealQuantity",getDecimalNew(String.valueOf(jsonObjectItem.get("FREALQUANTITY"))));//实收数量
                    mapItem.put("fValidQuantity",getDecimalNew(String.valueOf(jsonObjectItem.get("FVALIDQUANTITY"))));//合格数量
                    mapItem.put("fValidInQuan",getDecimalNew(String.valueOf(jsonObjectItem.get("CITEMNAME"))));//合格品入库数量
                    mapItem.put("cInvCode",String.valueOf(jsonObjectItem.get("CINVCODE")));//存货编码
                    mapItem.put("cItemName",String.valueOf(jsonObjectItem.get("CITEMNAME")));//项目名称
                    mapItem.put("iQuantity",getDecimalNew(String.valueOf(jsonObjectItem.get("IQUANTITY"))));//数量
                    String bInspect=String.valueOf(jsonObjectItem.get("BINSPECT"));
                    if(StringUtils.isNotBlank(bInspect)){
                        mapItem.put("bInspect",1);//是质检
                    }else{
                        mapItem.put("bInspect",0);//不是质检
                    }
                    mapItem.put("SAPAutoid",String.valueOf(jsonObjectItem.get("AUTOID")));//SAP采购到货子表id（行号）
                    mapItem.put("create_time",sdf.format(new Date()));//创建时间
                    mapItem.put("pull_date",end+"");//拉取时间
                    addItemList.add(mapItem);
                }

            }
            //判断获取到数据则进行新增
            //保存主表
            if(addMainList.size()>0){
                //先删除
                this.baseMapper.deleteSAPPuArrivalvouch(addMainList);//删除主表
                this.baseMapper.deleteSAPPuArrivalvouchs(addMainList);//删除子表
                //再新增
                fbsInventoryMapper.addSAPPuArrivalvouch(addMainList);
            }
            //保存子表
            if(addItemList.size()>0){
                fbsInventoryMapper.addSAPPuArrivalvouchs(addItemList);
            }

        }
    }

    @Override
    @DS("master")
    public void addSAPMaterialappvouchMainAndItem(Long start,Long end) {
        //传入参数
        String jsonSting="{\"TIMELIMIT\":{\"ST\":\""+start+"\",\"ET\":\""+end+"\"},\"COMMON_INFO_REQ\":{\"API_NO\":\"KANB00012\",\"GUID\":\""+UUID.randomUUID().toString()+"\",\"USERID\":\"USERNAME\"}}";
        JSONObject jsonObjectP=JSONObject.parseObject(JSONObject.parse(jsonSting).toString());
        //获取接收数据
        JSONObject jsonObjectResults= InterfaceConnUtils.doPost(jsonObjectP,"");
        //判断是否接收成功
        if(jsonObjectResults.getJSONObject("STATUS").get("TYPE").toString().equals("S")){
            //接收成功
            JSONArray jsonArray=jsonObjectResults.getJSONArray("OUTPUT");
            List<Map<String,Object>> addMainList=new ArrayList<>();//储存所有的领料申请主表数据
            List<Map<String,Object>> addItemList=new ArrayList<>();//存储所有的领料申请子表数据
//            List<Map<String,Object>> dispatchList=new ArrayList<>();//储存所有的领料申请主表数据
//            List<Map<String,Object>> dispatchItemList=new ArrayList<>();//存储所有的领料申请子表数据
            SimpleDateFormat sdf =   new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
            //循环获取
            for(int a=0;a<jsonArray.size();a++) {
                JSONObject jsonObjectMain=jsonArray.getJSONObject(a);//主表对象
                //主表
                Map<String,Object> mapMain=new LinkedHashMap<>();
                mapMain.put("idd",UUID.randomUUID().toString());//主键
                if(StringUtils.isNotBlank(String.valueOf(jsonObjectMain.get("DDATE")))){
                    try {
                        String DPODATE=String.valueOf(jsonObjectMain.get("DDATE"));
                        DPODATE=DPODATE+" 00:00:00";
                        mapMain.put("dDate",sdf.parse( DPODATE ));//单据时间
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }else {
                    mapMain.put("dDate",null);//单据时间
                }
                mapMain.put("ID",String.valueOf(jsonObjectMain.get("ID")));//领料单主表标识
                mapMain.put("cMaker",String.valueOf(jsonObjectMain.get("CMAKER")));//制单人
//                String businessType=String.valueOf(jsonObjectMain.get("CVENCODE"));
//                if(StringUtils.isNotBlank(businessType)){
//                    mapMain.put("businessType",1);//业务类型
//                }else{
//                    mapMain.put("businessType",1);//业务类型
//                }
                mapMain.put("cDepCode",String.valueOf(jsonObjectMain.get("CDEPCODE")));//部门编码
                mapMain.put("cDepName",String.valueOf(jsonObjectMain.get("CDEPNAME")));//部门名称
                mapMain.put("create_time",sdf.format(new Date()));//创建时间
                mapMain.put("pull_date",end+"");//拉取时间
                addMainList.add(mapMain);
                //子表
                JSONArray jsonArrayItems=jsonObjectMain.getJSONArray("ITEMS");
                for(int b=0;b<jsonArrayItems.size();b++){
                    JSONObject jsonObjectItem=jsonArrayItems.getJSONObject(b);//子表对象
                    Map<String,Object> mapItem=new LinkedHashMap<>();
                    mapItem.put("idd",UUID.randomUUID().toString());//主键
                    mapItem.put("ID",String.valueOf(jsonObjectItem.get("ID")));//领料申请主表ID
                    mapItem.put("cInvCode",String.valueOf(jsonObjectItem.get("CINVCODE")));//存货编码
                    mapItem.put("iQuantity",getDecimalNew(String.valueOf(jsonObjectItem.get("IQUANTITY"))));//数量
                    mapItem.put("fOutQuantity",getDecimalNew(String.valueOf(jsonObjectItem.get("FOUTQUANTITY"))));//出库数量
                    mapItem.put("cBCloser",String.valueOf(jsonObjectItem.get("CBCLOSER")));//发货人
                    if(StringUtils.isNotBlank(String.valueOf(jsonObjectItem.get("DARRIVEDATE")))){
                        try {
                            String DPODATE=String.valueOf(jsonObjectItem.get("DARRIVEDATE"));
                            DPODATE=DPODATE+" 00:00:00";
                            mapItem.put("dArriveDate",sdf.parse( DPODATE ));//计划到货日期
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                    }else {
                        mapItem.put("dArriveDate",null);//计划到货日期
                    }
//                    mapItem.put("cWhCode",String.valueOf(jsonObjectItem.get("IQUANTITY")));//仓库编码
//                    mapItem.put("cWhName",String.valueOf(jsonObjectItem.get("AUTOID")));//仓库名称
//                    mapItem.put("cItemCode",String.valueOf(jsonObjectItem.get("AUTOID")));//项目编码
//                    mapItem.put("cItemName",String.valueOf(jsonObjectItem.get("AUTOID")));//项目名称
                    mapItem.put("create_time",sdf.format(new Date()));//创建时间
                    mapItem.put("pull_date",end+"");//拉取时间
                    addItemList.add(mapItem);
                }
            }
            //判断获取到数据则进行新增
            //保存主表
            if(addMainList.size()>0){
                //先删除
                this.baseMapper.deleteSAPMaterialappvouch(addMainList);//删除主表
                this.baseMapper.deleteSAPMaterialappvouchs(addMainList);//删除子表
                //再新增
                this.baseMapper.addSAPMaterialappvouch(addMainList);
            }
            //保存子表
            if(addItemList.size()>0){
                this.baseMapper.addSAPMaterialappvouchs(addItemList);
            }

        }
    }

    @Override
    @DS("master")
    public void addSAPQMCHECKVOUCHER(Long start,Long end) {
        //传入参数
        String jsonSting="{\"TIMELIMIT\":{\"ST\":\""+start+"\",\"ET\":\""+end+"\"},\"COMMON_INFO_REQ\":{\"API_NO\":\"KANB00004\",\"GUID\":\""+UUID.randomUUID().toString()+"\",\"USERID\":\"USERNAME\"}}";
        JSONObject jsonObjectP=JSONObject.parseObject(JSONObject.parse(jsonSting).toString());
        //获取接收数据
        JSONObject jsonObjectResults= InterfaceConnUtils.doPost(jsonObjectP,"");
        //判断是否接收成功
        if(jsonObjectResults.getJSONObject("STATUS").get("TYPE").toString().equals("S")){
            //接收成功
            JSONArray jsonArray=jsonObjectResults.getJSONArray("ITEMS");
            List<Map<String,Object>> addList=new ArrayList<>();//储存所有的检验单数据
            //循环获取
            for(int a=0;a<jsonArray.size();a++) {
                JSONObject jsonObject=jsonArray.getJSONObject(a);//检验单对象
                Map<String,Object> map=new LinkedHashMap<>();
                map.put("id",UUID.randomUUID().toString());
                SimpleDateFormat sdf =   new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
                if(StringUtils.isNotBlank(String.valueOf(jsonObject.get("DDATE")))){
                    try {
                        String DPODATE=String.valueOf(jsonObject.get("DDATE"));
                        DPODATE=DPODATE+" 00:00:00";
                        map.put("DDATE",sdf.parse( DPODATE ));//检验日期
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }else {
                    map.put("DDATE",null);//检验日期
                }
                map.put("CVENCODE",String.valueOf(jsonObject.get("CVENCODE")));//供应商编码
                map.put("CINVCODE",String.valueOf(jsonObject.get("CINVCODE")));//存货编码
                map.put("FDTQUANTITY",getDecimalNew(String.valueOf(jsonObject.get("FDTQUANTITY"))));//抽检数量
                map.put("FDISBREAKQUANTITY",getDecimalNew(String.valueOf(jsonObject.get("FDISBREAKQUANTITY"))));//不合格破坏样本数量
                map.put("FQUANTITY",getDecimalNew(String.valueOf(jsonObject.get("FQUANTITY"))));//报检数量
                map.put("CINSPECTCODE",String.valueOf(jsonObject.get("CINSPECTCODE")));//报检单单据编号
                map.put("FDISQUANTITY",getDecimalNew(String.valueOf(jsonObject.get("FDISQUANTITY"))));//不良品数量
                map.put("CCHECKCODE",String.valueOf(jsonObject.get("CCHECKCODE")));//检验单单据编号
                map.put("create_time",sdf.format(new Date()));//创建时间
                map.put("pull_date",end+"");//拉取时间
                addList.add(map);
            }
            //判断获取到数据则进行新增
            if(addList.size()>0){
                //先删除
                this.baseMapper.deleteSAPQmcheckvoucher(addList);
                //再新增
                this.baseMapper.addSAPQmcheckvoucher(addList);
            }
        }
    }

    @Override
    @DS("master")
    public void addSAPRdrecord32MainAndItem(Long start,Long end) {
        //传入参数
        String jsonSting="{\"TIMELIMIT\":{\"ST\":\""+start+"\",\"ET\":\""+end+"\"},\"COMMON_INFO_REQ\":{\"API_NO\":\"KANB00010\",\"GUID\":\""+UUID.randomUUID().toString()+"\",\"USERID\":\"USERNAME\"}}";
        JSONObject jsonObjectP=JSONObject.parseObject(JSONObject.parse(jsonSting).toString());
        //获取接收数据
        JSONObject jsonObjectResults= InterfaceConnUtils.doPost(jsonObjectP,"");
        //判断是否接收成功
        if(jsonObjectResults.getJSONObject("STATUS").get("TYPE").toString().equals("S")){
            //接收成功
            JSONArray jsonArray=jsonObjectResults.getJSONArray("OUTPUT");
            List<Map<String,Object>> addMainList=new ArrayList<>();//储存所有的销售出库主表数据
            List<Map<String,Object>> addItemList=new ArrayList<>();//存储所有的销售出库子表数据
            List<Map<String,Object>> addDispatchList=new ArrayList<>();//储存所有的发退货主表数据
            List<Map<String,Object>> addDispatchListItemList=new ArrayList<>();//存储所有的发退货子表数据
            SimpleDateFormat sdf =   new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
            //循环获取
            for(int a=0;a<jsonArray.size();a++) {
                JSONObject jsonObjectMain=jsonArray.getJSONObject(a);//主表对象
                //主表
                Map<String,Object> mapMain=new LinkedHashMap<>();
                mapMain.put("idd",UUID.randomUUID().toString());//主键
                if(StringUtils.isNotBlank(String.valueOf(jsonObjectMain.get("DDATE")))){
                    try {
                        String DPODATE=String.valueOf(jsonObjectMain.get("DDATE"));
                        DPODATE=DPODATE+" 00:00:00";
                        mapMain.put("dDate",sdf.parse( DPODATE ));//单据时间
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }else {
                    mapMain.put("dDate",null);//单据时间
                }
                mapMain.put("ID",String.valueOf(jsonObjectMain.get("ID")));//销售出库主表标识
                mapMain.put("cBusCode",String.valueOf(jsonObjectMain.get("CBUSCODE")));//对应业务单号
//                String businessType=String.valueOf(jsonObjectMain.get("CVENCODE"));
//                if(StringUtils.isNotBlank(businessType)){
//                    mapMain.put("businessType",1);//业务类型
//                }else{
//                    mapMain.put("businessType",1);//业务类型
//                }

                String CSTCODE=String.valueOf(jsonObjectMain.get("CSTCODE"));
                mapMain.put("cSTCode",cstCode(CSTCODE));//销售类型编码
                mapMain.put("type",String.valueOf(jsonObjectMain.get("TYPE")));//类型描述
//                mapMain.put("cMemo",String.valueOf(jsonObjectMain.get("KTEXT")));//备注
                if(StringUtils.isNotBlank(String.valueOf(jsonObjectMain.get("POSTINGDATE")))){
                    try {
                        String DPODATE=String.valueOf(jsonObjectMain.get("POSTINGDATE"));
                        DPODATE=DPODATE+" 00:00:00";
                        mapMain.put("postingDate",sdf.parse( DPODATE ));//过账日期
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }else {
                    mapMain.put("postingDate",null);//过账日期
                }
                String DELIVERYSTATUS=String.valueOf(jsonObjectMain.get("DELIVERYSTATUS"));//交货状态
                mapMain.put("deliveryStatus",DELIVERYSTATUS);//交货状态
                mapMain.put("create_time",sdf.format(new Date()));//创建时间
                mapMain.put("pull_date",end+"");//拉取时间


                if(DELIVERYSTATUS!=null&&DELIVERYSTATUS.equals("A")){
                    mapMain.put("idd",UUID.randomUUID().toString());//主键
                    mapMain.put("DLID",String.valueOf(jsonObjectMain.get("ID")));//主表标识
                    mapMain.put("cVerifier","审核人");//主表标识
                    addDispatchList.add(mapMain);
                }else{
                    addMainList.add(mapMain);
                }

                //子表
                JSONArray jsonArrayItems=jsonObjectMain.getJSONArray("ITEMS");
                for(int b=0;b<jsonArrayItems.size();b++){
                    JSONObject jsonObjectItem=jsonArrayItems.getJSONObject(b);//子表对象
                    Map<String,Object> mapItem=new LinkedHashMap<>();
                    mapItem.put("idd",UUID.randomUUID().toString());//主键
                    mapItem.put("ID",String.valueOf(jsonObjectItem.get("ID")));//销售出库主表ID
                    mapItem.put("cItemCode",String.valueOf(jsonObjectItem.get("CITEMCODE")));//项目编码
                    mapItem.put("iQuantity",getDecimalNew(String.valueOf(jsonObjectItem.get("IQUANTITY"))));//数量
                    mapItem.put("cInvCode",String.valueOf(jsonObjectItem.get("CINVCODE")));//存货编码
                    mapItem.put("rowCode",String.valueOf(jsonObjectItem.get("ROWS")));//行项目编码
                    String CWHCODE=String.valueOf(jsonObjectItem.get("CWHCODE"));//仓库编码
                    mapItem.put("cWhCode",cWhCode(CWHCODE));//仓库编码
                    mapItem.put("cWhName",String.valueOf(jsonObjectItem.get("CWHNAME")));//仓库名称
                    mapItem.put("create_time",sdf.format(new Date()));//创建时间
                    mapItem.put("pull_date",end+"");//拉取时间
                    if(DELIVERYSTATUS!=null&&DELIVERYSTATUS.equals("A")){
                        mapItem.put("DLID",String.valueOf(jsonObjectItem.get("ID")));//发货退货主表标识
                        mapItem.put("cItemName",String.valueOf(jsonObjectItem.get("CITEMNAME")));//项目名称
                        mapItem.put("fOutQuantity",0.0);//累计出库数量
                        addDispatchListItemList.add(mapItem);
                    }else{
                        addItemList.add(mapItem);
                    }

                }
            }
            //判断获取到数据则进行新增
            //保存主表
            if(addMainList.size()>0){
                //先删除
                this.baseMapper.deleteSAPRdrecord32(addMainList);
                this.baseMapper.deleteSAPRdrecords32(addMainList);
                //再删除
                fbsInventoryMapper.addSAPRdrecord32(addMainList);
            }
            //保存子表
            if(addItemList.size()>0){
                fbsInventoryMapper.addSAPRdrecords32(addItemList);
            }

            //判断获取到数据则进行新增
            //保存主表
            if(addDispatchList.size()>0){
                //先删除
                this.baseMapper.deleteSAPDispatchList(addDispatchList);
                this.baseMapper.deleteSAPDispatchLists(addDispatchList);
                //再删除
                fbsInventoryMapper.addSAPDispatchList(addDispatchList);
            }
            //保存子表
            if(addDispatchListItemList.size()>0){
                fbsInventoryMapper.addSAPDispatchLists(addDispatchListItemList);
            }

        }
    }

    public String cWhCode(String CWHCODE){
        if(StringUtils.isNotBlank(CWHCODE)){
            //原材料仓库
            if(CWHCODE.equals("1001")||CWHCODE.equals("1002")||CWHCODE.equals("1003")||CWHCODE.equals("1004")||CWHCODE.equals("1007")){
//                mapItem.put("cWhCode","02");//仓库编码
                return "02";
            }else if(CWHCODE.equals("1006")){//反修库
//                mapItem.put("cWhCode","10");//仓库编码
                return "10";
            }else if(CWHCODE.equals("1000")){//成品仓库
//                mapItem.put("cWhCode","01");//仓库编码
                return "10";
            }else{
//                mapItem.put("cWhCode",CWHCODE);//仓库编码
                return CWHCODE;
            }
        }else{
//            mapItem.put("cWhCode",CWHCODE);//仓库编码
            return CWHCODE;
        }
    }

    public String cstCode(String CSTCODE){
        if(StringUtils.isNotBlank(CSTCODE)){
            if(CSTCODE.equals("601")){
                return "01";
            }else{
                return CSTCODE;
            }
        }else{
            return CSTCODE;
        }
    }

    @Override
    @DS("master")
    public void implementSAPPull() {
        SimpleDateFormat sdf =   new SimpleDateFormat( "yyyyMMddHHmmss" );
        Date nowDate=new Date();//当前时间
        Date endtime=iPullDateService.getMaxEndTime("1");//上一次查询日期
        //保存本次查询时间
        PullDate pullDate=new PullDate();
        pullDate.setEndTime(nowDate);
        pullDate.setType("1");
        iPullDateService.save(pullDate);

        Long start=Long.valueOf(sdf.format(endtime));//上一次查询时间
        Long end=Long.valueOf(sdf.format(nowDate));//当前时间
        System.out.println("开始："+start);
        System.out.println("结束："+end);

        //生产订单
        iFbsMomOrderService.getPullSapMomOrderAll(start,end);
    }

    @Override
    public void implementSAPPullTwo() {
        SimpleDateFormat sdf =   new SimpleDateFormat( "yyyyMMddHHmmss" );
        Date nowDate=new Date();//当前时间
        Date endtime=iPullDateService.getMaxEndTime("2");//上一次查询日期
        //保存本次查询时间
        PullDate pullDate=new PullDate();
        pullDate.setEndTime(nowDate);
        pullDate.setType("2");
        iPullDateService.save(pullDate);

        Long start=Long.valueOf(sdf.format(endtime));//上一次查询时间
        Long end=Long.valueOf(sdf.format(nowDate));//当前时间
        System.out.println("开始："+start);
        System.out.println("结束："+end);
        //检验单
        this.addSAPQMCHECKVOUCHER(start,end);
        //库存存量(全量获取)
        this.addSAPCurrentStock(start,end);
        //产成品主子表
        this.addSAPRdrecord10MainAndItems(start,end);
        //采购订单
        this.addSAPPO_PoMainAndItems(start,end);
        //采购到货
        this.addSAPPuArrivalvouch(start,end);
        //领料单
        this.addSAPMaterialappvouchMainAndItem(start,end);
        //销售出库
        this.addSAPRdrecord32MainAndItem(start,end);
    }

    @Override
    public void implementSAPPullThree() {
        SimpleDateFormat sdf =   new SimpleDateFormat( "yyyyMMddHHmmss" );
        Date nowDate=new Date();//当前时间
        Date endtime=iPullDateService.getMaxEndTime("3");//上一次查询日期
        //保存本次查询时间
        PullDate pullDate=new PullDate();
        pullDate.setEndTime(nowDate);
        pullDate.setType("3");
        iPullDateService.save(pullDate);

        Long start=Long.valueOf(sdf.format(endtime));//上一次查询时间
        Long end=Long.valueOf(sdf.format(nowDate));//当前时间
        System.out.println("开始："+start);
        System.out.println("结束："+end);
        //存货档案
        this.addSAPInventory(start,end);
        //供应商
        this.addSAPVendor(start,end);
    }


    public BigDecimal getDecimalNew(String d){
        if(StringUtils.isEmpty(d)||d.equals("null")||!isNumericzidai(d)){
            d="0.0";
        }
        BigDecimal decimal= new BigDecimal(d);
        return decimal;
    }
    public static boolean isNumericzidai(String str) {
        Pattern pattern = Pattern.compile("-?[0-9]+\\.?[0-9]*");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }
}
