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

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.huigou.cache.DictUtil;
import com.huigou.cache.SystemCache;
import com.huigou.context.Operator;
import com.huigou.context.OrgUnit;
import com.huigou.context.ThreadLocalUtil;
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.MannualStartWorkApplication;
import com.huigou.topsun.sap.common.DefaultHttpClient;
import com.huigou.topsun.sap.common.application.SapMutualEpLogApplication;
import com.huigou.topsun.sap.costReimbursement.domain.SapCostReimbursement;
import com.huigou.topsun.sap.purchase.domain.SapPurchase;
import com.huigou.topsun.sap.purchase.domain.SapPurchaseItem;
import com.huigou.topsun.sap.purchaseApproval.application.SapPurchaseApprovalApplication;
import com.huigou.topsun.sap.purchaseApproval.application.SapPurchaseApprovalItemApplication;
import com.huigou.topsun.sap.purchaseApproval.domain.SapPurchaseApproval;
import com.huigou.topsun.sap.purchaseApproval.domain.SapPurchaseApprovalItem;
import com.huigou.topsun.sap.purchaseApproval.domain.query.SapPurchaseApprovalQueryRequest;
import com.huigou.topsun.sap.purchaseApproval.domain.vo.SapPurchaseApprovalDto;
import com.huigou.topsun.sap.purchaseApproval.domain.vo.SapPurchaseApprovalItemVo;
import com.huigou.topsun.sap.purchaseApproval.domain.vo.SapPurchaseApprovalVo;
import com.huigou.topsun.sap.purchaseApproval.repository.SapPurchaseApprovalRepository;
import com.huigou.topsun.sap.purchaseOrder.domain.SapPurchaseOrder;
import com.huigou.uasp.bmp.common.BizBillStatus;
import com.huigou.uasp.bmp.fn.CodeGenerator;
import com.huigou.uasp.bmp.operator.OperatorApplication;
import com.huigou.uasp.bmp.opm.domain.model.org.Org;
import com.huigou.uasp.bpm.FlowBroker;
import com.huigou.uasp.bpm.ProcessAction;
import com.huigou.uasp.bpm.ProcessStartModel;
import com.huigou.uasp.bpm.engine.application.WorkflowApplication;
import com.huigou.util.*;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.DelegateTask;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.impl.persistence.entity.TaskEntity;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Auther: xin.lu
 * @Date: 2024/01/09/18:59
 * @Description:
 */
@Service("sapPurchaseApprovalApplication")
public class SapPurchaseApprovalApplicationImpl extends FlowBroker implements SapPurchaseApprovalApplication {
    @Resource
    private SapPurchaseApprovalRepository sapPurchaseApprovalRepository;
    @Resource
    private SapPurchaseApprovalItemApplication sapPurchaseApprovalItemApplication;

    @Autowired
    DefaultHttpClient defaultHttpClient;
    @Autowired
    SapMutualEpLogApplication sapMutualEpLogApplication;
    @Resource
    private OperatorApplication operatorApplication;
    @Autowired
    private MannualStartWorkApplication mannualStartWorkApplication;

    @Override
    protected String saveBizAndApprovalData() {
        super.saveBizAndApprovalData();
        SapPurchaseApproval sapPurchaseApproval = getBizEntity(SapPurchaseApproval.class);
        if (sapPurchaseApproval.isNew()) {
            sapPurchaseApproval.setStatusId(BizBillStatus.APPLYING.getId());
        } else {
            sapPurchaseApproval = (SapPurchaseApproval) commonDomainService.loadAndFillinProperties(sapPurchaseApproval);
        }
        sapPurchaseApproval = sapPurchaseApprovalRepository.save(sapPurchaseApproval);
        List<SapPurchaseApprovalItem> sapPurchaseApprovalItems = getBizEntities(SapPurchaseApprovalItem.class, "sapPurchaseItems");
        sapPurchaseApprovalItemApplication.saveSapPurchaseApprovalItems(sapPurchaseApproval.getId(),sapPurchaseApprovalItems);

        //String sapPurchaseVoJson = this.getSapPurchaseVoJson(sapPurchaseApproval);
        return sapPurchaseApproval.getId();
    }

    @Override
    protected void setTaskDescription(DelegateTask delegateTask) {
        String bizId = delegateTask.getExecution().getProcessBusinessKey();
        delegateTask.setDescription(this.getApprovalSubjectName(bizId));
    }

    /**
     * 获取任务标题
     *
     * @param bizId
     * @return
     */
    private String getApprovalSubjectName(String bizId) {
        SapPurchaseApproval sapPurchaseApproval = this.sapPurchaseApprovalRepository.findOne(bizId);
        //查询 单据日期
        String fillinDateStr = DateUtil.getDateFormat("yyyy-MM-dd HH:mm:ss", sapPurchaseApproval.getFillinDate());
        //设置标题
        return String.format("%s-%s(%s)", sapPurchaseApproval.getBatxt(), sapPurchaseApproval.getBanfn(), fillinDateStr);
    }

    @Override
    protected Map<String, Object> getProcessBizParams(String bizId) {
        // 返回业务数据给流程实例，
        return ClassHelper.toMap(sapPurchaseApprovalRepository.getOne(bizId));
    }

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

    /**
     * 任务完成前执行
     */
    @Override
    protected void onBeforeComplete(DelegateTask delegateTask) {
        super.onBeforeComplete(delegateTask);
        String bizId = delegateTask.getExecution().getProcessBusinessKey();
        if (this.isApplyProcUnit(delegateTask) && this.getApprovalParameter().isAdvanceProcessAction()) {
            updateStatus(bizId, BizBillStatus.APPROVING);
        }
    }

    /**
     * 回收事件
     **/
    @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(SapPurchaseApproval.class, bizId, status.getId());
    }

    @Override
    protected void onEnd(DelegateExecution delegateExecution) {
        super.onEnd(delegateExecution);
        String bizId = delegateExecution.getProcessBusinessKey();
        BizBillStatus status = approvePassed() ? BizBillStatus.COMPLETED : BizBillStatus.ABORTED;
        SapPurchaseApproval sapPurchaseApproval = sapPurchaseApprovalRepository.findOne(bizId);
        sapPurchaseApproval.setStatusId(status.getId());
        sapPurchaseApprovalRepository.save(sapPurchaseApproval);
        sendSapData(sapPurchaseApproval,"Y");
    }

    /**
     * 转换成SAP JSON格式数据
     * @return
     */
    /*public String getSapPurchaseVoJson(SapPurchaseApproval sapPurchase){
        List<SapPurchaseItem> sapPurchaseItemList = this.sapPurchaseApprovalItemApplication.findBySapPurchaseApprovalId(sapPurchase.getId());
        List<SapPurchaseVo> sapPurchaseVoList = new ArrayList<>();
        sapPurchaseItemList.forEach(sapPurchaseItem -> {
            SapPurchaseVo sapPurchaseVo = new SapPurchaseVo();
            BeanUtil.copyProperties(sapPurchaseItem,sapPurchaseVo);
            sapPurchaseVo.setBillCode(sapPurchase.getBillCode());
            sapPurchaseVo.setBsart(sapPurchase.getBsart());
            sapPurchaseVoList.add(sapPurchaseVo);
        });
        ObjectMapper objectMapper = new ObjectMapper();
        String returnJson = null;
        try {
            returnJson = objectMapper.writeValueAsString(sapPurchaseVoList);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        return returnJson;
    }*/

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

    /**
     * @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();
            SapPurchaseApproval sapPurchaseApproval = sapPurchaseApprovalRepository.findOne(bizId);
            sapPurchaseApproval.setStatusId(BizBillStatus.APPLYING.getId());
            sapPurchaseApprovalRepository.save(sapPurchaseApproval);
            //sendSapData(sapPurchaseApproval,"N");
            //终止
            //workflowApplication.abortProcessInstance(delegateTask.getProcessInstanceId());
        }
    }

    @Override
    public Map<String, Object> slicedSapPurchaseApprovalList(SapPurchaseApprovalQueryRequest queryRequest) {
        QueryDescriptor queryDescriptor = this.sqlExecutorDao.getQuery(QUERY_XML_FILE_PATH, "sapPurchaseApprovalList");
        QueryModel queryModel = this.sqlExecutorDao.getQueryModel(queryDescriptor, queryRequest);
        queryModel.putDictionary("status", BizBillStatus.getMap());
        return this.sqlExecutorDao.executeSlicedQuery(queryModel);
    }

    @Override
    public SapPurchaseApproval loadSapPurchaseApproval(String id) {
        return sapPurchaseApprovalRepository.findOne(id);
    }

    @Override
    @Transactional
    public void saveSapPurchaseApprovalVo(SapPurchaseApprovalDto sapPurchaseApprovalDto) {
       // SapPurchaseApproval sapPurchaseApprovalVo = new SapPurchaseApproval();
        SapPurchaseApprovalVo purchaseApprovalVo = sapPurchaseApprovalDto.getLsDeader();
        List<SapPurchaseApproval> purchaseApprovalList = sapPurchaseApprovalRepository.findAllByBanfn(purchaseApprovalVo.getBanfn());
        String purchaseApprovalId = "";
        SapPurchaseApproval sapPurchaseApproval = new SapPurchaseApproval();
        //根据SAP传过来的创建人编码，映射流程发起人
        String ernam = purchaseApprovalVo.getErnam();
        Org org = orgApplication.loadMainOrgByLoginName(ernam);
        String acceptPersonCode = SystemCache.getParameter("acceptPersonCode", String.class);
        if (ObjectUtil.isNull(org)){
            org = orgApplication.loadMainOrgByLoginName(acceptPersonCode);
        }
        if (ObjectUtil.isNotNull(org)){
            Operator operator = operatorApplication.createOperatorByPersonMemberId(org.getId());
            ThreadLocalUtil.putOperator(operator);
        }else {
            //throw new RuntimeException("未找到采购申请创建人：" + ernam);
        }

          //初始化用户信息
       /* String createdById = "5EEB2DC861694A65933CB4CE9A8D870A@C18E23AAAA6940E09DF7C122332C51E0";
        Operator operator = operatorApplication.createOperatorByPersonMemberId(createdById);
        sapPurchaseApproval.setDefaultValues(new OrgUnit(operator.getFullId(), operator.getFullName()));

        Map<String, Object> formData = BeanUtil.beanToMap(sapPurchaseApproval);
        String bizId = this.startProcessInstance(SapPurchaseApprovalApplication.PROCESS_DEFINITION_KEY, formData);
        sapPurchaseApproval.setId(bizId);
        sapPurchaseApproval = this.sapPurchaseApprovalRepository.save(sapPurchaseApproval);
       */
          //发起流程  05.11  lxh
          BeanUtil.copyProperties(sapPurchaseApprovalDto.getLsDeader(), sapPurchaseApproval);
        List<SapPurchaseApprovalItemVo> approvalItemVoList = sapPurchaseApprovalDto.getItems();
        List<SapPurchaseApprovalItem> sapPurchaseApprovalItems =  new ArrayList<>();
        for (SapPurchaseApprovalItemVo approvalItemVo : approvalItemVoList) {
            SapPurchaseApprovalItem sapPurchaseApprovalItem = new SapPurchaseApprovalItem();
            BeanUtil.copyProperties(approvalItemVo,sapPurchaseApprovalItem);
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
            if (StringUtil.isNotBlank(approvalItemVo.getLfdat())){
                try {
                    Date parse = dateFormat.parse(approvalItemVo.getLfdat());
                    sapPurchaseApprovalItem.setLfdat(parse);
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }
            }
            if (StringUtil.isNotBlank(approvalItemVo.getBadat())){
                try {
                    Date parse = dateFormat.parse(approvalItemVo.getBadat());
                    sapPurchaseApprovalItem.setBadat(parse);
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }
            }
            sapPurchaseApprovalItems.add(sapPurchaseApprovalItem);
            sapPurchaseApproval.setKnttp(approvalItemVo.getKnttp());//科目分配类别
            sapPurchaseApproval.setEkgrp(approvalItemVo.getEkgrp());//采购组
        }
        //knttp审批要素没有值时，赋值0，防止发起流程时报错
        if (StringUtil.isBlank(sapPurchaseApproval.getKnttp())){
            sapPurchaseApproval.setKnttp("0");
        }
         // String nextCode = codeGenerator.getNextCode("sapPurchaseApproval");
         // sapPurchaseApproval.setBillCode(nextCode);
         // sapPurchaseApproval = mannualStartWorkflow(sapPurchaseApproval);
          // purchaseOrderId = sapPurchaseApproval.getId();

        if (CollectionUtils.isEmpty(purchaseApprovalList)) {
            purchaseApprovalId=mannualStartWorkApplication.startWorkflow(sapPurchaseApproval,PROCESS_DEFINITION_KEY,"sapPurchaseApproval");

        } else{
            for (SapPurchaseApproval purchaseApproval : purchaseApprovalList) {
                //将存在的作废掉   05.11 lxh

                //终止状态不管
                //审批完成的，SAP撤审触发，终止审批完成的，并发起新的流程
                if (purchaseApproval.getStatusId() == BizBillStatus.COMPLETED.getId()){
                    purchaseApproval.setStatusId(BizBillStatus.ABORTED.getId());
                    purchaseApprovalId=mannualStartWorkApplication.startWorkflow(sapPurchaseApproval,PROCESS_DEFINITION_KEY,"sapPurchaseApproval");
                }

                //在审批中，更新明细数据的（先删除，再新增）
                if (purchaseApproval.getStatusId() == BizBillStatus.APPROVING.getId() || purchaseApproval.getStatusId() == BizBillStatus.APPLYING.getId()){
                    List<SapPurchaseApprovalItem> itemList = sapPurchaseApprovalItemApplication.querySapPurchaseApprovalItems(purchaseApproval.getId());
                    List<String> collect = itemList.stream().map(SapPurchaseApprovalItem::getId).collect(Collectors.toList());
                    sapPurchaseApprovalItemApplication.deleteByIds(collect);
                    purchaseApprovalId = purchaseApproval.getId();
                }
                this.sapPurchaseApprovalRepository.save(purchaseApproval);
            }
        }
        sapPurchaseApprovalItemApplication.saveSapPurchaseApprovalItems(purchaseApprovalId,sapPurchaseApprovalItems);
    }

    /*public String startProcessInstance(String processDefinitionKey,Map<String, Object> formData){
        Map<String, Object> variables = new HashMap();
        SDO localSdo = this.buildSDO(formData);
        ThreadLocalUtil.putVariable(Constants.SDO, localSdo);
        variables.put("startModel", ProcessStartModel.MANUAL.getId());
        Operator operator = localSdo.getOperator();
        variables.put("executorFullId", operator.getFullId());
        variables.put("executorFullName", operator.getFullName());
        ThreadLocalUtil.putOperator(operator);
        ThreadLocalUtil.putVariable("client.ip", "127.0.0.1");
        ProcessInstance processInstance = this.workflowApplication.startProcessInstanceByKey(processDefinitionKey, variables);
        String businessKey = processInstance.getBusinessKey();
        return businessKey;
    } */

    /**
     * 启动流程
     */
    /*private SapPurchaseApproval mannualStartWorkflow(SapPurchaseApproval sapPurchaseApproval) {
        Operator operator = null;
        operator = ThreadLocalUtil.getOperator();
        if (operator == null) {
            String createdById = "5EEB2DC861694A65933CB4CE9A8D870A@C18E23AAAA6940E09DF7C122332C51E0";
            operator = operatorApplication.createOperatorByPersonMemberId(createdById);
            ThreadLocalUtil.putOperator(operator);
        }

        // Assert.notNull(operator, "未获取到当前操作用户，无法创建流程");
        SDO sdo = ThreadLocalUtil.getVariable(Constants.SDO, SDO.class);
        if (sdo == null) {
            sdo = new SDO();
        }
        try {
            // 业务数据
            Map<String, Object> map = ClassHelper.beanToMap(sapPurchaseApproval);
            sdo.setProperties(map);

            // 启动流程的必要参数
            sdo.putProperty("fullId", operator.getFullId());
            sdo.putProperty("organId", operator.getOrgId());
            sdo.putProperty("organName", operator.getOrgName());
            sdo.putProperty("deptId", operator.getDeptId());
            sdo.putProperty("deptName", operator.getDeptName());
            sdo.putProperty("positionId", operator.getPositionId());
            sdo.putProperty("positionName", operator.getPositionName());
            sdo.putProperty("personMemberId", operator.getPersonMemberId());
            sdo.putProperty("personMemberName", operator.getPersonMemberName());
            sdo.putProperty("processAction", ProcessAction.SAVE);
            sdo.putProperty("procUnitId", "");
            //  sdo.putProperty("bizId", purchaseOrder.getId());
            sdo.putProperty("createdDate", new Date());
            sdo.putProperty("fillinDate", new Date());

            sdo.putProperty("billCode", sapPurchaseApproval.getBillCode());
            ThreadLocalUtil.putVariable(Constants.SDO, sdo);
            Map<String, Object> variables = new HashMap<>();
            variables.put("startModel", ProcessStartModel.MANUAL.getId());
            variables.put("executorFullId", operator.getFullId());
            variables.put("executorFullName", operator.getFullName());
            ThreadLocalUtil.putOperator(operator);
            ExecutionEntity pi = (ExecutionEntity) workflowApplication.startProcessInstanceByKey(PROCESS_DEFINITION_KEY, null, variables);
            // 业务参数
            TaskEntity applyTask = pi.getTasks().get(0);
            sdo.putProperty("processAction", ProcessAction.ADVANCE);
            sdo.putProperty("bizId", pi.getBusinessKey());
            sdo.putProperty("id", pi.getBusinessKey());
            sdo.putProperty("statusId", BizBillStatus.APPLYING.getId());
            ThreadLocalUtil.removeVariable("_approvalParameter_");
            ThreadLocalUtil.putVariable(Constants.SDO, sdo);
            workflowApplication.advance(applyTask.getId(), Collections.emptyMap());
            return this.sapPurchaseApprovalRepository.findOne(pi.getBusinessKey());
        }catch(Exception ex){
            ex.printStackTrace();
            throw ex;
        }

    }*/


    private SDO buildSDO(Map<String, Object> formData) {
        //String createdById = (String) formData.get("createdById");
        //暂定管理员id
        String createdById =  SystemCache.getParameter("adminPersonId", String.class);
        Operator operator = operatorApplication.createOperatorByPersonMemberId(createdById);
        SDO localSdo = new SDO();
        // 将业务数据传递给工作流
        formData.forEach(localSdo::putProperty);
        // 将业务流程信息传递给工作流
        localSdo.putProperty("processAction", ProcessAction.SAVE);
        localSdo.putProperty("procUnitId", "Apply");
        localSdo.setOperator(operator);
        return localSdo;
    }

    /**
     * 远程调用sap接口，传递数据
     */
    public void sendSapData(SapPurchaseApproval sapPurchaseApproval, String flag) {
        List<SapPurchaseApprovalItem> approvalItemList = sapPurchaseApprovalItemApplication.querySapPurchaseApprovalItems(sapPurchaseApproval.getId());
        List<Map<String,Object>> paramList= new ArrayList<>();
        for (SapPurchaseApprovalItem sapPurchaseApprovalItem : approvalItemList) {
            Map<String,Object> paramItem = new HashMap<>();
            paramItem.put("banfn",sapPurchaseApproval.getBanfn());
            paramItem.put("BEDNR",sapPurchaseApproval.getBillCode());
            paramItem.put("frgkz","10");
            paramItem.put("bnfpo",sapPurchaseApprovalItem.getBnfpo());
            paramItem.put("flag",flag);
            paramList.add(paramItem);

        }
        Map<String,Object> param = new HashMap<>();
        param.put("MODE","PR");
        param.put("DATA",paramList);

        ObjectMapper objectMapper = new ObjectMapper();
        String url = "pass_approval/approval";
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("businessType", "采购审批");
        resultMap.put("businessId", sapPurchaseApproval.getId());
        resultMap.put("parameter", JSON.toJSONString(param));
        try {
            String result = defaultHttpClient.execute(param, url);
            List<Map<String, Object>> resultList = objectMapper.readValue(result, new TypeReference<List<Map<String, Object>>>() {});
            Map<String, Object> backMap = resultList.get(0);
            if (!"S".equals(backMap.get("TYPE"))) {
                throw new RuntimeException("数据传输失败，请稍后手动重试！"+backMap.get("MESSAGE"));
            } else {
                resultMap.put("TYPE", backMap.get("TYPE"));
                resultMap.put("MESSAGE", backMap.get("MESSAGE"));
            }
            sapPurchaseApproval.setType((String) backMap.get("TYPE"));
            sapPurchaseApproval.setMessage((String) backMap.get("MESSAGE"));
            sapPurchaseApprovalRepository.save(sapPurchaseApproval);
        } catch (Exception e) {
            resultMap.put("TYPE", "E");
            resultMap.put("MESSAGE", e.getMessage());
            throw new RuntimeException("数据传输失败请检查数据后重试！"+e.getMessage());
        }finally {
            sapMutualEpLogApplication.saveSapMutualEpLog(resultMap);
        }
    }

    @Override
    public  String revokeApproval(String id){
        SapPurchaseApproval sapPurchaseApproval = this.sapPurchaseApprovalRepository.findOne(id);
        if (sapPurchaseApproval.getStatusId()!=BizBillStatus.COMPLETED.getId()){
            throw new RuntimeException("审批完成的单据才能撤销！");
        }
        sapPurchaseApproval.setStatusId(BizBillStatus.ABORTED.getId());
        sapPurchaseApprovalRepository.save(sapPurchaseApproval);
        List<SapPurchaseApprovalItem> sapPurchaseApprovalItemList=this.sapPurchaseApprovalItemApplication.querySapPurchaseApprovalItems(id);
        //发起流程
        SapPurchaseApproval newSapPurchaseApproval=new SapPurchaseApproval();
        ClassHelper.copyProperties(sapPurchaseApproval,newSapPurchaseApproval);
        newSapPurchaseApproval.setId("");

        String pId=mannualStartWorkApplication.startWorkflow(newSapPurchaseApproval,PROCESS_DEFINITION_KEY,"sapPurchaseApproval");
        newSapPurchaseApproval=this.sapPurchaseApprovalRepository.findOne(pId);

        List<SapPurchaseApprovalItem> newSapPurchaseApprovalItemList=new ArrayList<>();
        for (SapPurchaseApprovalItem sapPurchaseApprovalItem:sapPurchaseApprovalItemList){
            SapPurchaseApprovalItem newSapPurchaseApprovalItem=new SapPurchaseApprovalItem();
            ClassHelper.copyProperties(sapPurchaseApprovalItem,newSapPurchaseApprovalItem);
            newSapPurchaseApprovalItem.setId("");
            newSapPurchaseApprovalItemList.add(newSapPurchaseApprovalItem);
        }
        sapPurchaseApprovalItemApplication.saveSapPurchaseApprovalItems(newSapPurchaseApproval.getId(),newSapPurchaseApprovalItemList);

        return newSapPurchaseApproval.getId();
    }
}
