package com.huigou.topsun.sap.nonProdApply.application.impl;


import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.huigou.context.Operator;
import com.huigou.topsun.base.bsnMessage.appliction.BsnMessageApplication;
import com.huigou.topsun.base.bsnMessage.domain.*;
import com.huigou.topsun.base.bsnMessage.repository.BsnMessageSponsorRepository;
import com.huigou.topsun.sap.common.DefaultHttpClient;
import com.huigou.topsun.sap.common.application.SapMutualEpLogApplication;
import com.huigou.topsun.sap.common.domain.SapResult;
import com.huigou.topsun.sap.nonProdApply.application.NonProdApplyDeptApplication;

import com.huigou.topsun.sap.nonProdApply.domain.NonProdApplyBaseInfo;
import com.huigou.topsun.sap.nonProdApply.domain.SapNonProdApplyDept;
import com.huigou.topsun.sap.nonProdApply.domain.query.NonProdApplyBaseInfoQueryRequest;
import com.huigou.topsun.sap.nonProdApply.domain.vo.*;
import com.huigou.topsun.sap.nonProdApply.repository.NonProdApplyBaseInfoRepository;
import com.huigou.topsun.sap.nonProdApply.repository.NonProdApplyDeptRepository;
import com.huigou.uasp.bmp.common.application.BaseApplication;

import com.huigou.uasp.bmp.operator.OperatorApplication;
import com.huigou.util.ClassHelper;
import com.huigou.util.SDO;
import com.huigou.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.Column;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class NonProdApplyDeptApplicationImpl extends BaseApplication implements NonProdApplyDeptApplication {
    private final static Logger LOG = LoggerFactory.getLogger(NonProdApplyDeptApplicationImpl.class);
    @Autowired
    NonProdApplyDeptRepository nonProdApplyDeptRepository;
    @Autowired
    BsnMessageApplication bsnMessageApplication;
    @Autowired
    NonProdApplyBaseInfoRepository nonProdApplyBaseInfoRepository;

    @Autowired
    com.huigou.topsun.base.bsnMessage.repository.BsnMessageExecuteRepository bsnMessageExecuteRepository;
     @Autowired
    BsnMessageSponsorRepository bsnMessageSponsorRepository;
    @Autowired
    DefaultHttpClient defaultHttpClient;
    @Autowired
    SapMutualEpLogApplication sapMutualEpLogApplication;
    @Resource
    private OperatorApplication operatorApplication;


    @Override
    //业务的保存和提交
    public Map<String,Object> saveSapNonProdApplyDept(SDO sdo){
        Map<String,Object> map = new HashMap<>();
        map.put("result","");
        String businessCode=sdo.getString("businessCode");
        String baseId=sdo.getString("id");
        String genericName=sdo.getString("genericName");
        Integer active=sdo.getInteger("active");
        String meId=sdo.getString("meId");
        String opstatus=sdo.getString("opstatus");  //操作状态
        NonProdApplyBaseInfo baseInfo=nonProdApplyBaseInfoRepository.findOne(sdo.getString("id"));
        //判断汉语品名是否已经存在
        if (StringUtil.isNotBlank(sdo.getString("maktx"))) {
            List <Map <String,Object>>baseList=(List <Map <String,Object>>)sdo.getProperty("baseList");
            boolean isSame=false;
            if (baseList.size()>0){
                Map maps=baseList.get(0);
                String nbid=maps.get("id").toString();

               if ("new".equals(baseInfo.getMaintenanceType())){
                  if (!nbid.equals(baseInfo.getId())){
                     isSame=true;
                  }
               } else { //变更、扩展的
                   String  rootId=getRootId(baseInfo.getId(),baseList);
                   if (!rootId.equals(nbid)){
                       isSame=true;
                   }
               }
                if (isSame) {
                    throw new RuntimeException("汉语品名:" + sdo.getString("maktx") + "已经存在！请检查输入");
                }
            }

           /* List<SapNonProdApplyDept> prodApplyDeptList = nonProdApplyDeptRepository.findByMaktx(sdo.getString("maktx").trim());
            if (prodApplyDeptList.size() > 0) {
                for (SapNonProdApplyDept prodApplyDept : prodApplyDeptList) {
                    NonProdApplyBaseInfo parentBaseInfo = nonProdApplyBaseInfoRepository.findOne(prodApplyDept.getBaseInfoId());
                    if (parentBaseInfo != null) {
                        if (baseInfo.getId().equals(parentBaseInfo.getId()) //表示是当前单据 忽略掉
                                || parentBaseInfo.getStatusId() == 5  //排除终止的
                                || (baseInfo.getSourceId()!=null&&baseInfo.getSourceId().equals(parentBaseInfo.getId()))
                                || (baseInfo.getSourceId()!=null&&baseInfo.getSourceId().equals(parentBaseInfo.getSourceId())) //扩展与变更
                        ) {
                        } else {
                            throw new RuntimeException("汉语品名:" + sdo.getString("maktx") + "已经存在！请检查输入");
                        }
                    }
                }
            } */
        }

        baseInfo.setBusinessUsage(sdo.getString("businessUsage"));
        if (StringUtil.isNotBlank(sdo.getString("distribute"))){ //是否已分发
            baseInfo.setDistribute(2);
        } else {
            baseInfo.setDistribute(sdo.getInteger("active"));
        }
        if ("K".equals(businessCode)){  //首页进入的基本信息维护
            baseInfo.setGenericName(sdo.getString("genericName"));
            baseInfo.setApplicableStandard(sdo.getString("applicableStandard"));
            baseInfo.setBaseUnit(sdo.getString("baseUnit"));
            baseInfo.setSpecifications(sdo.getString("specifications"));
            baseInfo.setMaterial(sdo.getString("material"));
            baseInfo.setDesign(sdo.getString("design"));
            baseInfo.setSize(sdo.getString("size"));
         //   baseInfo.setGenericName(sdo.getString("brand"));

            baseInfo.setMaterialUsage(sdo.getString("materialUsage"));
            baseInfo.setItemAttributes(sdo.getString("itemAttributes"));
        }
        if ("".equals(businessCode)){ //基本信息维护
            baseInfo.setMaktxRemZh(sdo.getString("maktxRemZh"));
            baseInfo.setMaktxRemEn(sdo.getString("maktxRemEn"));
            baseInfo.setTextDescription(sdo.getString("textDescription"));
        }
        if ("V".equals(businessCode)) { //销售视图
            baseInfo.setBrand(sdo.getString("brand"));
            baseInfo.setBrand(sdo.getString("brandName"));
        }

        nonProdApplyBaseInfoRepository.save(baseInfo);

        NonProdApplyDeptVo deptVo=sdo.toObject(NonProdApplyBasicVo.class);
     /*   switch (businessCode) {
            case "K":
                deptVo = sdo.toObject(NonProdApplyBasicVo.class);
                break;
            case "C":
                deptVo = sdo.toObject(NonProdApplyClassVo.class);
                break;
            case "V":  //销售
                deptVo = sdo.toObject(NonProdApplySaleVo.class);
                break;
            case "E": //采购
                deptVo = sdo.toObject(NonProdApplyPurchaseVo.class);
                break;
            case "D": //MRP
                deptVo = sdo.toObject(NonProdApplyMRPVo.class);
                break;
            case "A": //生产
                deptVo = sdo.toObject(NonProdApplyProduceVo.class);
                break;
            case "L":  //存储
                deptVo = sdo.toObject(NonProdApplyStoreVo.class);
                break;
            case "S":  //仓库
                deptVo = sdo.toObject(NonProdApplyWarehouseVo.class);
                break;
            case "Q": //质量
                deptVo = sdo.toObject(NonProdApplyMassVo.class);
                break;
            case "B":  //财务
                deptVo = sdo.toObject(NonProdApplyFinancialVo.class);
                break;
            case "G":  //成本
                deptVo = sdo.toObject(NonProdApplyCostVo.class);
                break;
            default:
                deptVo = sdo.toObject(NonProdApplyBasicVo.class);
        }*/
       // SapNonProdApplyDept nonProdApplyDeptObj = sdo.toObject(SapNonProdApplyDept.class);
        //nonProdApplyDeptObj.setBaseInfoId(sdo.getId());
        deptVo.setBaseInfoId(sdo.getId());
        SapNonProdApplyDept nonProdApplyDept=nonProdApplyDeptRepository.findByBaseInfoId(sdo.getId());
        if (nonProdApplyDept==null){
            nonProdApplyDept=new SapNonProdApplyDept();
        }
        ClassHelper.copyProperties(deptVo,nonProdApplyDept);

        nonProdApplyDept = this.save(nonProdApplyDept);
        String applyDeptId=sdo.getString("applyDeptId");
        //分发操作
       /* if ((StringUtil.isBlank(businessCode)||"INIT_DPT".equals(businessCode))&&"2".equals(sdo.getString("distribute"))) { //业务类型为空 ，表示是基本信息进入的  才保存分发信息
            //保存部门分发任务
            //获取分发的部门与人员信息
            ObjectMapper objectMapper = new ObjectMapper();
            String deptStaffJSON = sdo.getString("deptStaff");
            List<Map<String, String>> deptStaffList = null;
            try {
                deptStaffList = objectMapper.readValue(deptStaffJSON, new TypeReference<List<Map<String, String>>>() {
                });
                if (deptStaffList.size()<1){
                    throw new RuntimeException("未选择对应的分发人员！");
                }
            } catch (JsonProcessingException e) {
                throw new RuntimeException("JSON转换失败：" + e);
            }
           if (StringUtils.isBlank(genericName)) {
                genericName=nonProdApplyDept.getMaktx()!=null?nonProdApplyDept.getMaktx():"";
            }
            saveDeptStaff(deptStaffList, nonProdApplyDept.getApplyDeptId(),genericName);
        }  */
        //不是分发的  提交后产生领导的待办信息
        if (StringUtil.isBlank(businessCode)&&active ==1&&StringUtil.isBlank(sdo.getString("distribute"))){ //基本信息提交后  发送待分发的待办消息
           //调用SAP进行校验
            baseInfo.setCheckFlag("X");
            String  backStr=sendSapMaterialData(baseInfo,nonProdApplyDept);
           if (StringUtil.isNotBlank(backStr)) {
               throw new RuntimeException(backStr);
           }else {
               //先结束 基本信息的待办
               BsnMessageSponsor bsnMessageSponsor2 = bsnMessageSponsorRepository.findByBusinessId(baseInfo.getId());
               if (bsnMessageSponsor2 != null) {
                   List<BsnMessageExecute> bsnMsgList2 = bsnMessageExecuteRepository.findAllByMessageSponsorId(bsnMessageSponsor2.getId());
                   for (BsnMessageExecute bsnMessageExecute : bsnMsgList2) {
                       if ("HYZY".equals(bsnMessageExecute.getBusinessCode())) {
                           bsnMessageApplication.submitTask(bsnMessageExecute.getId());
                       }
                   }
               }
               //产生领导确认的待办信息
               Map backMap = new HashMap();
               backMap.put("TYPE", "D");
               backMap.put("title", nonProdApplyDept.getMaktx()); //汉语品名
               backMap.put("positionCode", "LDQR");
               saveBsnMessageData(baseInfo, backMap);
           }
        }
      /*  if (active!=null&&active == 2&&opstatus.equals("1")){//各部门都提交后，隐藏消息
            bsnMessageApplication.submitTask(meId);
            //如果所有的业务部门处理完 ，则推送SAP
            BsnMessageSponsor bsnMessageSponsor=bsnMessageSponsorRepository.findByBusinessId(nonProdApplyDept.getApplyDeptId());
            boolean canSended=true;
            if (bsnMessageSponsor!=null){
                List<BsnMessageExecute> bsnMsgList = bsnMessageExecuteRepository.findAllByMessageSponsorId(bsnMessageSponsor.getId());
                for (BsnMessageExecute bsnMessageExecute : bsnMsgList) {
                    if (!"system".equals(bsnMessageExecute.getBusinessCode())&&
                        !"HYZY".equals(bsnMessageExecute.getBusinessCode())&&
                        !"INIT_DPT".equals(bsnMessageExecute.getBusinessCode())
                       &&bsnMessageExecute.getActive() == 0) {
                        canSended=false;
                        break;
                    }
                }
                //结束货源专员的待办
                BsnMessageSponsor bsnMessageSponsor2=bsnMessageSponsorRepository.findByBusinessId(baseInfo.getId());
                if (bsnMessageSponsor2!=null){
                    List<BsnMessageExecute> bsnMsgList2 = bsnMessageExecuteRepository.findAllByMessageSponsorId(bsnMessageSponsor2.getId());
                    for (BsnMessageExecute bsnMessageExecute : bsnMsgList2) {
                        if ("HYZY".equals(bsnMessageExecute.getBusinessCode())) {
                            bsnMessageApplication.submitTask(bsnMessageExecute.getId());
                        }
                    }
                }
            }
            if (canSended) {
              String backStr=sendSapData(baseInfo, nonProdApplyDept);
                map.put("result",backStr);
            }
        }*/

        map.put("applyDeptId",nonProdApplyDept.getApplyDeptId());
        return map;
    }

    private String getRootId(String id,List <Map <String,Object>>baseList){
        String rootId="";
        for (Map map:baseList){
            if (id.equals(map.get("id").toString())) {
                if (StringUtils.isBlank(map.get("sourceId").toString())) {
                    rootId = map.get("id").toString();
                    break;
                } else {
                    rootId = getRootId(map.get("sourceId").toString(), baseList);
                }
            }
        }
        return rootId;
    }
    @Override
    public SapNonProdApplyDept save(SapNonProdApplyDept sapNonProdApplyDept){
        return nonProdApplyDeptRepository.save(sapNonProdApplyDept);
    }
    @Override
    //保存业务部门的待办消息
    public void saveDeptStaff(List<Map<String, String>> deptStaffList,String bussinessId,String genericName){
        //封装分发数据
        BsnMessageSponsor bsnMessageSponsor = new BsnMessageSponsor();
        bsnMessageSponsor.setTaskSponsor(this.getOperator().getUserId());
        bsnMessageSponsor.setTitle(genericName);//通用品名
        bsnMessageSponsor.setExecutorUrl("sapNonProdApplyNext/fillInNonProdApplyDept.do");
        bsnMessageSponsor.setBusinessId(bussinessId);
        bsnMessageSponsor.setCreateDate(new Date());
        bsnMessageSponsor.setStatus(0);

        for (Map<String, String> stringMap : deptStaffList) {
            BsnMessageExecute messageExecute = new BsnMessageExecute();
            String userCode = stringMap.get("userCode");
            String deptName = stringMap.get("deptName");
            String deptCode = stringMap.get("deptCode");
            String[] split = userCode.split("@");
            messageExecute.setTaskExecute(split[0]);
            messageExecute.setBusinessCode(deptCode);
            messageExecute.setActive(ActiveStatus.UNFINISHED.getValue());
            messageExecute.setUpdateDate(new Date());
            messageExecute.setTaskDescribe(deptName+"部门数据维护");
            bsnMessageSponsor.addExecute(messageExecute);
        }
        //保存任务
        bsnMessageApplication.keepTasks(bsnMessageSponsor);

    }
    /**
     * 分发任务
     * @param sdo
     */
    @Override
    public void distributeSapNonProdApplyDept(SDO sdo) {
        //获取分发的部门与人员信息
        ObjectMapper objectMapper = new ObjectMapper();
        String deptStaffJSON = sdo.getString("deptStaff");
        List<Map<String, String>> deptStaffList = null;
        try {
            deptStaffList = objectMapper.readValue(deptStaffJSON, new TypeReference<List<Map<String, String>>>() {});
            if (deptStaffList.size()<1){
                throw new RuntimeException("未选择对应的分发人员！");
            }
        } catch (JsonProcessingException e) {
            throw new RuntimeException("JSON转换失败："+e);
        }
        //将状态为保存未分发的全部修改为分发未完成
        Map<String, Object> map = this.saveSapNonProdApplyDept(sdo);

        //结束分发任务的待办信息
        NonProdApplyBaseInfo nonProdApplyBaseInfo=nonProdApplyBaseInfoRepository.findOne(sdo.getString("id"));
        //SapNonProdApplyDept  sapNonProdApplyDept=nonProdApplyDeptRepository.findByBaseInfoId(sdo.getString("id"));
       // if(nonProdApplyBaseInfo.getMaintenanceType().equals("new")) { //新申请的 分发后结束分发人的待办信息 06.17
            BsnMessageSponsor bsnMessageSponsor=bsnMessageSponsorRepository.findByBusinessId(nonProdApplyBaseInfo.getId());
            if (bsnMessageSponsor!=null){
                List<BsnMessageExecute> bsnMsgList = bsnMessageExecuteRepository.findAllByMessageSponsorId(bsnMessageSponsor.getId());
                for (BsnMessageExecute bsnMessageExecute : bsnMsgList) { //目前指定到岗位 货源专员 HYZY
                    if ("HYZY".equals(bsnMessageExecute.getBusinessCode())) {
                        bsnMessageApplication.submitTask(bsnMessageExecute.getId());
                    }
                }
            }
      //  }
         //发布各业务人员待处理的任务
        bsnMessageApplication.publishTasks((String) map.get("applyDeptId"));


    }

    @Override
    public SapNonProdApplyDept getNonProdApplyDeptById(String id) {
        return nonProdApplyDeptRepository.findByApplyDeptId(id);
    }

    @Override
    public SapNonProdApplyDept getNonProdApplyDeptByBaseInfoId(String baseInfoId) {
        return nonProdApplyDeptRepository.findByBaseInfoId(baseInfoId);
    }
    @Override
    public SapNonProdApplyDept getNonProdApplyDeptByMatnr(String matnr){
        return nonProdApplyDeptRepository.findByMatnr(matnr);
    }
    @Override
    public void deleteSapNonProdApplyDept(SapNonProdApplyDept sapNonProdApplyDept){
        if (sapNonProdApplyDept!=null){
            nonProdApplyDeptRepository.delete(sapNonProdApplyDept);
        }
    }

    @Override
    public void rejectNonProdApplyDept(SDO sdo) {
        String meId = sdo.getString("meId");
        Map<String,Object> map = new HashMap<>();
        String auditDept = sdo.getString("auditDept");
        List<String> deptList = Arrays.asList(auditDept.split(","));
        for (String key : deptList) {
            map.put(key,sdo.getString(key));
        }
        bsnMessageApplication.rejectTasksByMeId(map,meId);
    }

    /**
     * 远程调用sap接口，传递数据
     */
    public String sendSapMaterialData(NonProdApplyBaseInfo baseInfo,SapNonProdApplyDept applyDept) {
        Map<String, Object> map = new HashMap<>();
        String backStr="";
        ProdApplyToSapVO sapVO=new ProdApplyToSapVO();
        ClassHelper.copyProperties(baseInfo,sapVO);
        ClassHelper.copyProperties(applyDept,sapVO);
        sapVO.setMaktxRemZh(baseInfo.getMaktxRemZh());
        sapVO.setMaktxRemEn(baseInfo.getMaktxRemEn());

        //中英文语言代码
        if (StringUtil.isNotBlank(sapVO.getMaktx())){
            sapVO.setSpars("1");
        }
        if (StringUtil.isNotBlank(sapVO.getMaktxEn())){
            sapVO.setSparsEn("E");
        }
        if ("0".equals(sapVO.getXchpf())){ //批次管理 否 传递空
            sapVO.setXchpf("");
        }
        if ("0".equals(sapVO.getNcost())){ //不参与成本核算 否 传递空
            sapVO.setNcost("");
        }
        if ("0".equals(sapVO.getHkmat())){ //物料来源 否 传递空
            sapVO.setHkmat("");
        }
        if ("0".equals(sapVO.getEkalr())){ //数量结构 传递空
            sapVO.setEkalr("");
        }
        if (baseInfo.getBusinessUsage().contains("K")){
            sapVO.setPstat(baseInfo.getBusinessUsage());
        }else {
            sapVO.setPstat("K,"+baseInfo.getBusinessUsage());
        }
        if (baseInfo.getBusinessUsage().contains("B")){
            sapVO.setPstat("G,"+sapVO.getPstat());
        }
        sapVO.setBwkey(applyDept.getWerks());
        sapVO.setLosgr(applyDept.getPeinh()); //成本核算的价格单位 默认为定价基数

        sapVO.setUpdkz("I");
        if ("0".equals(sapVO.getInsmk())){
            sapVO.setInsmk("");
        }
        if ("0".equals(sapVO.getRgekz())){
            sapVO.setRgekz("");
        }
        //存储分区标识默认001
        sapVO.setLgbkz("001");
         sapVO.setMbrsh("M");//行业默认M
        if ("0".equals(sapVO.getPerkz())){ //期间标识
           sapVO.setPerkz("");
        }
        //销售单位转换
        if (StringUtil.isNotBlank(sapVO.getVrkme())){
            Map<String,Object> unitsaleMap = new HashMap<>();
            List<Map<String,Object>> unitMapList = new ArrayList<>();
            unitsaleMap.put("MEINH",sapVO.getVrkme());
            unitsaleMap.put("UMREZ",sapVO.getUmrez());
            unitsaleMap.put("UMREN",sapVO.getUmren()); //去掉sale   lxh  03.29
            unitsaleMap.put("MEINS",sapVO.getMeins());
            unitMapList.add(unitsaleMap);
            sapVO.setMapList(unitMapList);
        }
        ObjectMapper objectMapper = new ObjectMapper();
        String url = "bd_mastdata/material";
        String busiType="物料主数据推送SAP";
        if ("product".equals(baseInfo.getKind())){
            url = "bd_mastdata/material02";
            busiType="产品主数据推送SAP";
        }

        /**
         * 封装EP BOM原材料信息
         */
        StringBuilder bomText = new StringBuilder();
        bomText.append(applyDept.getLength())
                .append(",")
                .append(applyDept.getWidthCm())
                .append(",")
                .append(applyDept.getThickness())
                .append(",")
                .append(applyDept.getWeight())
                .append(",")
                .append(applyDept.getSingleThickness());
        sapVO.setBomText(bomText.toString());

        List<ProdApplyToSapVO> mapList = new ArrayList<>();
        mapList.add(sapVO);
        //日志记录

        Map<String, Object> backMap = new HashMap<>();
        backMap.put("businessType", busiType);
        backMap.put("businessId", baseInfo.getId());
        try {
            String paramJson = new ObjectMapper().writeValueAsString(mapList);
            backMap.put("parameter", paramJson);//JSON.toJSONString(mapList));
        } catch (Exception ex){
            //ex.printStackTrace();
            LOG.info("数据转换出错:={}", JSON.toJSONString(mapList));
            backMap.put("parameter", JSON.toJSONString(mapList));
        }
        backMap.put("sequence", backMap.get("row"));
        backMap.put("TYPE", "E");
        String errorMsg = "";
        try {
            String result = defaultHttpClient.execute(mapList, url);
            List<Map<String, Object>> resultList = objectMapper.readValue(result, new TypeReference<List<Map<String, Object>>>() {
            });
            Map<String, Object>  returnMap = resultList.get(0);
            if ("S".equals(returnMap.get("TYPE")) && resultList.size()>1){
                returnMap = resultList.get(1);
            }
            mapCopy(backMap,returnMap);
            // resultMap.put("businessType", busiType);
            // resultMap.put("parameter", JSON.toJSONString(map));
            //  resultMap.put("businessId", prodApplyBaseInfo.getId());
            if ("S".equals(returnMap.get("TYPE"))) {
                backMap.put("TYPE", "S");
                backMap.put("MESSAGE",applyDept.getMatnr()+":"+backMap.get("MESSAGE"));
                if (!"product".equals(baseInfo.getKind())) {
                    applyDept.setMatnr((String) backMap.get("MESSAGE_V1"));
                }
                if (StringUtil.isBlank(baseInfo.getCheckFlag())) { //非校验
                    this.nonProdApplyDeptRepository.save(applyDept);
                    baseInfo.setDistribute(2); //已办结
                    nonProdApplyBaseInfoRepository.save(baseInfo);
                }
            } else {
                //更改到到提交状态
                baseInfo.setDistribute(0);
                List<String> messages = resultList
                        .stream()
                        .map(resultMap ->{
                            return (String)resultMap.get("MESSAGE");
                        }).collect(Collectors.toList());
                errorMsg = String.join("；",messages);
                backStr="传输失败:" + errorMsg;
                backMap.put("MESSAGE",backStr);
                nonProdApplyBaseInfoRepository.save(baseInfo);
                //throw new RuntimeException(backStr);
            }
        } catch (Exception e) {
            backMap.put("MESSAGE",applyDept.getMatnr()+":"+errorMsg);
            //sapMutualEpLogApplication.saveSapMutualEpLog(resultMap);
            System.out.println("传输错误了："+e.getMessage());
            backStr="传输失败:" +  errorMsg;
            throw new RuntimeException(backStr);
        } finally {
            sapMutualEpLogApplication.saveSapMutualEpLog(backMap);
            //Operator operator = operatorApplication.createOperatorByPersonMemberId(baseInfo.getPersonMemberId());
            //向货源专员 发重新分发的消息
             backMap.put("title",applyDept.getMaktx());//汉语品名
             backMap.put("positionCode","HYZY");
             if (StringUtil.isBlank(baseInfo.getCheckFlag())) {
                 saveBsnMessageData(baseInfo, backMap);
             }
            return backStr;
        }

    }

    final void mapCopy(Map resultMap, Map paramMap) {
        if (resultMap==null) resultMap=new HashMap();
         if (paramMap==null ) return ;

         Iterator it=paramMap.entrySet().iterator();
        while (it.hasNext()){
           Map.Entry entry=(Map.Entry)it.next();
           Object key=entry.getKey();
           resultMap.put(key,paramMap.get(key)!=null?paramMap.get(key):"");
        }
    }


    /*
     *  审批完成 推送处理基本信息的待办消息
     * 最后一个业务务部门 处理完成推送SAP失败  则向货源专员发起再次分发的待办消息
    * 推送SAP成功则向货源专员 写入一条成功的消息
    */
    public void saveBsnMessageData(NonProdApplyBaseInfo baseInfo,Map<String,Object> backMap) {
        BsnMessageSponsor bsnMessageSponsor = bsnMessageSponsorRepository.findByBusinessId(baseInfo.getId());
        String sql = "select p.id,p.code,p.name,o.dept_name,o.dept_code,o.id person_member_id,o.position_name,o.position_code from sa_opperson p " +
                "left join  sa_oporg  o on p.CODE=o.code where  MAIN_ORG_ID in (select id from sa_oporg where  code='"+backMap.get("positionCode").toString()+"')";
        List<Map<String, Object>> mapLists = this.sqlExecutorDao.queryToListMap(sql);
        for (Map map : mapLists) {
            if (bsnMessageSponsor == null) {
                bsnMessageSponsor = new BsnMessageSponsor();
                bsnMessageSponsor.setTaskSponsor(map.get("id").toString());
                bsnMessageSponsor.setTitle(baseInfo.getGenericName());//通用品名
                if ("product".equals(baseInfo.getKind())) {
                    bsnMessageSponsor.setExecutorUrl("sapNonProdApplyNext/forwardNonProdApplyNext.do?prod=1&isReadOnly=false");
                } else {
                    bsnMessageSponsor.setExecutorUrl("sapNonProdApplyNext/forwardNonProdApplyNext.do?isReadOnly=false");
                }
                //bsnMessageSponsor.setBusinessId(applyDept.getApplyDeptId());
                bsnMessageSponsor.setBusinessId(baseInfo.getId()); //货源专员 存base_info的ID
                bsnMessageSponsor.setCreateDate(new Date());
                bsnMessageSponsor.setStatus(0);
            }

            BsnMessageExecute messageExecute = new BsnMessageExecute();
            messageExecute.setTaskExecute(map.get("id").toString());
            messageExecute.setBusinessCode(map.get("positionCode").toString()); //HYZY
            messageExecute.setActive(ActiveStatus.UNFINISHED.getValue());
            messageExecute.setUpdateDate(new Date());
             String sign="-.";
             String title= backMap.get("title")!=null?backMap.get("title").toString():"";
             String genericName=baseInfo.getGenericName();
            if (StringUtils.isBlank(baseInfo.getGenericName())){
                genericName=title;
            }
            if ("S".equals(backMap.get("TYPE").toString())) {
                messageExecute.setTaskDescribe(title+sign + backMap.get("MESSAGE").toString());
            } else if ("E".equals(backMap.get("TYPE").toString())) {
                messageExecute.setTaskDescribe(title+sign + backMap.get("MESSAGE").toString());
            } else if ("C".equals(backMap.get("TYPE").toString())) {  //审批完成 推送待办的基本信息处理信息
                String mess = sign+"物料维护(";
                if (baseInfo.getMaintenanceType().equals("modify")) {
                    mess = sign+"物料变更(";
                }
                if (baseInfo.getMaintenanceType().equals("extend")) {
                    mess = sign+"物料扩展(";
                }
                if (genericName.equals(title)){
                   title="";
                }
                messageExecute.setTaskDescribe(genericName+ mess + title + ")");
            } else if ("D".equals(backMap.get("TYPE").toString())) {  // 推送待分发的待办信息
                if (genericName.equals(title)){
                    title="";
                } else {
                    title="("+title+")";
                }
                messageExecute.setTaskDescribe(genericName +sign+ "待确认" + title);
            } else if ("P".equals(backMap.get("TYPE").toString())) { //产品数据
                messageExecute.setTaskDescribe(genericName +sign+ "数据维护");
            }
            bsnMessageApplication.saveBsnMessageSponsor(bsnMessageSponsor);
            messageExecute.setMessageSponsorId(bsnMessageSponsor.getId());

            List<BsnMessageExecute> executes = new ArrayList<>();
            executes.add(messageExecute);
            bsnMessageApplication.saveBsnMessageExecute(executes);
        }
    }

    //领导确认
    @Override
    public  Map<String,Object> confirmNonProdApplyDept(SDO sdo){
        Map<String,Object> map = new HashMap<>();
        map.put("result","");
        String confirm=sdo.getString("confirm");
        String baseId=sdo.getString("id");
        NonProdApplyBaseInfo baseInfo=nonProdApplyBaseInfoRepository.findOne(baseId);
        //先结束 领导确认的待办
        BsnMessageSponsor bsnMessageSponsor2=bsnMessageSponsorRepository.findByBusinessId(baseInfo.getId());
        if (bsnMessageSponsor2!=null){
            List<BsnMessageExecute> bsnMsgList2 = bsnMessageExecuteRepository.findAllByMessageSponsorId(bsnMessageSponsor2.getId());
            for (BsnMessageExecute bsnMessageExecute : bsnMsgList2) {
                if ("LDQR".equals(bsnMessageExecute.getBusinessCode())) {
                    bsnMessageApplication.submitTask(bsnMessageExecute.getId());
                }
            }
        }
        SapNonProdApplyDept nonProdApplyDept=nonProdApplyDeptRepository.findByBaseInfoId(sdo.getId());
        if ("2".equals(confirm)){//确认
            // 推送SAP
            baseInfo.setCheckFlag("");
            String backStr=sendSapMaterialData(baseInfo,nonProdApplyDept);
            map.put("result",backStr);
        } else { //回退给货源专员
            //产生货源专员的待办信息
            Map backMap=new HashMap();
            backMap.put("TYPE","D");
            backMap.put("title",nonProdApplyDept.getMaktx()); //汉语品名
            backMap.put("positionCode","HYZY");
            saveBsnMessageData(baseInfo,backMap);
            baseInfo.setDistribute(0);//改回待 提交状态
            nonProdApplyBaseInfoRepository.save(baseInfo);
        }
        return map;
    }
}
