package org.jeecg.modules.fbsMomOrder.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.QueryWrapper;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.util.InterfaceConnUtils;
import org.jeecg.modules.fbsBasedate.entity.FbsTechnologicalProcess;
import org.jeecg.modules.fbsBasedate.entity.FbsTechnologicalProcessItem;
import org.jeecg.modules.fbsBasedate.service.IFbsTechnologicalProcessItemService;
import org.jeecg.modules.fbsBasedate.service.IFbsTechnologicalProcessService;
import org.jeecg.modules.fbsInventory.mapper.FbsInventoryMapper;
import org.jeecg.modules.fbsMomOrder.entity.FbsMomOrder;
import org.jeecg.modules.fbsMomOrder.entity.FbsMomOrderdetail;
import org.jeecg.modules.fbsMomOrder.mapper.FbsMomOrderMapper;
import org.jeecg.modules.fbsMomOrder.mapper.FbsMomOrderdetailMapper;
import org.jeecg.modules.fbsMomOrder.service.IFbsMomOrderService;
import org.jeecg.modules.fbsWorkshopDispatchList.entity.FbsWorkshopDispatchList;
import org.jeecg.modules.fbsWorkshopDispatchList.mapper.FbsWorkshopDispatchListMapper;
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 FbsMomOrderServiceImpl extends ServiceImpl<FbsMomOrderMapper, FbsMomOrder> implements IFbsMomOrderService {
    @Resource
    private FbsMomOrderMapper fbsMomOrderMapper;
    @Resource
    private IFbsMomOrderService iFbsMomOrderService;
    @Resource
    private FbsMomOrderdetailMapper fbsMomOrderdetailMapper;
    @Resource
    private IFbsTechnologicalProcessService iFbsTechnologicalProcessService;
    @Resource
    private IFbsTechnologicalProcessItemService iFbsTechnologicalProcessItemService;

    @Resource
    private FbsInventoryMapper fbsInventoryMapper;

    @Resource
    private FbsWorkshopDispatchListMapper fbsWorkshopDispatchListMapper;

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

    @Override
    public List<Map<String,String>> getIsOnlyByCbatch(List<String> cBatchList) {
        return fbsMomOrderMapper.getIsOnlyByCbatch(cBatchList);
    }



    @Override
    @DS("master")
    public void getPullSapMomOrderAll(Long start,Long end) {
//        Map<String,Object> fbsMomOrderdetail=new LinkedHashMap<>();
//        fbsMomOrderdetail.put("id",UUID.randomUUID().toString());
//        fbsMomOrderdetail.put("MoDId","123");//生产订单明细id（SAP生产订单号）
//        fbsMomOrderdetail.put("MoId","1234");//生产订单id（SAP生产订单号）
//        fbsMomOrderdetail.put("InvCode","1235");//存货编码
//        fbsMomOrderdetail.put("CostItemName","12356");//项目名称
//        fbsMomOrderdetail.put("Qty","123");//数量
//        fbsMomOrderdetail.put("SortSeq",1);//行号
//        fbsMomOrderdetail.put("QualifiedInQty",2);//入库数量
//        fbsMomOrderdetail.put("Status","123");//状态
////        try {
//            fbsMomOrderdetail.put("CloseTime","2021-02-02");//关闭时间
////        } catch (ParseException e) {
////            e.printStackTrace();
////        }
//        fbsMomOrderdetail.put("RelsUser","666");//审核人
//        fbsMomOrderdetailMapper.insertMomOrderDetailSap(fbsMomOrderdetail);
//        JSONObject jsonObject=JSONObject.parseObject("{\"aa\":\"bb\",\"AUFNR\":\"bb\",\"POST1\":\"bb\",\"ERDAT\":\"2021-01-01 12:00:00\",\"aa\":\"bb\"}");
//        JSONArray jsonArray=JSONArray.parseArray("[{\"moid\":\"bb\",\"item1\":[{\"MoCode\":\"cc\"}]}]");
        //传入参数
        String jsonSting="{\"TIMELIMIT\":{\"ST\":\""+start+"\",\"ET\":\""+end+"\"},\"COMMON_INFO_REQ\":{\"API_NO\":\"KANB00001\",\"GUID\":\""+UUID.randomUUID().toString()+"\",\"USERID\":\"USERNAME\"}}";
        JSONObject jsonObjectP=JSONObject.parseObject(JSONObject.parse(jsonSting).toString());
        //获取接收数据
        JSONObject jsonObjectResults= InterfaceConnUtils.doPost(jsonObjectP,"");
        JSONArray jsonArray=new JSONArray();


        //判断是否接收成功
        if(jsonObjectResults.getJSONObject("STATUS").get("TYPE").toString().equals("S")){
            List<FbsMomOrder> fbsMomOrderList=new ArrayList<>();//生产订单数据
            List<Map<String,Object>> fbsMomOrderdetailList=new ArrayList<>();//生产订单明细
            List<Map<String,Object>> momMorderList=new ArrayList<>();//生产订单资料
            List<Map<String,Object>> malList=new ArrayList<>();//生产订单子件
            List<String> moIDList=new ArrayList<>();
            //接收成功
            jsonArray=jsonObjectResults.getJSONArray("RESULTS");
            for(int a=0;a<jsonArray.size();a++) {
                JSONObject jsonObject = jsonArray.getJSONObject(a);
                String STATUS = String.valueOf(jsonObject.get("STATUS")).trim();//状态
                if(StringUtils.isNotBlank(STATUS)&&STATUS.equals("REL 标记")) {
                    //根据订单号修改状态为删除
//                    fbsMomOrderdetailMapper.updateOrderdetailStatus(String.valueOf(jsonObject.get("MOID")));
                    moIDList.add(String.valueOf(jsonObject.get("MOID")));
                }else{
                //生产订单数据
                FbsMomOrder fbsMomOrder = new FbsMomOrder();
//                fbsMomOrder.setId(UUID.randomUUID().toString());
                fbsMomOrder.setMoid(String.valueOf(jsonObject.get("MOID")));//生产订单id（SAP生产订单号）
                fbsMomOrder.setMocode(String.valueOf(jsonObject.get("MOCODE")));//生产订单号
                fbsMomOrder.setDefine12(String.valueOf(jsonObject.get("DEFINE12")));//项目名称
                fbsMomOrder.setCostItemCode(String.valueOf(jsonObject.get("CostItemCode")));//项目编码
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                if (StringUtils.isNotBlank(String.valueOf(jsonObject.get("CREATETIME")))) {
                    try {
                        String DPODATE = String.valueOf(jsonObject.get("CREATETIME"));
                        DPODATE = DPODATE + " 00:00:00";
                        fbsMomOrder.setCreatetime(sdf.parse(DPODATE));//创建时间
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                } else {
                    fbsMomOrder.setCreatetime(null);//创建时间
                }
//                fbsMomOrder.put("create_time",sdf.format(new Date()));//创建时间
                //保存生产订单
//                fbsMomOrderMapper.insert(fbsMomOrder);


                fbsMomOrderList.add(fbsMomOrder);


                //生产订单明细
                //        FbsMomOrderdetail fbsMomOrderdetail=new FbsMomOrderdetail();
                Map<String, Object> fbsMomOrderdetail = new LinkedHashMap<>();
                fbsMomOrderdetail.put("id", UUID.randomUUID().toString());
                fbsMomOrderdetail.put("MoDId", String.valueOf(jsonObject.get("MOID")));//生产订单明细id（SAP生产订单号）
                fbsMomOrderdetail.put("MoId", String.valueOf(jsonObject.get("MOID")));//生产订单id（SAP生产订单号）
                String InvCode = String.valueOf(jsonObject.get("INVCODE"));//存货编码
                //判断是否无物料
                if (InvCode == null || InvCode.equals("")) {//无物料则生成物料
                    SimpleDateFormat df = new SimpleDateFormat("yyMMdd");//设置日期格式
                    String InvCodeNew = df.format(new Date())+((int)((Math.random()*9+1)*1000));//时间+四位随机数
                    fbsMomOrderdetail.put("InvCode", InvCodeNew);//存货编码
                    //保存存货
                    Map<String, Object> mapAdd = new HashMap<>();
                    mapAdd.put("id", UUID.randomUUID().toString());
                    mapAdd.put("cInvCode", InvCodeNew);
                    mapAdd.put("cInvName", String.valueOf(jsonObject.get("INVNAME")));
                    mapAdd.put("cInvDefine13", getDecimalNew(String.valueOf(jsonObject.get("STANDARDWORKINGHOURSZ"))));
                    mapAdd.put("iSafeNum", 0.0);
                    mapAdd.put("cInvCCode", "无物料");
                    mapAdd.put("cInvCName", "无物料");
                    fbsInventoryMapper.addInventory(mapAdd);
                    InvCode = InvCodeNew+"";
                }
                fbsMomOrderdetail.put("InvCode", InvCode);//存货编码
                fbsMomOrderdetail.put("CostItemName", String.valueOf(jsonObject.get("COSTITEMNAME")));//项目名称
                fbsMomOrderdetail.put("cost_item_code", String.valueOf(jsonObject.get("CostItemCode")));//项目编码
                fbsMomOrderdetail.put("Qty", String.valueOf(jsonObject.get("QTY")));//数量
                fbsMomOrderdetail.put("SortSeq", Integer.parseInt(jsonObject.get("SORTSEQ").toString()));//行号
                fbsMomOrderdetail.put("QualifiedInQty", jsonObject.get("QUALIFIEDINQTY"));//入库数量

                fbsWorkshopDispatchListMapper.updateSAPstateByCode(String.valueOf(jsonObject.get("MOCODE")), STATUS);//修改派工单的SAP订单状态
                if (StringUtils.isNotBlank(STATUS)) {
                    if (STATUS.equals("REL")) {//审核
                        fbsMomOrderdetail.put("Status", 3);//特殊原因改为审核
                    } else if (STATUS.equals("REL PCNF")) {//审核
                        fbsMomOrderdetail.put("Status", 3);
                    } else if (STATUS.equals("REL CNF")) {//关闭
                        fbsMomOrderdetail.put("Status", 4);
                    } else if (STATUS.equals("REL 标记")) {//删除
                        fbsMomOrderdetail.put("Status", 5);
                    } else {//未识别
                        fbsMomOrderdetail.put("Status", 0);
                    }
                    fbsMomOrderdetail.put("SAPStatus", STATUS);//SAP状态
                } else {
                    fbsMomOrderdetail.put("Status", 0);//状态
                    fbsMomOrderdetail.put("SAPStatus", "");//SAP状态
                }
//                fbsMomOrderdetail.put("CloseTime",String.valueOf(jsonObject.get("CLOSETIME")));//关闭时间
                if (StringUtils.isNotBlank(String.valueOf(jsonObject.get("CLOSETIME")))) {
                    try {
                        String CLOSETIME = String.valueOf(jsonObject.get("CLOSETIME"));
                        SimpleDateFormat sdff = new SimpleDateFormat("yyyyMMddHHmmss");
                        Date date = sdff.parse(CLOSETIME);
                        fbsMomOrderdetail.put("CloseTime", date);//关闭时间
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                } else {
                    fbsMomOrderdetail.put("CloseTime", null);//关闭时间
                }
                fbsMomOrderdetail.put("RelsUser", String.valueOf(jsonObject.get("RELSUSER")));//审核人
                fbsMomOrderdetail.put("pull_date", end + "");//拉取时间
//                fbsMomOrderdetailMapper.insertMomOrderDetailSap(fbsMomOrderdetail);
                fbsMomOrderdetailList.add(fbsMomOrderdetail);
                //获取存货对应的标准工时存取到存货档案中
                BigDecimal standardWorkingHoursZ = getDecimalNew(String.valueOf(jsonObject.get("STANDARDWORKINGHOURSZ")));
                fbsInventoryMapper.updateCInvDefine13ByCInvCode(standardWorkingHoursZ, String.valueOf(jsonObject.get("INVCODE")));

                //生产订单资料
                Map<String, Object> momMorder = new HashMap<>();
                momMorder.put("id", UUID.randomUUID().toString());
                momMorder.put("MoDId", String.valueOf(jsonObject.get("MOID")));//生产订单明细id
                if (StringUtils.isNotBlank(String.valueOf(jsonObject.get("CREATETIME")))) {
                    try {
                        String STARTDATE = String.valueOf(jsonObject.get("STARTDATE"));
                        STARTDATE = STARTDATE + " 00:00:00";
                        momMorder.put("StartDate", sdf.parse(STARTDATE));//开工时间
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                } else {
                    momMorder.put("StartDate", null);//开工时间
                }
                if (StringUtils.isNotBlank(String.valueOf(jsonObject.get("DUEDATE")))) {
                    try {
                        String DUEDATE = String.valueOf(jsonObject.get("DUEDATE"));
                        DUEDATE = DUEDATE + " 00:00:00";
                        momMorder.put("DueDate", sdf.parse(DUEDATE));//完工时间
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                } else {
                    momMorder.put("DueDate", null);//完工时间
                }
                momMorder.put("pull_date", end + "");//拉取时间
//                fbsMomOrderdetailMapper.insertMomMorderSap(momMorder);
                momMorderList.add(momMorder);
//            try {
//                map.put("StartDate",sdf.parse( String.valueOf(jsonObject.get("StartDate")) ));//开工时间
//            } catch (ParseException e) {
//                e.printStackTrace();
//            }
//            try {
//                map.put("DueDate",sdf.parse( String.valueOf(jsonObject.get("DueDate")) ));//完工时间
//            } catch (ParseException e) {
//                e.printStackTrace();
//            }

                //生产订单子件信息
//                List<Map<String,Object>> malList=new ArrayList<>();
                JSONArray item1 = jsonObject.getJSONArray("COMPS");
                if (item1 != null && item1.size() > 0) {
                    for (int i = 0; i < item1.size(); i++) {
                        Map<String, Object> moal = new HashMap<>();
                        moal.put("id", UUID.randomUUID().toString());
                        moal.put("MoDId", String.valueOf(item1.getJSONObject(i).get("MOCODE")));//生产订单明细

                        moal.put("Qty", isNULLD(String.valueOf(item1.getJSONObject(i).get("QTY"))));//数量
                        moal.put("IssQty", isNULLD(String.valueOf(item1.getJSONObject(i).get("ISSQTY"))));//已领量  
                        moal.put("InvCode", String.valueOf(item1.getJSONObject(i).get("INVCODE")));//存货编码  
                        moal.put("pull_date", end + "");//拉取时间
                        malList.add(moal);
                    }
//                    fbsMomOrderdetailMapper.insertMomMoallocateBatchSap(malList);
//                    malList.add()
                }

                //工艺
                JSONArray PROCS = jsonObject.getJSONArray("PROCS");
                if (PROCS != null && PROCS.size() > 0) {
                    //获取物料编码
                    String invcode = InvCode+"";
                    //获取工艺主数据名称
                    String nameMain = String.valueOf(jsonObject.getJSONArray("PROCS").getJSONObject(0).get("OPERATIONDESCRIBE"));
                    //判断是否存在工艺
                    QueryWrapper<FbsTechnologicalProcess> fbsTechnologicalProcessQueryWrapper = new QueryWrapper<>();
                    fbsTechnologicalProcessQueryWrapper.lambda().eq(FbsTechnologicalProcess::getName, invcode);
                    List<FbsTechnologicalProcess> fbsTechnologicalProcessList = iFbsTechnologicalProcessService.list(fbsTechnologicalProcessQueryWrapper);
                    //不存在则添加新工艺
                    if (fbsTechnologicalProcessList == null || fbsTechnologicalProcessList.size() <= 0) {
                        FbsTechnologicalProcess fbsTechnologicalProcess = new FbsTechnologicalProcess();
                        fbsTechnologicalProcess.setName(invcode);
                        fbsTechnologicalProcess.setMemo(nameMain);//备注中存工艺主名称
                        fbsTechnologicalProcess.setCreateBy("adminSAP");
                        fbsTechnologicalProcess.setPullDate(end + "");
                        iFbsTechnologicalProcessService.save(fbsTechnologicalProcess);//插入数据库
                        //获取工艺明细数据
                        List<FbsTechnologicalProcessItem> fbsTechnologicalProcessItemList = new ArrayList<>();
                        for (int i = 0; i < PROCS.size(); i++) {
                            FbsTechnologicalProcessItem fbsTechnologicalProcessItem = new FbsTechnologicalProcessItem();
                            fbsTechnologicalProcessItem.setFbsTechnologicalProcessId(fbsTechnologicalProcess.getId());//主表id
                            fbsTechnologicalProcessItem.setMemo(String.valueOf(PROCS.getJSONObject(i).get("OPERATIONNUMBER")));//工艺编码
                            fbsTechnologicalProcessItem.setName(String.valueOf(PROCS.getJSONObject(i).get("DESCRIBE")));//工艺明细名称
                            fbsTechnologicalProcessItem.setCreateBy("adminSAP");
                            fbsTechnologicalProcessItem.setStandardWorkingHours(getDecimalNew(String.valueOf(PROCS.getJSONObject(i).get("DESCRIBE"))));//标准工时
                            fbsTechnologicalProcessItem.setSort(i);//排序
                            fbsTechnologicalProcessItemList.add(fbsTechnologicalProcessItem);
                        }
                        iFbsTechnologicalProcessItemService.saveBatch(fbsTechnologicalProcessItemList);//插入数据库
                    }
                }
            }
            }
            //生产订单
            if(fbsMomOrderList.size()>0){
                //再新增
                fbsMomOrderdetailMapper.deleteSAPMomOrder(fbsMomOrderList);//删除订单
                fbsMomOrderdetailMapper.deleteSAPMomOrderdetail(fbsMomOrderList);//删除订单明细
                iFbsMomOrderService.saveBatch(fbsMomOrderList);
            }
            //生产订单明细
            if(fbsMomOrderdetailList.size()>0){
                fbsMomOrderdetailMapper.insertSAPMomOrderdetail(fbsMomOrderdetailList);
                fbsMomOrderdetailMapper.deleteSAPMomMorder(fbsMomOrderdetailList);//根据明细id删除订单资料
                fbsMomOrderdetailMapper.deleteMomMoallocateBatchSap(fbsMomOrderdetailList);//根据明细id删除订单子件
            }
            //生产订单资料
            if(momMorderList.size()>0){
                fbsMomOrderdetailMapper.insertSAPMomMorder(momMorderList);
            }
            //生产订单子件
            if(malList.size()>0){
                fbsMomOrderdetailMapper.insertMomMoallocateBatchSap(malList);
            }
            //修改删除的
            if(moIDList!=null&&moIDList.size()>0) {
                fbsMomOrderdetailMapper.updateOrderdetailStatus(moIDList);//修改删除的
            }
        }


//        System.out.println(JSONObject.toJSON(fbsMomOrder));
    }

    public Double isNULLD(String num){
        if(StringUtils.isNotBlank(num)){
            return Double.valueOf(num);
        }else{
            return 0.0;
        }
    }

    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;
    }
}
