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

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.huigou.cache.DictUtil;
import com.huigou.cache.SystemCache;
import com.huigou.context.Operator;
import com.huigou.context.OrgUnit;
import com.huigou.data.domain.model.CommonDomainConstants;
import com.huigou.data.domain.model.Creator;
import com.huigou.data.query.model.QueryDescriptor;
import com.huigou.data.query.model.QueryModel;
import com.huigou.topsun.base.bsnMessage.appliction.BsnMessageApplication;
import com.huigou.topsun.base.bsnMessage.domain.ActiveStatus;
import com.huigou.topsun.base.bsnMessage.domain.BsnMessageExecute;
import com.huigou.topsun.base.bsnMessage.domain.BsnMessageSponsor;
import com.huigou.topsun.base.bsnMessage.repository.BsnMessageExecuteRepository;
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.EpResult;
import com.huigou.topsun.sap.costReimbursement.domain.SapCostReimbursement;
import com.huigou.topsun.sap.nonProdApply.application.NonProdApplyApplication;
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.ProdApplyFromSapVO;
import com.huigou.topsun.sap.nonProdApply.domain.vo.ProdApplyToSapVO;
import com.huigou.topsun.sap.nonProdApply.repository.NonProdApplyBaseInfoRepository;

import com.huigou.topsun.sap.nonProdApply.repository.NonProdApplyDeptRepository;
import com.huigou.topsun.sap.wasteSale.domain.WasteSale;
import com.huigou.uasp.bmp.common.BizBillStatus;
import com.huigou.uasp.bmp.doc.attachment.application.AttachmentApplication;
import com.huigou.uasp.bmp.doc.attachment.domain.model.Attachment;
import com.huigou.uasp.bmp.operator.OperatorApplication;
import com.huigou.uasp.bmp.opm.repository.org.OrgRepository;
import com.huigou.uasp.bpm.ApprovalParameter;
import com.huigou.uasp.bpm.FlowBroker;
import com.huigou.uasp.bpm.HandleResult;
import com.huigou.util.ClassHelper;

import com.huigou.util.DateUtil;
import com.huigou.util.StringUtil;
import lombok.SneakyThrows;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.DelegateTask;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

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

@Service("nonProdApplyApplication")
public class NonProdApplyApplicationImpl  extends FlowBroker implements NonProdApplyApplication {
    @Autowired
    NonProdApplyBaseInfoRepository nonProdApplyBaseInfoRepository;
    @Autowired
    NonProdApplyDeptApplication nonProdApplyDeptApplication;
    @Autowired
    BsnMessageApplication bsnMessageApplication;
    @Autowired
    BsnMessageSponsorRepository bsnMessageSponsorRepository;
    @Autowired
    com.huigou.topsun.base.bsnMessage.repository.BsnMessageExecuteRepository bsnMessageExecuteRepository;

    @Autowired
    SapMutualEpLogApplication sapMutualEpLogApplication;
    @Resource
    private OperatorApplication operatorApplication;
    @Resource
    private OrgRepository orgRepository;
    @Autowired
    DefaultHttpClient defaultHttpClient;
    @Autowired
    private NonProdApplyDeptRepository nonProdApplyDeptRepository;
    @Autowired
    private AttachmentApplication attachmentApplication;
    @SneakyThrows
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    @Override
    protected String saveBizAndApprovalData() {
        super.saveBizAndApprovalData();

        NonProdApplyBaseInfo nonProdApplyBaseInfo = getBizEntity(NonProdApplyBaseInfo.class);
        SapNonProdApplyDept sapNonProdApplyDept=null;
        boolean isNew=nonProdApplyBaseInfo.isNew();
        if (nonProdApplyBaseInfo.isNew()) {
            nonProdApplyBaseInfo.setStatusId(BizBillStatus.APPLYING.getId());
            nonProdApplyBaseInfo.setDistribute(0);
            nonProdApplyBaseInfo.setCreatedDate(new Date());
            if (StringUtil.isNotBlank(nonProdApplyBaseInfo.getSourceId())){ //有数据来源ID的 表示是变更或扩展的
                sapNonProdApplyDept=nonProdApplyDeptApplication.getNonProdApplyDeptByBaseInfoId(nonProdApplyBaseInfo.getSourceId());
            }
        } else {
            nonProdApplyBaseInfo = (NonProdApplyBaseInfo) commonDomainService.loadAndFillinProperties(nonProdApplyBaseInfo);
        }
        //判断汉语品名是否已经存在
        if ("new".equals(nonProdApplyBaseInfo.getMaintenanceType()) && StringUtil.isNotBlank(nonProdApplyBaseInfo.getGenericName())) {
            List<NonProdApplyBaseInfo> baseInfoList = nonProdApplyBaseInfoRepository.findByGenericNameAndMaintenanceType(nonProdApplyBaseInfo.getGenericName(), "new");
            if (!CollectionUtils.isEmpty(baseInfoList)){
                for (NonProdApplyBaseInfo prodApplyBaseInfo : baseInfoList) {
                    if (!prodApplyBaseInfo.getId().equals(nonProdApplyBaseInfo.getId())){
                        throw new RuntimeException("汉语品名:" + nonProdApplyBaseInfo.getGenericName() + "已经存在！请检查输入");
                    }
                }
            }
        }

        if (nonProdApplyBaseInfo.getCreatedDate()==null){
            nonProdApplyBaseInfo.setCreatedDate(new Date());
        }
        if (StringUtil.isBlank(nonProdApplyBaseInfo.getKind())) {
           nonProdApplyBaseInfo.setKind("materiel");
        }
        nonProdApplyBaseInfo = nonProdApplyBaseInfoRepository.save(nonProdApplyBaseInfo);
        //是变更或扩展的
        if (isNew&&StringUtil.isNotBlank(nonProdApplyBaseInfo.getSourceId())) {
            SapNonProdApplyDept newSapNonProdApplyDept=new SapNonProdApplyDept();
            if ("modify".equals(nonProdApplyBaseInfo.getMaintenanceType())) {
                ClassHelper.copyProperties(sapNonProdApplyDept, newSapNonProdApplyDept);
            } else { //扩展的  设置默认基本字段
                if ("1".equals(nonProdApplyBaseInfo.getIsExtendOrg())){
                    ClassHelper.copyProperties(sapNonProdApplyDept, newSapNonProdApplyDept);
                }else {
                    newSapNonProdApplyDept.setMatnr(sapNonProdApplyDept.getMatnr());
                    newSapNonProdApplyDept.setMatkl(sapNonProdApplyDept.getMatkl());
                    newSapNonProdApplyDept.setMatklTypeName(sapNonProdApplyDept.getMatklTypeName());
                    newSapNonProdApplyDept.setMatklType(sapNonProdApplyDept.getMatklType());
                    newSapNonProdApplyDept.setMatklName(sapNonProdApplyDept.getMatklName());
                    newSapNonProdApplyDept.setGroes(sapNonProdApplyDept.getGroes());
                    newSapNonProdApplyDept.setMtart(sapNonProdApplyDept.getMtart());
                    newSapNonProdApplyDept.setSpart(sapNonProdApplyDept.getSpart());
                    newSapNonProdApplyDept.setSpartName(sapNonProdApplyDept.getSpartName());
                    newSapNonProdApplyDept.setMtposMara(sapNonProdApplyDept.getMtposMara());
                    newSapNonProdApplyDept.setXchpf(sapNonProdApplyDept.getXchpf());
                    newSapNonProdApplyDept.setMaktx(sapNonProdApplyDept.getMaktx());
                    newSapNonProdApplyDept.setMaktxEn(sapNonProdApplyDept.getMaktxEn());
                    newSapNonProdApplyDept.setMeins(sapNonProdApplyDept.getMeins());
                    newSapNonProdApplyDept.setMeinsName(sapNonProdApplyDept.getMeinsName());
                    newSapNonProdApplyDept.setRaube(sapNonProdApplyDept.getRaube());
                    newSapNonProdApplyDept.setBrgew(sapNonProdApplyDept.getBrgew());
                    newSapNonProdApplyDept.setGewei(sapNonProdApplyDept.getGewei());
                    newSapNonProdApplyDept.setVolum(sapNonProdApplyDept.getVolum());
                    newSapNonProdApplyDept.setVoleh(sapNonProdApplyDept.getVoleh());
                    newSapNonProdApplyDept.setIprkz(sapNonProdApplyDept.getIprkz());
                    newSapNonProdApplyDept.setMhdhb(sapNonProdApplyDept.getMhdhb());
                    newSapNonProdApplyDept.setMhdrz(sapNonProdApplyDept.getMhdrz());
                    newSapNonProdApplyDept.setNormt(sapNonProdApplyDept.getNormt());
                    newSapNonProdApplyDept.setLength(sapNonProdApplyDept.getLength());
                    newSapNonProdApplyDept.setWidthCm(sapNonProdApplyDept.getWidthCm());
                    newSapNonProdApplyDept.setThickness(sapNonProdApplyDept.getThickness());
                    newSapNonProdApplyDept.setWeight(sapNonProdApplyDept.getWeight());
                    newSapNonProdApplyDept.setSingleThickness(sapNonProdApplyDept.getSingleThickness());
                    newSapNonProdApplyDept.setKlart(sapNonProdApplyDept.getKlart());
                    newSapNonProdApplyDept.setClassify(sapNonProdApplyDept.getClassify());
                    newSapNonProdApplyDept.setMaktxRemEn(sapNonProdApplyDept.getMaktxRemEn());
                    newSapNonProdApplyDept.setMaktxRemZh(sapNonProdApplyDept.getMaktxRemZh());
                    newSapNonProdApplyDept.setWerks(sapNonProdApplyDept.getWerks());
                    newSapNonProdApplyDept.setWerksName(sapNonProdApplyDept.getWerksName());
                    newSapNonProdApplyDept.setLgort(sapNonProdApplyDept.getLgort());
                    newSapNonProdApplyDept.setLgortName(sapNonProdApplyDept.getLgortName());
                    newSapNonProdApplyDept.setLgtyp(sapNonProdApplyDept.getLgtyp());
                    newSapNonProdApplyDept.setLgtypName(sapNonProdApplyDept.getLgtypName());
                    newSapNonProdApplyDept.setMtvfp(sapNonProdApplyDept.getMtvfp());
                    newSapNonProdApplyDept.setLvorm(sapNonProdApplyDept.getLvorm());
                }


//                newSapNonProdApplyDept.setMagrv(sapNonProdApplyDept.getMagrv());
//                newSapNonProdApplyDept.setVkorg(sapNonProdApplyDept.getVkorg());
//                newSapNonProdApplyDept.setVtweg(sapNonProdApplyDept.getVtweg());
//                newSapNonProdApplyDept.setLgnum(sapNonProdApplyDept.getLgnum());
//                newSapNonProdApplyDept.setVkorgName(sapNonProdApplyDept.getVkorgName());
//                newSapNonProdApplyDept.setVtwegName(sapNonProdApplyDept.getVtwegName());
//                newSapNonProdApplyDept.setLgnumName(sapNonProdApplyDept.getLgnumName());
//                newSapNonProdApplyDept.setEkgrpName(sapNonProdApplyDept.getEkgrpName());
//                newSapNonProdApplyDept.setRaubeName(sapNonProdApplyDept.getRaubeName());
//                newSapNonProdApplyDept.setDispoName(sapNonProdApplyDept.getDispoName());
//                newSapNonProdApplyDept.setMinbeName(sapNonProdApplyDept.getMinbeName());
//                newSapNonProdApplyDept.setLadgrName(sapNonProdApplyDept.getLadgrName());
//                销售组织
//                newSapNonProdApplyDept.setVkorg(sapNonProdApplyDept.getVkorg());
//                newSapNonProdApplyDept.setVkorgName(sapNonProdApplyDept.getVkorgName());
//                newSapNonProdApplyDept.setVtweg(sapNonProdApplyDept.getVtweg());
//                newSapNonProdApplyDept.setVtwegName(sapNonProdApplyDept.getVtwegName());
//                newSapNonProdApplyDept.setWerks(sapNonProdApplyDept.getWerks());
//                newSapNonProdApplyDept.setWerksName(sapNonProdApplyDept.getWerksName());
            }
            newSapNonProdApplyDept.setId("");
            newSapNonProdApplyDept.setApplyDeptId("");
            newSapNonProdApplyDept.setBaseInfoId(nonProdApplyBaseInfo.getId());
            nonProdApplyDeptApplication.save(newSapNonProdApplyDept);
          }
        return nonProdApplyBaseInfo.getId();
    }


    @Override
    protected Map<String, Object> getProcessBizParams(String bizId) {
        // 返回业务数据给流程实例，
        return ClassHelper.toMap(nonProdApplyBaseInfoRepository.getOne(bizId));
    }
   /*
     * 任务完成前执行
     */
    @Override
    protected void onBeforeComplete(DelegateTask delegateTask) {
        super.onBeforeComplete(delegateTask);
        String bizId = delegateTask.getExecution().getProcessBusinessKey();
        NonProdApplyBaseInfo nonProdApplyBaseInfo = nonProdApplyBaseInfoRepository.findOne(bizId);
        nonProdApplyBaseInfo.setStatusId(BizBillStatus.APPROVING.getId());
        nonProdApplyBaseInfo.setApprover(getOperator().getPersonMemberName());
        nonProdApplyBaseInfoRepository.save(nonProdApplyBaseInfo);
    }

    @Override
    public void onComplete(DelegateTask delegateTask) {
        super.onComplete(delegateTask);
        String bizId = delegateTask.getExecution().getProcessBusinessKey();
            //审批不通过
        ApprovalParameter parameter = getApprovalParameter();
        // if (ObjectUtils.equals(parameter.getHandleResult(), HandleResult.DISAGREE.id)) {   //审批不通过 或者退回
        //  }
        if (this.isApplyProcUnit(delegateTask)) {   //申请后直接提交
        }
    }

    /**
     * 流程实例结束
     *
     * @param delegateExecution
     */
    @Override
    protected void onEnd(DelegateExecution delegateExecution) {
        //super.onEnd(delegateExecution);
        String bizId = delegateExecution.getProcessBusinessKey();
        ApprovalParameter parameter = getApprovalParameter();
        BizBillStatus status = approvePassed() ? BizBillStatus.COMPLETED : BizBillStatus.ABORTED;

        NonProdApplyBaseInfo nonProdApplyBaseInfo = nonProdApplyBaseInfoRepository.findOne(bizId);
        //审批通过,给货源专员发送消息
        if (ObjectUtils.equals(parameter.getHandleResult(), 1)) { //同意
            Map backMap=new HashMap();
            backMap.put("TYPE","C");
            backMap.put("title",nonProdApplyBaseInfo.getBillCode());
            backMap.put("positionCode","HYZY");
            nonProdApplyDeptApplication.saveBsnMessageData(nonProdApplyBaseInfo,backMap);
        }
        nonProdApplyBaseInfo.setStatusId(status.getId());
        nonProdApplyBaseInfo.setApprover(getOperator().getPersonMemberName());
        nonProdApplyBaseInfo.setApprovalDate(new Date());
        //复制正反面图片
        List<Attachment> frontAttachments = attachmentApplication.queryAttachments("frontPicture", nonProdApplyBaseInfo.getAttbizId());
        List<Attachment> backAttachments = attachmentApplication.queryAttachments("backPicture", nonProdApplyBaseInfo.getAttbizId());
        if (frontAttachments.size() > 0) {
            Attachment attachment = frontAttachments.get(0);
            Attachment attachmentNew = new Attachment();
            ClassHelper.copyProperties(attachment, attachmentNew);
            attachmentNew.setId(null);
            attachmentNew.setBizId(nonProdApplyBaseInfo.getId());
            Creator creator = attachmentNew.getCreator();
            creator.setCreatedDate(new Date());
            attachmentNew.setCreator(creator);
            attachmentApplication.saveAttachment(attachmentNew);
        }
        if (backAttachments.size() > 0) {
            Attachment attachment = backAttachments.get(0);
            Attachment attachmentNew = new Attachment();
            ClassHelper.copyProperties(attachment, attachmentNew);
            attachmentNew.setId(null);
            attachmentNew.setBizId(nonProdApplyBaseInfo.getId());
            Creator creator = attachmentNew.getCreator();
            creator.setCreatedDate(new Date());
            attachmentNew.setCreator(creator);
            attachmentApplication.saveAttachment(attachmentNew);
        }
        nonProdApplyBaseInfoRepository.save(nonProdApplyBaseInfo);
      }

    @Override
    protected void onAbortProcessInstance(DelegateExecution delegateExecution) {
        super.onAbortProcessInstance(delegateExecution);
        String bizId = delegateExecution.getProcessBusinessKey();
        NonProdApplyBaseInfo nonProdApplyBaseInfo = nonProdApplyBaseInfoRepository.findOne(bizId);
        nonProdApplyBaseInfo.setStatusId(BizBillStatus.ABORTED.getId());
        nonProdApplyBaseInfoRepository.save(nonProdApplyBaseInfo);
    }

    /**
     * 流程撤销事件
     **/
    @Override
    protected void onRecallProcessInstance(DelegateExecution delegateExecution) {
        String bizId = delegateExecution.getProcessBusinessKey();
        // 修改单据状态为申请
        updateStatus(bizId, BizBillStatus.APPLYING);
    }

    /**
     * 回收事件
     **/
    @Override
    protected void onWithdraw(DelegateTask delegateTask, String destActivityId) {
        super.onWithdraw(delegateTask, destActivityId);
        String bizId = delegateTask.getExecution().getProcessBusinessKey();
        if (destActivityId.equalsIgnoreCase("apply")) {
            updateStatus(bizId, BizBillStatus.APPLYING);
        }
    }

    @Transactional
    protected void updateStatus(String bizId, BizBillStatus status) {
        Assert.hasText(bizId, CommonDomainConstants.ID_NOT_BLANK);
        this.commonDomainService.updateStatus(NonProdApplyBaseInfo.class, bizId, status.getId());
    }

    /**
     * @param delegateTask
     * @param destActivityId 回退到的目标节点id
     */
    @Override
    protected void onBack(DelegateTask delegateTask, String destActivityId) {
        super.onBack(delegateTask, destActivityId);
        if ("Apply".equalsIgnoreCase(destActivityId)) {
            String bizId = delegateTask.getExecution().getProcessBusinessKey();
            NonProdApplyBaseInfo nonProdApplyBaseInfo = nonProdApplyBaseInfoRepository.findOne(bizId);
            nonProdApplyBaseInfo.setStatusId(BizBillStatus.APPLYING.getId());
            nonProdApplyBaseInfoRepository.save(nonProdApplyBaseInfo);
        }
    }

    /**
     * 设置任务名称
     */
    @Override
    protected void setTaskDescription(DelegateTask delegateTask) {
        String bizId = delegateTask.getExecution().getProcessBusinessKey();
        delegateTask.setDescription(this.getApprovalSubjectName(bizId));
    }

    /**
     * 获取任务标题
     *
     * @param bizId
     * @return
     */
    private String getApprovalSubjectName(String bizId) {
        NonProdApplyBaseInfo baseInfo = this.nonProdApplyBaseInfoRepository.findOne(bizId);
        //查询 单据日期
        String fillinDateStr = DateUtil.getDateFormat("yyyy-MM-dd HH:mm:ss", baseInfo.getFillinDate());
        //设置标题
        String title = "物料主数据";
        String maintenanceType = baseInfo.getMaintenanceType();
        if ("new".equals(maintenanceType)){
            title = title + "新增";
        } else if ("modify".equals(maintenanceType)) {
            SapNonProdApplyDept applyDept = this.nonProdApplyDeptApplication.getNonProdApplyDeptByBaseInfoId(baseInfo.getId());
            title = title + "修改" + "(" + applyDept.getMatnr() + ")";
        } else if ("extend".equals(maintenanceType)) {
            SapNonProdApplyDept applyDept = this.nonProdApplyDeptApplication.getNonProdApplyDeptByBaseInfoId(baseInfo.getId());
            title = title + "扩展" + "(" + applyDept.getMatnr() + ")";
        }
        return String.format("%s-%s-%s(%s)", title, baseInfo.getBillCode(), baseInfo.getGenericName(),fillinDateStr);
    }

    @Override
    public NonProdApplyBaseInfo loadNonProdApplyBaseInfoById(String id) {

        NonProdApplyBaseInfo nonProdApplyBaseInfo=nonProdApplyBaseInfoRepository.findOne(id);
        if (nonProdApplyBaseInfo==null){
            throw new RuntimeException("数据已经不存在！");
        }
        SapNonProdApplyDept applyDept=nonProdApplyDeptApplication.getNonProdApplyDeptByBaseInfoId(nonProdApplyBaseInfo.getId());
        if (applyDept!=null){
            nonProdApplyBaseInfo.setApplyDeptId(applyDept.getApplyDeptId());
            nonProdApplyBaseInfo.setMatnr(applyDept.getMatnr());
        }
        return nonProdApplyBaseInfo;
    }

    @Override
    public Map<String, Object> slicedNonProdApplyBaseInfoQuery(NonProdApplyBaseInfoQueryRequest query) {
        QueryDescriptor queryDescriptor = this.sqlExecutorDao.getQuery(QUERY_XML_FILE_PATH, "slicedNonProdApplyBaseInfoQuery");
        QueryModel model = this.sqlExecutorDao.getQueryModel(queryDescriptor, query);
        model.putDictionary("maintenanceType", DictUtil.getDictionary("maintainType"));
        model.putDictionary("baseUnit", DictUtil.getDictionary("measuringUnit"));
        model.putDictionary("mtart", DictUtil.getDictionary("suppliesType"));
        model.putDictionary("businessUsage", DictUtil.getDictionary("serviceusage"));
        model.putDictionary("status", DictUtil.getDictionary("bizBillStatus"));
        model.setSortFieldName("billCode");
        model.setSortOrder("desc");
        return this.sqlExecutorDao.executeSlicedQuery(model);

    }


    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void deleteNonProdApplyBaseInfoById(String id) {
        NonProdApplyBaseInfo baseInfo=this.nonProdApplyBaseInfoRepository.findOne(id);
        if (baseInfo.getStatusId()!=0){
           throw new RuntimeException("审批中和已完成状态的，不能删除！");
        }
        nonProdApplyBaseInfoRepository.delete(id);

    }

    @Override
    @Transactional
    public void deleteNonProdApplyBaseInfoByIds(List<String> ids) {
        ids.forEach(this::deleteNonProdApplyBaseInfoById);
        for (String id:ids) {
            nonProdApplyDeptApplication.deleteSapNonProdApplyDept(nonProdApplyDeptApplication.getNonProdApplyDeptByBaseInfoId(id));

            //更新流程任务的状态
            String sql = "update act_ru_task_extension set STATUS_ID_='completed',STATUS_NAME_='已完成'  where ";
                   sql += " BUSINESS_KEY_='" + id + "'";
             sqlExecutorDao.executeUpdate(sql);
        }
    }

    @Override
    public String publishDataToSap(String id){
        NonProdApplyBaseInfo nonProdApplyBaseInfo = nonProdApplyBaseInfoRepository.findOne(id);
        SapNonProdApplyDept applyDept=nonProdApplyDeptApplication.getNonProdApplyDeptByBaseInfoId(nonProdApplyBaseInfo.getId());

       // nonProdApplyDeptApplication.sendSapData(nonProdApplyBaseInfo,applyDept);
        return "";
    }


    public  Map<String, Object> slicedNonApplyBaseInfoByMatnr(NonProdApplyBaseInfoQueryRequest query){

        QueryDescriptor queryDescriptor = this.sqlExecutorDao.getQuery(QUERY_XML_FILE_PATH, "slicedNonApplyBaseInfoByMatnr");
        QueryModel model = this.sqlExecutorDao.getQueryModel(queryDescriptor, query);
        model.setPageIndex(1);
        model.setPageSize(100);
      //  if (StringUtil.isNotBlank(query.getMatnr())) {
       //     model.addCriteria("  and  ad.matnr =:matnr");
       //     model.putParam("matnr", query.getMatnr());
       // }
        return this.sqlExecutorDao.executeSlicedQuery(model);
    }

  //按汉语品名查询数据
  @Override
    public  Map<String, Object> slicedNonApplyBaseInfoByMaktx(NonProdApplyBaseInfoQueryRequest query){

        QueryDescriptor queryDescriptor = this.sqlExecutorDao.getQuery(QUERY_XML_FILE_PATH, "slicedNonApplyBaseInfoByMaktx");
        QueryModel model = this.sqlExecutorDao.getQueryModel(queryDescriptor, query);
        model.setPageIndex(1);
        model.setPageSize(100);
        return this.sqlExecutorDao.executeSlicedQuery(model);
    }

    @Override
    public String getMaktxRemZhByMatnrAndWerks(String matnr, String werks) {
        String maktxRemZh = "";
        if (StringUtil.isNotBlank(matnr) && StringUtil.isNotBlank(werks)){
            List<SapNonProdApplyDept> deptList = nonProdApplyDeptRepository.findByMatnrAndWerks(matnr, werks);
            if (deptList.size()>0){
                List<String> ids = deptList
                        .stream()
                        .map(SapNonProdApplyDept::getBaseInfoId)
                        .collect(Collectors.toList());
                List<NonProdApplyBaseInfo> list = nonProdApplyBaseInfoRepository.findAll(ids);
                list = list
                        .stream()
                        .filter( nonProdApplyBaseInfo -> nonProdApplyBaseInfo.getDistribute() == 2 && StringUtil.isNotBlank(nonProdApplyBaseInfo.getMaktxRemZh()))
                        .sorted(Comparator.comparing(NonProdApplyBaseInfo::getFillinDate).reversed())
                        .collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(list)){
                    maktxRemZh = list.get(0).getMaktxRemZh();
                }
            }
        }
        return maktxRemZh;
    }


    @Override
    //获取变更或扩展前的业务部门
   public  String getChangeBusinessUsage(String bizId,String type){

       //查询扩展前所有的 业务部门
       SapNonProdApplyDept nonProdApplyDept = nonProdApplyDeptApplication.getNonProdApplyDeptByBaseInfoId(bizId);
       NonProdApplyBaseInfoQueryRequest queryRequest=new NonProdApplyBaseInfoQueryRequest();
       queryRequest.setMatnr(nonProdApplyDept.getMatnr());
       Map exmap=this.slicedNonApplyBaseInfoByMatnr(queryRequest);

       boolean isExistApplyStatus=false; //是否存在未完成的扩展数据
       List <Map <String,Object>>extendedList=(List)exmap.get("Rows");
       String usedBusiness="";
       String maintenanceType="变更";
       for (Map <String,Object>mapExd:extendedList) {
           if (!"modify".equals(maintenanceType)) {
               usedBusiness += mapExd.get("businessUsage").toString() + ",";
           }
           if (!"3".equals(mapExd.get("status").toString()) && !"5".equals(mapExd.get("status").toString())){
               isExistApplyStatus=true;
               maintenanceType=mapExd.get("maintenanceType").toString().equals("extend")?"扩展":"变更";
               break;
           }
       }
       if (isExistApplyStatus&&maintenanceType.equals(type)){
           throw new RuntimeException("当前物料编码"+nonProdApplyDept.getMatnr()+"已经存在"+maintenanceType+"申请中的数据！");
       }
       if (usedBusiness.length()>1){
           usedBusiness=usedBusiness.substring(0,usedBusiness.length()-1);
       }
       return usedBusiness;
   }

    @Override
    @Transactional
    public String saveProdApplyFromSapVO(ProdApplyFromSapVO prodApplyFromSapVO,SapNonProdApplyDept sapNonProdApplyDept) {

        //初始化用户信息
         String createdById = SystemCache.getParameter("adminPersonId", String.class);
         Operator operator = operatorApplication.createOperatorByPersonMemberId(createdById);
         String  message="";
   try {
       NonProdApplyBaseInfo nonProdApplyBaseInfo = new NonProdApplyBaseInfo();

       ClassHelper.copyProperties(prodApplyFromSapVO,sapNonProdApplyDept);
       ClassHelper.copyProperties(prodApplyFromSapVO, nonProdApplyBaseInfo);

       nonProdApplyBaseInfo.setCreatedDate(new Date());
       nonProdApplyBaseInfo.setStatusId(BizBillStatus.COMPLETED.getId());
       nonProdApplyBaseInfo.setApprover(operator.getPersonMemberName());
       nonProdApplyBaseInfo.setDefaultValues(new OrgUnit(operator.getFullId(), operator.getFullName()));

       nonProdApplyBaseInfo.setMaintenanceType("new");
       nonProdApplyBaseInfo.setApprovalDate(new Date());
       nonProdApplyBaseInfo.setKind("product");

       nonProdApplyBaseInfo = nonProdApplyBaseInfoRepository.save(nonProdApplyBaseInfo);

       sapNonProdApplyDept.setBaseInfoId(nonProdApplyBaseInfo.getId());

       nonProdApplyDeptApplication.save(sapNonProdApplyDept);
       Map backMap=new HashMap();
       backMap.put("TYPE","P");
       backMap.put("title",sapNonProdApplyDept.getMaktx()); //汉语品名
       backMap.put("positionCode","HYZY");
       nonProdApplyDeptApplication.saveBsnMessageData(nonProdApplyBaseInfo, backMap);
     }catch(Exception ex){
        message=ex.getMessage();
     //  ex.printStackTrace();
     }
      return  message;
    }
}