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

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
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.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.application.SapMutualEpLogApplication;
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.wasteSale.domain.WasteSale;
import com.huigou.uasp.bmp.common.BizBillStatus;
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 javax.annotation.Resource;
import javax.persistence.Column;
import java.util.*;

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

    @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 (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 { //扩展的  设置默认基本字段
                newSapNonProdApplyDept.setMatnr(sapNonProdApplyDept.getMatnr());
                newSapNonProdApplyDept.setMatkl(sapNonProdApplyDept.getMatkl());
                newSapNonProdApplyDept.setMtart(sapNonProdApplyDept.getMtart());
                newSapNonProdApplyDept.setLvorm(sapNonProdApplyDept.getLvorm());
                newSapNonProdApplyDept.setSpart(sapNonProdApplyDept.getSpart());
                newSapNonProdApplyDept.setMtposMara(sapNonProdApplyDept.getMtposMara());
                newSapNonProdApplyDept.setMaktx(sapNonProdApplyDept.getMaktx());
                newSapNonProdApplyDept.setSpars(sapNonProdApplyDept.getSpars());
                newSapNonProdApplyDept.setMaktx(sapNonProdApplyDept.getMaktx());
                newSapNonProdApplyDept.setSpars(sapNonProdApplyDept.getSpars());
                newSapNonProdApplyDept.setNormt(sapNonProdApplyDept.getNormt());
                newSapNonProdApplyDept.setXchpf(sapNonProdApplyDept.getXchpf());
                newSapNonProdApplyDept.setMagrv(sapNonProdApplyDept.getMagrv());
                newSapNonProdApplyDept.setMeins(sapNonProdApplyDept.getMeins());
                newSapNonProdApplyDept.setMeinsName(sapNonProdApplyDept.getMeinsName());
                newSapNonProdApplyDept.setGroes(sapNonProdApplyDept.getGroes());

                newSapNonProdApplyDept.setBrgew(sapNonProdApplyDept.getBrgew());
                newSapNonProdApplyDept.setNtgew(sapNonProdApplyDept.getNtgew());
                newSapNonProdApplyDept.setGewei(sapNonProdApplyDept.getGewei());
                newSapNonProdApplyDept.setVolum(sapNonProdApplyDept.getVolum());
                newSapNonProdApplyDept.setVoleh(sapNonProdApplyDept.getVoleh());
                newSapNonProdApplyDept.setRaube(sapNonProdApplyDept.getRaube());
                newSapNonProdApplyDept.setIprkz(sapNonProdApplyDept.getIprkz());
                newSapNonProdApplyDept.setMhdrz(sapNonProdApplyDept.getMhdrz());
                newSapNonProdApplyDept.setMhdhb(sapNonProdApplyDept.getMhdhb());

                newSapNonProdApplyDept.setWerks(sapNonProdApplyDept.getWerks());
                newSapNonProdApplyDept.setLgort(sapNonProdApplyDept.getLgort());
                newSapNonProdApplyDept.setVkorg(sapNonProdApplyDept.getVkorg());
                newSapNonProdApplyDept.setVtweg(sapNonProdApplyDept.getVtweg());
                newSapNonProdApplyDept.setLgnum(sapNonProdApplyDept.getLgnum());
                newSapNonProdApplyDept.setLgtyp(sapNonProdApplyDept.getLgtyp());

                newSapNonProdApplyDept.setMatklName(sapNonProdApplyDept.getMatklName());
                newSapNonProdApplyDept.setSpartName(sapNonProdApplyDept.getSpartName());
                newSapNonProdApplyDept.setWerksName(sapNonProdApplyDept.getWerksName());
                newSapNonProdApplyDept.setLgortName(sapNonProdApplyDept.getLgortName());

                newSapNonProdApplyDept.setVkorgName(sapNonProdApplyDept.getVkorgName());
                newSapNonProdApplyDept.setVtwegName(sapNonProdApplyDept.getVtwegName());
                newSapNonProdApplyDept.setLgnumName(sapNonProdApplyDept.getLgnumName());
                newSapNonProdApplyDept.setLgtypName(sapNonProdApplyDept.getLgtypName());
                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();
        if (this.isApplyProcUnit(delegateTask) && this.getApprovalParameter().isAdvanceProcessAction()) {
            NonProdApplyBaseInfo nonProdApplyBaseInfo = nonProdApplyBaseInfoRepository.findOne(bizId);
           // BizBillStatus status = approvePassed() ? BizBillStatus.COMPLETED : BizBillStatus.ABORTED;
            nonProdApplyBaseInfo.setStatusId(BizBillStatus.APPROVING.getId());
            nonProdApplyBaseInfo.setApprover(getOperator().getPersonMemberName());
           // nonProdApplyBaseInfo.setApprovalDate(new Date());
            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(nonProdApplyBaseInfo.getMaintenanceType().equals("new")) { //新申请的 发布分发人的待办信息 06.17 给货源专员发送消息
            //审批通过
            if (ObjectUtils.equals(parameter.getHandleResult(), 1)) { //同意
                //SapNonProdApplyDept nonProdApplyDept=nonProdApplyDeptApplication.getNonProdApplyDeptByBaseInfoId(nonProdApplyBaseInfo.getSourceId());
                //SapNonProdApplyDept newNonProdApplyDept=nonProdApplyDeptApplication.getNonProdApplyDeptByBaseInfoId(nonProdApplyBaseInfo.getId());
                 //publishHyzyMessage(nonProdApplyBaseInfo);
                Map backMap=new HashMap();
                backMap.put("TYPE","C");
                backMap.put("title",nonProdApplyBaseInfo.getBillCode());
                backMap.put("positionCode","HYZY");
                nonProdApplyDeptApplication.saveBsnMessageData(nonProdApplyBaseInfo,backMap);
            }
       // }
      //  if(nonProdApplyBaseInfo.getMaintenanceType().equals("modify")||
       //         nonProdApplyBaseInfo.getMaintenanceType().equals("extend")
       // ){ //变更和扩展的发布 分发信息

            //审批通过
          /*   if (ObjectUtils.equals(parameter.getHandleResult(), 1)) { //同意
                SapNonProdApplyDept nonProdApplyDept=nonProdApplyDeptApplication.getNonProdApplyDeptByBaseInfoId(nonProdApplyBaseInfo.getSourceId());
                SapNonProdApplyDept newNonProdApplyDept=nonProdApplyDeptApplication.getNonProdApplyDeptByBaseInfoId(nonProdApplyBaseInfo.getId());
                publishHyzyMessage(nonProdApplyBaseInfo);
               List<Map<String, String>> deptStaffList=new ArrayList<>();

                BsnMessageSponsor sponsor = bsnMessageSponsorRepository.findByBusinessId(nonProdApplyDept.getApplyDeptId());
                BsnMessageSponsor newSponsor=new  BsnMessageSponsor();
                ClassHelper.copyProperties(sponsor,newSponsor);

               List<BsnMessageExecute> bsnMsgList=bsnMessageExecuteRepository.findAllByMessageSponsorId(sponsor.getId());

                //封装分发数据
              //  BsnMessageSponsor bsnMessageSponsor = new BsnMessageSponsor();
                newSponsor.setTaskSponsor(this.getOperator().getUserId());
                newSponsor.setBusinessId(newNonProdApplyDept.getApplyDeptId());
                //newSponsor.setId(UUID.randomUUID().toString().replaceAll("-",""));
                newSponsor.setId("");
                newSponsor.setCreateDate(new Date());
                newSponsor.setStatus(0);

                for (BsnMessageExecute bsnMessageExecute:bsnMsgList){
                    BsnMessageExecute messageExecute = new BsnMessageExecute();
                    ClassHelper.copyProperties(bsnMessageExecute,messageExecute);
                  //  bsnMessageExecute.setMessageSponsorId(newSponsor.getId());
                    messageExecute.setActive(0);
                    messageExecute.setUpdateDate(new Date());
                    String msgExeDescribe=messageExecute.getTaskDescribe().replaceAll("数据维护","数据变更");
                    messageExecute.setTaskDescribe(msgExeDescribe);
                    messageExecute.setId("");
                    newSponsor.addExecute(messageExecute);
                }
                //保存任务
                bsnMessageApplication.keepTasks(newSponsor);
                 //发布任务
                bsnMessageApplication.publishTasks(nonProdApplyDept.getApplyDeptId());*/
         //   }
        //}
        nonProdApplyBaseInfo.setStatusId(status.getId());
        nonProdApplyBaseInfo.setApprover(getOperator().getPersonMemberName());
        nonProdApplyBaseInfo.setApprovalDate(new Date());
        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);
    }
     //发布货源专员的待办消息
   // private void publishHyzyMessage(NonProdApplyBaseInfo baseInfo){

   /*
        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='HYZY')";
        List<Map<String, Object>> mapList = this.sqlExecutorDao.queryToListMap(sql);
        for (Map map : mapList) {
           // String user = map.get("code").toString();
            BsnMessageSponsor bsnMessageSponsor = new BsnMessageSponsor();
            bsnMessageSponsor.setTaskSponsor(map.get("id").toString());
            bsnMessageSponsor.setTitle(baseInfo.getGenericName());//通用品名
            bsnMessageSponsor.setExecutorUrl("sapNonProdApplyNext/forwardNonProdApplyNext.do?isReadOnly=false");
            if ("product".equals(baseInfo.getKind())) {
                bsnMessageSponsor.setExecutorUrl("sapNonProdApplyNext/forwardNonProdApplyNext.do?prod=1&isReadOnly=false");
            }
            bsnMessageSponsor.setBusinessId(baseInfo.getId());//newNonProdApplyDept.getApplyDeptId()改为BaseInfo 的ID
            bsnMessageSponsor.setCreateDate(new Date());
            bsnMessageSponsor.setStatus(0);
            //List<Map<String, String>> deptStaffList=new ArrayList<>();
            //Map <String,String>map=new HashMap<String, String>();
            // map.put("");
            //deptStaffList.add(map);
            // for (Map<String, String> stringMap : deptStaffList) {
            BsnMessageExecute messageExecute = new BsnMessageExecute();
            String userCode = map.get("personMemberId").toString();//stringMap.get("userCode");
            String deptName = map.get("positionName").toString();//stringMap.get("deptName");
            String deptCode = map.get("positionCode").toString();
            ;//stringMap.get("deptCode");
            String[] split = userCode.split("@");
            messageExecute.setTaskExecute(split[0]);
            messageExecute.setBusinessCode(deptCode);
            messageExecute.setActive(ActiveStatus.UNFINISHED.getValue());
            messageExecute.setUpdateDate(new Date());
            String mess="-.物料维护(";
            if (baseInfo.getMaintenanceType().equals("modify")){
                mess="-.物料变更(";
            }
            if (baseInfo.getMaintenanceType().equals("extend")){
                mess="-.物料扩展(";
            }
            messageExecute.setTaskDescribe(baseInfo.getGenericName() + mess+ deptName + ")");

            //保存任务
            // bsnMessageApplication.keepTasks(bsnMessageSponsor);

            bsnMessageApplication.saveBsnMessageSponsor(bsnMessageSponsor);
            messageExecute.setMessageSponsorId(bsnMessageSponsor.getId());

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

    //}
    /**
     * 流程撤销事件
     **/
    @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)) {
            title = title + "修改";
        } else if ("extend".equals(maintenanceType)) {
            title = title + "扩展";
        }
        return String.format("%s-%s(%s)", title, baseInfo.getBillCode(), 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);
//        if (StringUtil.isNotBlank(query.getMatnr())) {
//            model.addCriteria(" and  ad.matnr like:matnr");
//            model.putLikeParam("matnr", query.getMatnr());
//        }
//        if (query.getStatus() != null) {
//            model.addCriteria(" and t.status =:status");
//            model.putParam("status", query.getStatus());
//        }
//        if (query.getMaintenanceType() != null) {
//            model.addCriteria(" and t.maintenance_type =:maintenanceType");
//            model.putParam("maintenanceType", query.getMaintenanceType());
//        }
//        if (query.getGenericName() != null) {
//            model.addCriteria(" and t.generic_name =:generic_name");
//            model.putParam("genericName", query.getGenericName());
//        }
//
//        if (query.getMaktx() != null) {
//            model.addCriteria(" and  ad.maktx like:maktx");
//            model.putLikeParam("maktx", query.getMaktx());
//        }
//        if (query.getBillCode() != null) {
//            model.addCriteria(" and  t.bill_code like:billCode");
//            model.putLikeParam("billCode", query.getBillCode());
//        }
//        if (query.getStartDate() != null&&!"".equals(query.getStartDate())) {
//            model.addCriteria(" and t.created_date >=:startDate");
//            model.putParam("startDate", query.getStartDate());
//        }
//        if (query.getEndDate() != null&&!"".equals(query.getEndDate())) {
//            model.addCriteria(" and t.created_date <=:endDate");
//            model.putParam("endDate", query.getEndDate());
//
//        }
        model.putDictionary("maintenanceType", DictUtil.getDictionary("maintainType"));
        model.putDictionary("baseUnit", DictUtil.getDictionary("measuringUnit"));
        model.putDictionary("itemAttributes", 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 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())){
               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) {

        //初始化用户信息
         String createdById = SystemCache.getParameter("adminPersonId", String.class);
         Operator operator = operatorApplication.createOperatorByPersonMemberId(createdById);
         String  message="";
   try {
       NonProdApplyBaseInfo nonProdApplyBaseInfo = new NonProdApplyBaseInfo();
       SapNonProdApplyDept sapNonProdApplyDept = new 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);

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

       nonProdApplyDeptApplication.save(sapNonProdApplyDept);

       //保存基本信息的维护的待办
      // saveDeptStaff(deptStaffList, nonProdApplyDept.getApplyDeptId(),genericName);
/*  改为推送给 货源专员
       BsnMessageSponsor bsnMessageSponsor = new BsnMessageSponsor();
       bsnMessageSponsor.setTaskSponsor(operator.getLoginUser().getId());
       String genericName=nonProdApplyBaseInfo.getGenericName()!=null?nonProdApplyBaseInfo.getGenericName():"";
       if (StringUtils.isBlank(genericName)) {
           genericName=sapNonProdApplyDept.getMaktx()!=null?sapNonProdApplyDept.getMaktx():"";
       }
       bsnMessageSponsor.setTitle(genericName);//通用品名
       bsnMessageSponsor.setExecutorUrl("sapNonProdApplyNext/forwardNonProdApplyNext.do?prod=1&isReadOnly=false");
       bsnMessageSponsor.setBusinessId(sapNonProdApplyDept.getApplyDeptId());
       bsnMessageSponsor.setCreateDate(new Date());
       bsnMessageSponsor.setStatus(0);
       //List<Map<String, String>> deptStaffList=new ArrayList<>();
       //Map <String,String>map=new HashMap<String, String>();
      // map.put("");
       //deptStaffList.add(map);
      // for (Map<String, String> stringMap : deptStaffList) {
           BsnMessageExecute messageExecute = new BsnMessageExecute();
           String userCode = operator.getPersonMemberId();//stringMap.get("userCode");
           String deptName = operator.getDeptName();//stringMap.get("deptName");
           String deptCode = operator.getDeptCode();//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+"产品数据维护");

       //保存任务
      // bsnMessageApplication.keepTasks(bsnMessageSponsor);

        bsnMessageApplication.saveBsnMessageSponsor(bsnMessageSponsor);
        messageExecute.setMessageSponsorId(bsnMessageSponsor.getId());

         List<BsnMessageExecute> executes =new ArrayList<>();
          executes.add(messageExecute);
         bsnMessageApplication.saveBsnMessageExecute(executes); */
      // bsnMessageApplication.publishTasks(sapNonProdApplyDept.getApplyDeptId());
       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;
    }
}