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.SystemCache;
import com.huigou.context.Operator;
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.base.task.BaseTask;
import com.huigou.topsun.sap.common.DefaultHttpClient;
import com.huigou.topsun.sap.common.application.SapMutualEpLogApplication;
import com.huigou.topsun.sap.common.domain.SapMutualEpLog;
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.sapApplication.application.SapDictionaryApplication;
import com.huigou.topsun.sap.transfers.application.SapStockTransfersApplication;
import com.huigou.uasp.bmp.common.BizBillStatus;
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.util.*;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.DelegateTask;
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.io.IOException;
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;
    @Autowired
    private SapStockTransfersApplication sapStockTransfersApplication;
    @Autowired
    private SapDictionaryApplication sapDictionaryApplication;
    @Autowired
    private BaseTask baseTask;

    @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());
        String title = "";
        if ("update".equals(sapPurchaseApproval.getRevokeType())){
            title = "撤审修改-";
        }else if ("close".equals(sapPurchaseApproval.getRevokeType())){
            title = "撤审关单-";
        }
        //设置标题
        return String.format("%s-%s(%s)", title + 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();
        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);
        if (StringUtil.isBlank(sapPurchaseApproval.getRevokeReason())){
            //如果没有撤销原因，才去调用sap接口；撤审通知去sap主动撤审
            sendSapData(sapPurchaseApproval,"Y","");
        }else {
            this.sendSapData(sapPurchaseApproval, "N","3");
        }
    }

    /**
     * 转换成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","0");
            //终止
            //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<>();
        String loekz = "";//删除标识
        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());//采购组

            //采购申请是库存转储时，修改表头采购申请类型描述
            if ("7".equals(sapPurchaseApprovalItem.getPstyp())){
                sapPurchaseApproval.setBatxt(sapPurchaseApprovalItem.getPtext());
            }
            if ("X".equals(approvalItemVo.getLoekz())){
                loekz = "X";
            }
        }
        //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{
            boolean needStartWorkflow = true;
            for (SapPurchaseApproval purchaseApproval : purchaseApprovalList) {
                //将存在的作废掉   05.11 lxh

                //审批完成的，终止状态的，终止审批完成的，并发起新的流程
                if (purchaseApproval.getStatusId() == BizBillStatus.COMPLETED.getId() || purchaseApproval.getStatusId() == BizBillStatus.ABORTED.getId()){
                    purchaseApproval.setStatusId(BizBillStatus.ABORTED.getId());
                    if ("X".equals(loekz)){
                        //如果在SAP中删除了，终止流程，不另外发起新的流程
                        needStartWorkflow = false;
                    }
                }

                //在审批中，更新明细数据的（先删除，再新增）
                if (purchaseApproval.getStatusId() == BizBillStatus.APPROVING.getId() || purchaseApproval.getStatusId() == BizBillStatus.APPLYING.getId()){
                    needStartWorkflow = false;
                    //更新主表信息
                    purchaseApproval.setBsart(sapPurchaseApproval.getBsart());
                    purchaseApproval.setBatxt(sapPurchaseApproval.getBatxt());
                    purchaseApproval.setKnttp(sapPurchaseApproval.getKnttp());
                    purchaseApproval.setEkgrp(sapPurchaseApproval.getEkgrp());

                    List<SapPurchaseApprovalItem> itemList = sapPurchaseApprovalItemApplication.querySapPurchaseApprovalItems(purchaseApproval.getId());
                    List<String> collect = itemList.stream().map(SapPurchaseApprovalItem::getId).collect(Collectors.toList());
                    sapPurchaseApprovalItemApplication.deleteByIds(collect);
                    purchaseApprovalId = purchaseApproval.getId();

                    if ("X".equals(loekz)){
                        purchaseApproval.setStatusId(BizBillStatus.ABORTED.getId());
                        baseTask.deleteRunTimeTaskExtensionByBizId(purchaseApproval.getId());
                        baseTask.updateHistoricTaskInstanceExtensionByBizId(purchaseApproval.getId());
                    }
                }
                this.sapPurchaseApprovalRepository.save(purchaseApproval);
            }
            if (needStartWorkflow){
                purchaseApprovalId=mannualStartWorkApplication.startWorkflow(sapPurchaseApproval,PROCESS_DEFINITION_KEY,"sapPurchaseApproval");
            }
        }
        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,String status) {
        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);
            paramItem.put("status",status);
            //如果是关单，传X和0
            if ("close".equals(sapPurchaseApproval.getRevokeType())){
                paramItem.put("ELIKZ", "X");
                paramItem.put("status", 0);
            }
            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));
        String type = "";
        String message = "";
        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);
            type = (String) backMap.get("TYPE");
            message = (String) backMap.get("MESSAGE");
            if (!"S".equals(type)) {
                throw new RuntimeException("数据传输失败，请稍后手动重试！"+message);
            } else {
                resultMap.put("TYPE", type);
                resultMap.put("MESSAGE", message);
            }
        } catch (Exception e) {
            resultMap.put("TYPE", "E");
            resultMap.put("MESSAGE", e.getMessage());
            throw new RuntimeException("数据传输失败请检查数据后重试！"+e.getMessage());
        }finally {
            sapPurchaseApproval.setType(type);
            sapPurchaseApproval.setMessage(message);
            sapPurchaseApprovalRepository.save(sapPurchaseApproval);
            sapMutualEpLogApplication.saveSapMutualEpLog(resultMap);
        }

        //根据明细的项目类别判断是不是库存转储
        SapPurchaseApprovalItem sapPurchaseApprovalItem = approvalItemList.get(0);
        if ("7".equals(sapPurchaseApprovalItem.getPstyp())){
            sapStockTransfersApplication.createSapStockTransfersFromPurchaseApproval(sapPurchaseApproval,approvalItemList);
        }
    }

    @Override
    public  String revokeApproval(String id,String revokeReason,String revokeType){
        SapPurchaseApproval sapPurchaseApproval = this.sapPurchaseApprovalRepository.findOne(id);
        //验证采购申请单是否生成了采购订单
        String result = this.checkOrderByPurchaseNo(sapPurchaseApproval.getBanfn());
        //Y是可以提交撤审，N是查询到有对应的采购订单，不可以提交撤审
        if ("N".equals(result)){
            throw new RuntimeException("采购申请单已生成采购订单，不能撤销！");
        }

        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("");
        newSapPurchaseApproval.setRevokeReason(revokeReason);
        newSapPurchaseApproval.setRevokeType(revokeType);
        newSapPurchaseApproval.setBillCode("");
        newSapPurchaseApproval.setType(null);
        newSapPurchaseApproval.setMessage(null);
        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();
    }

    @Override
    public String checkOrderByPurchaseNo(String banfn) {
        String result = "";
        try {
            List<Map<String, String>> mapList = sapDictionaryApplication.getSapDictionary("BANFN", banfn);
            if (!CollectionUtils.isEmpty(mapList)){
                result = mapList.get(0).get("ZYN");
            }
        }catch (IOException e){
            throw new RuntimeException("查询采购申请单失败，请稍后重试！");
        }
        return result;
    }

    @Override
    public void abortPurchaseApproval(String id,String jobPageId) {
        //先标记终止状态
        SapPurchaseApproval purchaseApproval = sapPurchaseApprovalRepository.findOne(id);
        List<SapMutualEpLog> logList = sapMutualEpLogApplication.findByBusinessId(purchaseApproval.getId());
        if (!CollectionUtils.isEmpty(logList)){
            List<String> types = logList
                    .stream()
                    .map(SapMutualEpLog::getType)
                    .collect(Collectors.toList());
            if (types.contains("E")){
                purchaseApproval.setStatusId(BizBillStatus.ABORTED.getId());
                //删除待办
                actApplication.deleteRuntimeTaskExtension(jobPageId);
                sapPurchaseApprovalRepository.save(purchaseApproval);
            }
            else {
                throw new RuntimeException("正常流程不能强制终止");
            }
        }else {
            throw new RuntimeException("正常流程不能强制终止");
        }
    }
}
