package com.sunda.spmsweb.oaservice;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sunda.spmscommon.service.ISysLogService;
import com.sunda.spmscommon.utils.OAMainUtils;
import com.sunda.spmsuser.entity.SpmsUser;
import localhost.services.ExtHrmresources.AnyType2AnyTypeMapEntry;
import localhost.services.ExtHrmresources.ExtHrmresourcesPortTypeProxy;
import localhost.services.RequestService.RequestServicePortTypeProxy;
import localhost.services.WorkflowData.WorkflowDataPortTypeProxy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import weaver.soa.workflow.request.MainTableInfo;
import weaver.soa.workflow.request.Property;
import weaver.soa.workflow.request.RequestInfo;

import javax.annotation.PostConstruct;
import java.math.BigDecimal;
import java.rmi.RemoteException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.sunda.spmscommon.Constans.*;

/**
 * @program: spms
 * @description: OaServiceImpl
 * @author: Wayne Wu
 * @create: 2021-03-01 18:48
 **/
@Slf4j
@Component
public class OaService {

    @Autowired
    ISysLogService iSysLogService;

    // 静态初使化当前类
    public static OaService oaService;


    private static final String APPID = "44977cbe-6f5f-4f72-89bd-d0a22156f463";

    //注解@PostConstruct，这样方法就会在Bean初始化之后被Spring容器执行
    @PostConstruct
    public void init() {
        oaService = this;
    }

    /** 生产环境 OA 审批流对应流程ID */
//    String workflow0915 = "520";


    /***
     * 根据用户工号，向OA系统请求获取用户详细信息
     * @param userId
     * @return
     */
    public Map<String, Object> getUserInfo(String userId) {
        Map<String, Object> map = new HashMap<>();
        ExtHrmresourcesPortTypeProxy extHrmresourcesPortTypeProxy = new ExtHrmresourcesPortTypeProxy();
        try {
        	AnyType2AnyTypeMapEntry[] sss = extHrmresourcesPortTypeProxy.getUserInfoByWorkcode(userId);
        	JSONArray array = (JSONArray) JSON.toJSON(sss);
        	System.out.println("===1===" + array.toString());
            if (array.size() == 0 || "[]".equals(array.toString()) || "{}".equals(array.getJSONObject(0).toJSONString())){
                return null;
            }
            for (int i = 0; i < array.size(); i ++){
                //System.out.println(array.getJSONObject(i));
                if ("workcode".equals(array.getJSONObject(i).getString("key"))){
                    map.put("userId", array.getJSONObject(i).getString("value"));
                }
                if ("id".equals(array.getJSONObject(i).getString("key"))){
                    map.put("workId", array.getJSONObject(i).getString("value"));
                }
                if ("name".equals(array.getJSONObject(i).getString("key"))){
                    map.put("lastName", array.getJSONObject(i).getString("value"));
                }
                if ("telephone".equals(array.getJSONObject(i).getString("key"))){
                    map.put("telephone", array.getJSONObject(i).getString("value"));
                }
                if ("mobile".equals(array.getJSONObject(i).getString("key"))){
                    map.put("mobile", array.getJSONObject(i).getString("value"));
                }
                if ("email".equals(array.getJSONObject(i).getString("key"))){
                    map.put("email", array.getJSONObject(i).getString("value"));
                }
                if ("jobtitleid".equals(array.getJSONObject(i).getString("key"))){
                    map.put("positionId", array.getJSONObject(i).getString("value"));
                }
                if ("jobtitlename".equals(array.getJSONObject(i).getString("key"))){
                    map.put("positionName", array.getJSONObject(i).getString("value"));
                }
                if ("departmentid".equals(array.getJSONObject(i).getString("key"))){
                    map.put("deptId", array.getJSONObject(i).getString("value"));
                }
                if ("departmentname".equals(array.getJSONObject(i).getString("key"))){
                    map.put("deptName", array.getJSONObject(i).getString("value"));
                }
                if ("subcompanyid".equals(array.getJSONObject(i).getString("key"))){
                    map.put("subcompanyId", array.getJSONObject(i).getString("value"));
                }
                if ("subcompanyname".equals(array.getJSONObject(i).getString("key"))){
                    map.put("subcompanyName", array.getJSONObject(i).getString("value"));
                }
                if ("company".equals(array.getJSONObject(i).getString("key"))){
                    map.put("company", array.getJSONObject(i).getString("value"));
                }
                if ("point".equals(array.getJSONObject(i).getString("key"))){
                    map.put("branchPoint", array.getJSONObject(i).getString("value"));
                }
                if ("line".equals(array.getJSONObject(i).getString("key"))){
                    map.put("branchLine", array.getJSONObject(i).getString("value"));
                }
                if ("managerid".equals(array.getJSONObject(i).getString("key"))){
                    map.put("managerId", array.getJSONObject(i).getString("value"));
                }
                if ("managername".equals(array.getJSONObject(i).getString("key"))){
                    map.put("managerName", array.getJSONObject(i).getString("value"));
                }
                if ("status".equals(array.getJSONObject(i).getString("key"))){
                    map.put("oaStatus", array.getJSONObject(i).getString("value"));
                }
            }
            return map;
		} catch (Exception e) {
			e.printStackTrace();
		}
        return null;
    }

    /***
     * 根据用户工号，向OA系统请求获取用户详细信息
     * @param userId
     * @return
     */
    public Map<String, Object> getUserInfoByOaV2(String userId,String oaUrl) {
        Map<String, Object> map = new HashMap<>();
        try {
            OAMainUtils oaMainUtils = new OAMainUtils();
            String userInfo = oaMainUtils.oaRestFull(userId,oaUrl);
            JSONObject userDoc = JSONObject.parseObject(userInfo);
            String id = "";
            String departmentid = "";
            if("true".equals(userDoc.getString("api_status"))){
                String data = userDoc.getString("data");
                JSONObject dataJson = JSONObject.parseObject(data);
                if(dataJson.getString("workcode")==null){
                    return null;
                }
                map.put("userId", dataJson.getString("workcode"));
                map.put("workId", dataJson.getString("id"));
                map.put("lastName", dataJson.getString("name"));
                map.put("telephone", dataJson.getString("telephone"));
                map.put("mobile", dataJson.getString("mobile"));
                map.put("email", dataJson.getString("email"));
                map.put("positionId", dataJson.getString("jobtitleid"));
                map.put("positionName", dataJson.getString("jobtitlename"));
                map.put("deptId", dataJson.getString("departmentid"));
                map.put("deptName", dataJson.getString("departmentname"));
                map.put("subcompanyId", dataJson.getString("subcompanyid"));
                map.put("subcompanyName", dataJson.getString("subcompanyname"));
                map.put("company", dataJson.getString("company"));
                map.put("branchPoint", dataJson.getString("point"));
                map.put("branchLine", dataJson.getString("line"));
                map.put("managerId", dataJson.getString("managerid"));
                map.put("managerName", dataJson.getString("managername"));
                map.put("oaStatus", dataJson.getString("status"));
                return map;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 返回 OA 处理结果代码，小于等于 0 则失败；
     * -1：创建流程失败
     * -2：用户没有流程创建权限
     * -3：创建流程基本信息失败
     * -4：保存表单主表信息失败
     * -5：更新紧急程度失败
     * -6：流程操作者失败
     * -7：流转至下一节点失败
     * -8：节点附加操作失败
     * @param jsonObject
     * @param spmsId
     * @param spmsUser
     * @param string 
     * @return
     */
    public int createRequest(JSONObject jsonObject, String spmsId, SpmsUser spmsUser,
                             String workflow0703, String workflow1201, String workflow3601, String workflow3302,
                             String workflow0705, String workflow3602,
                             String fileName, String fileUrl,String oaUrl,boolean newOa,List<Map<String, Object>> orderItem){
        if (!jsonObject.getJSONObject("orderWerks").containsKey("oaProcessId") || jsonObject.getJSONObject("orderWerks").getString("oaProcessId").length() == 0){
            return 0;
        }
        String oaProcessId = jsonObject.getJSONObject("orderWerks").getString("oaProcessId");
        JSONObject doc = jsonObject.getJSONObject("orderWerks");
        if ("0703".equals(oaProcessId)){
            /** OA workflow id 0703 : 580 开发测试；240 正式；  */
            return createRequest0703(doc, spmsId, spmsUser, workflow0703,fileUrl,oaUrl,newOa);
        }
        if ("1201".equals(oaProcessId)){
            /** OA workflow id 1201 : 589 开发测试；262 正式； */
            return createRequest1201(doc, spmsId, spmsUser, workflow1201,fileUrl,oaUrl,newOa);
        }
        if ("3601".equals(oaProcessId)){
            /** OA workflow id 3601 : 592 开发测试；353 正式； */
            return createRequest3601(doc, spmsId, spmsUser, workflow3601,fileUrl,oaUrl,newOa);
        }
        if ("3302".equals(oaProcessId)){
        	/** OA workflow id 3302 : 668 开发测试；353 正式； */
        	return createRequest3302(doc, spmsId, spmsUser, workflow3302,fileUrl,oaUrl,newOa);
        }
        if ("0705".equals(oaProcessId) || "3602".equals(oaProcessId)){
            return createRequest0705(doc, spmsId, spmsUser, workflow0705,workflow3602,fileUrl,oaUrl,newOa,orderItem);
        }
        return 0;
    }

	/** 被驳回的工厂请购单——状态 4，经机电主任修改后重新提交OA系统，新状态为：7 —— 重新提交 OA；待完成； */
    public boolean reSubmitOa(JSONObject doc, SpmsUser spmsUser,
                              String workflow0703, String workflow1201, String workflow3601, String workflow3302,
                              String workflow0705, String workflow3602,
                              String fileUrl,String oaUrl,boolean newOa,List<Map<String, Object>> orderItem){
        try {
            Map<String, Object> rl = new HashMap<String, Object>();
            List<Map<String, Object>> aas = new ArrayList<Map<String, Object>>();
            RequestServicePortTypeProxy wfproxy = new RequestServicePortTypeProxy();
            String oaProcessId = doc.getJSONObject("orderWerks").getString("oaProcessId");
            String oaBianhao = doc.getJSONObject("orderWerks").getString("oaBianhao");
            String spmsId = doc.getJSONObject("orderWerks").getString("spmsId");
            JSONObject orderWerks = doc.getJSONObject("orderWerks");
            RequestInfo reqinfo = new RequestInfo();
            reqinfo.setCreatorid(spmsUser.getWorkId());
            Map<String, Object> map = new HashMap<>();
            MainTableInfo wmi = new MainTableInfo();
            if ("0703".equals(oaProcessId)){
                reqinfo.setWorkflowid(workflow0703);
                rl.put("workflowId", workflow0703);
                map.put("xgfj", fileUrl == null ? "" : fileUrl);
                Property[] wrti = new Property[map.size()];
                int i = 0;
                for (Map.Entry<String, Object> entry : map.entrySet()){
                    wrti[i] = new Property();
                    wrti[i].setName(entry.getKey());
                    wrti[i].setValue(entry.getValue().toString());
                    if (entry.getKey().equals("xgfj")){
                        wrti[i].setType("http:" + "附件-备品备件请购单明细表.xlsx");
                    }
                    i ++;

                    Map<String, Object> ol = new HashMap<String, Object>();
                    ol.put("fieldName", entry.getKey());
                    ol.put("fieldValue", entry.getValue().toString());
                    if (entry.getKey().equals("xgfj")){
                        List<Map<String, Object>> file = new ArrayList<Map<String, Object>>();
                        Map<String, Object> mapFIle = new HashMap<String, Object>();
                        mapFIle.put("filePath",entry.getValue().toString());
                        mapFIle.put("fileName","附件-备品备件请购单明细表.xlsx");
                        file.add(mapFIle);
                        ol.put("fieldValue", file);
                    }
                    aas.add(ol);
                }
                wmi.setProperty(wrti);
            }
            if ("1201".equals(oaProcessId)){
                reqinfo.setWorkflowid(workflow1201);
                rl.put("workflowId", workflow1201);
                map.put("xiangguanfujian", fileUrl == null ? "" : fileUrl);
                Property[] wrti = new Property[map.size()];
                int i = 0;
                for (Map.Entry<String, Object> entry : map.entrySet()){
                    wrti[i] = new Property();
                    wrti[i].setName(entry.getKey());
                    wrti[i].setValue(entry.getValue().toString());
                    if (entry.getKey().equals("xiangguanfujian")){
                        wrti[i].setType("http:" + "附件-备品备件请购单明细表.xlsx");
                    }
                    i ++;

                    Map<String, Object> ol = new HashMap<String, Object>();
                    ol.put("fieldName", entry.getKey());
                    ol.put("fieldValue", entry.getValue().toString());
                    if (entry.getKey().equals("xiangguanfujian")){
                        List<Map<String, Object>> file = new ArrayList<Map<String, Object>>();
                        Map<String, Object> mapFIle = new HashMap<String, Object>();
                        mapFIle.put("filePath",entry.getValue().toString());
                        mapFIle.put("fileName","附件-备品备件请购单明细表.xlsx");
                        file.add(mapFIle);
                        ol.put("fieldValue", file);
                    }
                    aas.add(ol);
                }
                wmi.setProperty(wrti);
            }
            if ("3601".equals(oaProcessId)){
                reqinfo.setWorkflowid(workflow3601);
                rl.put("workflowId", workflow3601);
                map.put("fujian", fileUrl == null ? "" : fileUrl);
                Property[] wrti = new Property[map.size()];
                int i = 0;
                for (Map.Entry<String, Object> entry : map.entrySet()){
                    wrti[i] = new Property();
                    wrti[i].setName(entry.getKey());
                    wrti[i].setValue(entry.getValue().toString());
                    if (entry.getKey().equals("fujian")){
                        wrti[i].setType("http:" + "附件-备品备件请购单明细表.xlsx");
                    }
                    i ++;

                    Map<String, Object> ol = new HashMap<String, Object>();
                    ol.put("fieldName", entry.getKey());
                    ol.put("fieldValue", entry.getValue().toString());
                    if (entry.getKey().equals("fujian")){
                        List<Map<String, Object>> file = new ArrayList<Map<String, Object>>();
                        Map<String, Object> mapFIle = new HashMap<String, Object>();
                        mapFIle.put("filePath",entry.getValue().toString());
                        mapFIle.put("fileName","附件-备品备件请购单明细表.xlsx");
                        file.add(mapFIle);
                        ol.put("fieldValue", file);
                    }
                    aas.add(ol);
                }
                wmi.setProperty(wrti);
            }
            if ("3302".equals(oaProcessId)){
            	reqinfo.setWorkflowid(workflow3302);
                rl.put("workflowId", workflow3302);
            	map.put("fj1", fileUrl == null ? "" : fileUrl);
                map.put("fj2", orderWerks.get("attachmentUrl") == null ? "" : orderWerks.getString("attachmentUrl") );
            	Property[] wrti = new Property[map.size()];
            	int i = 0;
            	for (Map.Entry<String, Object> entry : map.entrySet()){
            		wrti[i] = new Property();
            		wrti[i].setName(entry.getKey());
            		wrti[i].setValue(entry.getValue().toString());
            		if (entry.getKey().equals("fj1")){
            			wrti[i].setType("http:" + "附件-劳保用品请购单明细表.xlsx");
            		}
                    if (entry.getKey().equals("fj2")){
                        wrti[i].setType(orderWerks.get("attachmentName") == null ? "" : orderWerks.getString("attachmentName"));
                    }
            		i ++;

                    Map<String, Object> ol = new HashMap<String, Object>();
                    ol.put("fieldName", entry.getKey());
                    ol.put("fieldValue", entry.getValue().toString());
                    if (entry.getKey().equals("fj1")){
                        List<Map<String, Object>> file = new ArrayList<Map<String, Object>>();
                        Map<String, Object> mapFIle = new HashMap<String, Object>();
                        mapFIle.put("filePath",entry.getValue().toString());
                        mapFIle.put("fileName","附件-劳保用品请购单明细表.xlsx");
                        file.add(mapFIle);
                        ol.put("fieldValue", file);
                    }
                    if (entry.getKey().equals("fj2")){
                        List<Map<String, Object>> file = new ArrayList<Map<String, Object>>();
                        Map<String, Object> mapFIle = new HashMap<String, Object>();
                        mapFIle.put("filePath",entry.getValue().toString());
                        mapFIle.put("fileName",orderWerks.get("attachmentName") == null ? "" : orderWerks.getString("attachmentName"));
                        file.add(mapFIle);
                        ol.put("fieldValue", file);
                    }
                    aas.add(ol);
            	}
            	wmi.setProperty(wrti);
            }

            if ("0705".equals(oaProcessId) || "3602".equals(oaProcessId)){
                map.put("zd2", orderWerks.getString("applicationDate"));//申请日期
                map.put("zd4", spmsUser.getWorkId());//申请人
                map.put("zd5", spmsUser.getDeptId() == null  ? "" : spmsUser.getDeptId());//部门
                map.put("zd6", spmsUser.getPositionId() == null  ? "" : spmsUser.getPositionId());//岗位
                map.put("zd3", spmsUser.getUserId());//工号
                if ("0705".equals(oaProcessId)){
                    map.put("xqzt", orderWerks.getString("prSubject"));//需求主体
                }
                map.put("wltype", orderWerks.get("itemType") == null ? 0 : Integer.parseInt(orderWerks.getString("itemType")));//物品类别
                map.put("gc", orderWerks.get("werks") == null ? "" : orderWerks.getString("werks"));//SPMS需求工厂
                map.put("spmsordernum", spmsId);//SPMS单据号
                //map.put("currency", "CNY");//币种
                for (int j = 0; j < orderItem.size(); j++) {
                    Map<String, Object> itemDTO = orderItem.get(j);
                    if(itemDTO.get("waers")!=null && itemDTO.get("waers").toString().length()>0){
                        map.put("currency", itemDTO.get("waers"));//币种
                        continue;
                    }
                }

                map.put("yjfy", orderWerks.get("estimateCost") == null ? "" : orderWerks.getString("estimateCost"));//预计费用合计
                map.put("yjfyrbm", orderWerks.get("estimateCost") == null ? "" : orderWerks.getString("estimateCost"));//预计费用合计（RMB）
                //map.put("guojia", orderWerks.get("country") == null ? "" : orderWerks.getString("country"));//国家
                //map.put("cgy", "");//采购经理
                map.put("zd10", orderWerks.get("justification") == null ? "" : orderWerks.getString("justification"));//备注
                //map.put("zd11", orderWerks.get("justification") == null ? "" : orderWerks.getString("justification"));//工厂请购单抬头备注
                // 分公司
                map.put("zd6", spmsUser.getCompany() == null ? "" : spmsUser.getCompany());
                // 分点
                map.put("zd7", spmsUser.getBranchPoint() == null ? "" : spmsUser.getBranchPoint());
                // 分线
                map.put("zd8", spmsUser.getBranchLine() == null ? "" : spmsUser.getBranchLine());

                // 请购单明细附件
                //map.put("fj1", fileUrl == null ? "" : fileUrl);
                // 请购单审批附件
                if(orderWerks.get("attachmentUrl") != null && orderWerks.getString("attachmentUrl").length()>0){
                    map.put("xgfj", orderWerks.get("attachmentUrl") == null ? "" : orderWerks.getString("attachmentUrl") );
                }
                /** 请求OA内容记录 */
                oaService.iSysLogService.addSubmitOaRecord("3", SPMS_SUBMIT_OA, "添加", spmsUser.getUserId(),
                        "com.sunda.spmsweb.oaservice.createRequest0705()", "", JSON.toJSONString(reqinfo), "WebService", orderWerks.toJSONString(), spmsId);

                String reqid = "0";
                rl.put("requestName", orderWerks.getString("subject"));
                if ("0705".equals(oaProcessId)){
                    rl.put("workflowId", workflow0705);
                }else if ("3602".equals(oaProcessId)){
                    rl.put("workflowId", workflow3602);
                }
                rl.put("requestLevel", orderWerks.getString("urgency"));
                rl.put("remindtype", "0");
                rl.put("isNextFlow", "1");
                rl.put("description",orderWerks.getString("subject"));

                for (Map.Entry<String, Object> entry : map.entrySet()){
                    Map<String, Object> ol = new HashMap<String, Object>();
                    ol.put("fieldName", entry.getKey());
                    if (entry.getKey().equals("fj1")){
                        List<Map<String, Object>> file = new ArrayList<Map<String, Object>>();
                        Map<String, Object> mapFIle = new HashMap<String, Object>();
                        mapFIle.put("filePath",entry.getValue().toString());
                        mapFIle.put("fileName","附件-本地采购请购单明细表.xlsx");
                        file.add(mapFIle);
                        ol.put("fieldValue", file);
                    }else  if (entry.getKey().equals("xgfj")){
                        List<Map<String, Object>> file = new ArrayList<Map<String, Object>>();
                        String filePath = entry.getValue().toString();
                        String fileName = orderWerks.get("attachmentName") == null ? "" : orderWerks.getString("attachmentName");
                        String[] filePaths = filePath.split(",");
                        String[] fileNames = fileName.split(",");
                        for (int s = 0; s < filePaths.length; s ++){
                            Map<String, Object> mapFIle = new HashMap<String, Object>();
                            mapFIle.put("filePath",filePaths[s]);
                            mapFIle.put("fileName",fileNames[s]);
                            file.add(mapFIle);
                        }
                        ol.put("fieldValue", file);
                    }else{
                        ol.put("fieldValue", entry.getValue() == null ? "" : entry.getValue().toString());
                    }
                    aas.add(ol);
                }
                if ("0705".equals(oaProcessId)){
                    rl.put("mainData", JSONUtil.parseArray(aas).toString());
                }else if ("3602".equals(oaProcessId)){
                    rl.put("mainData", JSONUtil.parseArray(aas).toString());
                }
                List<Map<String, Object>> mapList = new ArrayList<>();
                for (int j = 0; j < orderItem.size(); j++) {
                    Map<String, Object> itemDTO = orderItem.get(j);
                    //double discrepancy = Double.parseDouble(itemDTO.get("discrepancy").toString());
                    Map<String, Object> mapItem = new HashMap<>();
                    mapItem.put("wpmc", itemDTO.get("materialZhDesc"));//物品名称
                    //mapItem.put("wpms", itemDTO.get("materialZhDesc"));//规格型号
                    mapItem.put("sl", itemDTO.get("approvalQty"));//数量
                    mapItem.put("dw", itemDTO.get("basicUnit"));//单位
                    mapItem.put("dj", itemDTO.get("materialPrice"));//采购单价
                    if(itemDTO.get("materialPrice")!=null && itemDTO.get("approvalQty")!=null){
                        BigDecimal materialPrice = new BigDecimal(itemDTO.get("materialPrice").toString());
                        BigDecimal approvalQty = new BigDecimal(itemDTO.get("approvalQty").toString());;
                        BigDecimal materialTotalPrice = materialPrice.multiply(approvalQty);
                        mapItem.put("je", materialTotalPrice);//采购金额
                    }else{
                        mapItem.put("je", itemDTO.get("materialTotalPrice"));//采购金额
                    }
                    mapItem.put("dhsj", orderWerks.getString("dateRequired"));//到货时间
                    mapItem.put("sybm", "");//使用部门
                    mapItem.put("sqyy", itemDTO.get("rowComment"));//申请原因及用途
                    mapItem.put("gys", "");//供应商
                    mapItem.put("wlbm", itemDTO.get("materialNo"));//物料编码
                    mapList.add(mapItem);
                }
                List<Map<String, Object>> aasDetailList = new ArrayList<>();
                Map<String, Object> aasDetail = new HashMap<>();
                List<Map<String, Object>> detailTableDb = new ArrayList<Map<String, Object>>();
                for (int k = 0; k < mapList.size(); k++) {
                    Map<String, Object> item = mapList.get(k);
                    Map<String, Object> workflowRequestTableRecord = new HashMap<>();
                    workflowRequestTableRecord.put("recordOrder", 0);
                    List<Map<String, Object>> detailTable = new ArrayList<Map<String, Object>>();
                    for (Map.Entry<String, Object> entry : item.entrySet()) {
                        Map<String, Object> ol = new HashMap<String, Object>();
                        ol.put("fieldName", entry.getKey());
                        ol.put("fieldValue", entry.getValue() == null ? "" : entry.getValue().toString());
                        detailTable.add(ol);
                    }
                    workflowRequestTableRecord.put("workflowRequestTableFields", detailTable);
                    detailTableDb.add(workflowRequestTableRecord);
                }
                //明细表
                aasDetail.put("workflowRequestTableRecords", detailTableDb);

                if ("0705".equals(oaProcessId)){
                    if(oaUrl.contains("fm-oa") || oaUrl.contains("oa-ipo")){
                        aasDetail.put("tableDBName", "formtable_main_557_dt1");
                    }else{
                        //集团生产环境是formtable_main_478_dt1
                        //测试环境是formtable_main_479_dt1
                        aasDetail.put("tableDBName", "formtable_main_478_dt1");
                    }
                }else if ("3602".equals(oaProcessId)){
                    //集团生产环境是formtable_main_479_dt1
                    //测试环境是formtable_main_480_dt1
                    aasDetail.put("tableDBName", "formtable_main_480_dt1");
                }

                aasDetailList.add(aasDetail);
                rl.put("detailData", JSONUtil.parseArray(aasDetailList).toString());

            }
            reqinfo.setMainTableInfo(wmi);
            reqinfo.setRequestlevel(orderWerks.getString("urgency"));
            reqinfo.setRemindtype("0");
            reqinfo.setIsNextFlow("1");
            reqinfo.setDescription(orderWerks.getString("subject"));
            /** 请求OA内容记录 */
            oaService.iSysLogService.addSubmitOaRecord("3", SPMS_RE_SUBMIT_OA, "添加", spmsUser.getUserId(),
                    "com.sunda.spmsweb.oaservice.reSubmitOa()", "", JSON.toJSONString(reqinfo), "WebService", orderWerks.toJSONString(), spmsId);

            if(newOa){
//            rl.put("requestLevel", doc.getString("urgency"));
//            rl.put("remindtype", "0");
//            rl.put("isNextFlow", "1");
//            rl.put("description",doc.getString("subject"));
                rl.put("requestId",oaBianhao);
                rl.put("remark","");
                rl.put("requestLevel", orderWerks.getString("urgency"));
                rl.put("description",orderWerks.getString("subject"));

                rl.put("mainData", JSONUtil.parseArray(aas).toString());
                String jsonParams = JSONUtil.parseObj(rl).toString();
                OAMainUtils oaMainUtils = new OAMainUtils();
                log.info("推送至OA的参数jsonParams()：" + jsonParams);
                String message =  oaMainUtils.oaRestFul(oaUrl, "/api/workflow/paService/submitRequest", rl,spmsUser.getUserId());
                log.info("OA返回的参数message：" + message);
                JSONObject messageDoc = JSONObject.parseObject(message);
                String reqid = "";
                if("SUCCESS".equals(messageDoc.getString("code"))){
//                String data = messageDoc.getString("data");
//                JSONObject dataJson = JSONObject.parseObject(data);
//                reqid = dataJson.getString("requestid");
                }else{
                    throw new Exception("保存异常：" + messageDoc.getString("errMsg"));
                }
                return true;
            }else{
                return wfproxy.nextNodeBySubmit(reqinfo, Integer.parseInt(oaBianhao), Integer.parseInt(spmsUser.getWorkId()), "");
            }
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }

    public int createRequest0703(JSONObject doc, String spmsId, SpmsUser spmsUser, String workflow0703, String fileUrl, String oaUrl, boolean newOa){
		RequestServicePortTypeProxy wfproxy = new RequestServicePortTypeProxy();
		try {
			RequestInfo reqinfo = new RequestInfo();
			reqinfo.setCreatorid(spmsUser.getWorkId());
			reqinfo.setWorkflowid(workflow0703);
			reqinfo.setRequestlevel(doc.getString("urgency"));
			reqinfo.setRemindtype("0");
			reqinfo.setIsNextFlow("1");
			reqinfo.setDescription(doc.getString("subject"));

			Map<String, Object> map = new HashMap<>();
			map.put("zd2", doc.getString("applicationDate"));
            map.put("zd4", spmsUser.getWorkId());
            //map.put("zd7", spmsUser.getSubcompanyId() == null ? "" : spmsUser.getSubcompanyId());
            /** 分公司字段取值修改 20210804 */
            map.put("zd7", spmsUser.getCompany() == null ? "" : spmsUser.getCompany());
            map.put("zd8", spmsUser.getBranchPoint() == null ? "" : spmsUser.getBranchPoint());
            map.put("zd9", spmsUser.getBranchLine() == null  ? "" : spmsUser.getBranchLine());
            map.put("zd5", spmsUser.getDeptId() == null  ? "" : spmsUser.getDeptId());
            map.put("zd6", spmsUser.getPositionId() == null  ? "" : spmsUser.getPositionId());
            map.put("zd3", spmsUser.getUserId());
            map.put("zd11", doc.get("justification") == null ? "" : doc.getString("justification"));
            map.put("xmh", doc.get("projectCode") == null ? "" : doc.getString("projectCode"));
            map.put("cgdd", doc.get("purchaseLocation") == null ? 0 : Integer.parseInt(doc.getString("purchaseLocation")));
            map.put("sqlb", doc.get("applicationType") == null ? 0 : (doc.getString("applicationType").length() == 0 ? 0 : Integer.parseInt(doc.getString("applicationType"))));
            map.put("yjfy", doc.get("estimateCost") == null ? 0.00 : (doc.getString("estimateCost").length() == 0 ? 0.00 : Double.parseDouble(doc.getString("estimateCost"))));
            //map.put("spmsurl", "");
            //map.put("dj", 0);
            //map.put("zd11", "");
            //map.put("je", 0);
            map.put("zd10", "");
            map.put("xglc", "");
            //map.put("xgfj", "");
            map.put("cgy", "");
            map.put("spmsordernum", spmsId);
            map.put("xgfj", fileUrl == null ? "" : fileUrl);

			MainTableInfo wmi = new MainTableInfo();
			Property[] wrti = new Property[map.size()];
            int i = 0;
            for (Map.Entry<String, Object> entry : map.entrySet()){
                wrti[i] = new Property();
                wrti[i].setName(entry.getKey());
                wrti[i].setValue(entry.getValue().toString());
                if (entry.getKey().equals("xgfj")){
                    wrti[i].setType("http:" + "附件-备品备件请购单明细表.xlsx");
                }
                i ++;
            }
			wmi.setProperty(wrti);
			reqinfo.setMainTableInfo(wmi);

            /** 请求OA内容记录 */
            oaService.iSysLogService.addSubmitOaRecord("3", SPMS_SUBMIT_OA, "添加", spmsUser.getUserId(),
                    "com.sunda.spmsweb.oaservice.createRequest0703()", "", JSON.toJSONString(reqinfo), "WebService", doc.toJSONString(), spmsId);

            String reqid = "0";
            if(newOa){
                Map<String, Object> rl = new HashMap<String, Object>();
                rl.put("requestName", doc.getString("subject"));
                rl.put("workflowId", workflow0703);
                rl.put("requestLevel", doc.getString("urgency"));
                rl.put("remindtype", "0");
                rl.put("isNextFlow", "1");
                rl.put("description",doc.getString("subject"));

                List<Map<String, Object>> aas = new ArrayList<Map<String, Object>>();
                for (Map.Entry<String, Object> entry : map.entrySet()){
                    Map<String, Object> ol = new HashMap<String, Object>();
                    ol.put("fieldName", entry.getKey());
                    ol.put("fieldValue", entry.getValue().toString());
                    if (entry.getKey().equals("xgfj")){
                        List<Map<String, Object>> file = new ArrayList<Map<String, Object>>();
                        Map<String, Object> mapFIle = new HashMap<String, Object>();
                        mapFIle.put("filePath",entry.getValue().toString());
                        mapFIle.put("fileName","附件-备品备件请购单明细表.xlsx");
                        file.add(mapFIle);
                        ol.put("fieldValue", file);
                    }
                    aas.add(ol);
                }
                rl.put("mainData", JSONUtil.parseArray(aas).toString());
                String jsonParams = JSONUtil.parseObj(rl).toString();
                OAMainUtils oaMainUtils = new OAMainUtils();
                log.info("推送至OA的参数jsonParams()：" + jsonParams);
                String message =  oaMainUtils.oaRestFul(oaUrl, "/api/workflow/paService/doCreateRequest", rl,spmsUser.getUserId());
                log.info("OA返回的参数message：" + message);
                JSONObject messageDoc = JSONObject.parseObject(message);
                if("SUCCESS".equals(messageDoc.getString("code"))){
                    String data = messageDoc.getString("data");
                    JSONObject dataJson = JSONObject.parseObject(data);
                    reqid = dataJson.getString("requestid");
                }else{
                    throw new Exception("保存异常：" + messageDoc.getString("errMsg"));
                }
            }else{
                // 生成待办 ，返回待办id
                reqid = wfproxy.createRequest(reqinfo);
            }
            // 返回大于0 的数字则调用成功
			System.out.println("reqid ======== " + reqid);
            return Integer.parseInt(reqid);
		} catch (Exception e) {
            e.printStackTrace();
			System.out.println(e.getMessage());
            return 0;
		}
    }

    public int createRequest1201(JSONObject doc, String spmsId, SpmsUser spmsUser, String workflow1201, String fileUrl, String oaUrl, boolean newOa){
        RequestServicePortTypeProxy wfproxy = new RequestServicePortTypeProxy();
        try {
            RequestInfo reqinfo = new RequestInfo();
            reqinfo.setCreatorid(spmsUser.getWorkId());
            /** OA workflow id 1201 : 589 测试；262 正式； */
            reqinfo.setWorkflowid(workflow1201);
            reqinfo.setRequestlevel(doc.getString("urgency"));
            reqinfo.setRemindtype("0");
            reqinfo.setIsNextFlow("1");
            reqinfo.setDescription(doc.getString("subject"));

            Map<String, Object> map = new HashMap<>();
            map.put("riqi", doc.getString("applicationDate"));
            map.put("shenqingren", spmsUser.getWorkId());
            map.put("bumen", spmsUser.getDeptId() == null  ? "" : spmsUser.getDeptId());
            map.put("zhiwu", spmsUser.getPositionId() == null  ? "" : spmsUser.getPositionId());
            //OA流程所需，前台不展示，传空
            map.put("fybm", 0);
            //OA新增
            map.put("fybmspms", "");
            map.put("xmlx", doc.get("projectType") == null ? 0 : (doc.getString("projectType").length() == 0 ? 0 : Integer.parseInt(doc.getString("projectType"))));
            map.put("status", doc.get("projectStatus") == null ? 0 : (doc.getString("projectStatus").length() == 0 ? 0 : Integer.parseInt(doc.getString("projectStatus"))));
            map.put("sfhy", doc.get("shippingType") == null ? 0 : (doc.getString("shippingType").length() == 0 ? 0 : Integer.parseInt(doc.getString("shippingType"))));
            map.put("devicetype", doc.get("deviceType") == null ? 0 : (doc.getString("deviceType").length() == 0 ? 0 : Integer.parseInt(doc.getString("deviceType"))));
            map.put("xmh", doc.get("projectCode") == null ? "" : doc.getString("projectCode"));
            map.put("cgdd", doc.get("purchaseLocation") == null ? 0 : Integer.parseInt(doc.getString("purchaseLocation")));
            map.put("sqlb", doc.get("applicationType") == null ? 0 : (doc.getString("applicationType").length() == 0 ? 0 : Integer.parseInt(doc.getString("applicationType"))));
            map.put("sbqd", doc.get("deviceStatement") == null ? "" : doc.getString("deviceStatement"));
            map.put("cgzje", doc.get("estimateCost") == null ? 0 : (doc.getString("estimateCost").length() == 0 ? 0 : Double.parseDouble(doc.getString("estimateCost"))));
            map.put("remark",doc.get("comments") == null ? "" : doc.getString("comments"));
            map.put("bianhao", "");
            map.put("spmsordernum", spmsId);
            //map.put("xiangguanfujian", "");
            //map.put("spmsurl", "");
            map.put("xiangguanfujian", fileUrl == null ? "" : fileUrl);

            MainTableInfo wmi = new MainTableInfo();
            Property[] wrti = new Property[map.size()];
            int i = 0;
            for (Map.Entry<String, Object> entry : map.entrySet()){
                wrti[i] = new Property();
                wrti[i].setName(entry.getKey());
                wrti[i].setValue(entry.getValue().toString());
                if (entry.getKey().equals("xiangguanfujian")){
                    wrti[i].setType("http:" + "附件-备品备件请购单明细表.xlsx");
                }
                i ++;
            }
            wmi.setProperty(wrti);
            reqinfo.setMainTableInfo(wmi);

            /** 请求OA内容记录 */
            oaService.iSysLogService.addSubmitOaRecord("3", SPMS_SUBMIT_OA, "添加", spmsUser.getUserId(),
                    "com.sunda.spmsweb.oaservice.createRequest1201()", "", JSON.toJSONString(reqinfo), "WebService", doc.toJSONString(), spmsId);

            String reqid = "0";
            if(newOa){
                Map<String, Object> rl = new HashMap<String, Object>();
                rl.put("requestName", doc.getString("subject"));
                rl.put("workflowId", workflow1201);
                rl.put("requestLevel", doc.getString("urgency"));
                rl.put("remindtype", "0");
                rl.put("isNextFlow", "1");
                rl.put("description",doc.getString("subject"));

                List<Map<String, Object>> aas = new ArrayList<Map<String, Object>>();
                for (Map.Entry<String, Object> entry : map.entrySet()){
                    Map<String, Object> ol = new HashMap<String, Object>();
                    ol.put("fieldName", entry.getKey());
                    ol.put("fieldValue", entry.getValue().toString());
                    if (entry.getKey().equals("xiangguanfujian")){
                        List<Map<String, Object>> file = new ArrayList<Map<String, Object>>();
                        Map<String, Object> mapFIle = new HashMap<String, Object>();
                        mapFIle.put("filePath",entry.getValue().toString());
                        mapFIle.put("fileName","附件-备品备件请购单明细表.xlsx");
                        file.add(mapFIle);
                        ol.put("fieldValue", file);
                    }
                    aas.add(ol);
                }
                rl.put("mainData", JSONUtil.parseArray(aas).toString());
                String jsonParams = JSONUtil.parseObj(rl).toString();
                OAMainUtils oaMainUtils = new OAMainUtils();
                log.info("推送至OA的参数jsonParams()：" + jsonParams);
                String message =  oaMainUtils.oaRestFul(oaUrl, "/api/workflow/paService/doCreateRequest", rl,spmsUser.getUserId());
                log.info("OA返回的参数message：" + message);
                JSONObject messageDoc = JSONObject.parseObject(message);
                if("SUCCESS".equals(messageDoc.getString("code"))){
                    String data = messageDoc.getString("data");
                    JSONObject dataJson = JSONObject.parseObject(data);
                    reqid = dataJson.getString("requestid");
                }else{
                    throw new Exception("保存异常：" + messageDoc.getString("errMsg"));
                }
            }else{
                // 生成待办 ，返回待办id
                reqid = wfproxy.createRequest(reqinfo);
            }


            // 返回大于0 的数字则调用成功
            System.out.println("reqid ======== " + reqid);
            return Integer.parseInt(reqid);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
            return 0;
        }
    }

    public int createRequest3302(JSONObject doc, String spmsId, SpmsUser spmsUser, String workflow3302, String fileUrl, String oaUrl, boolean newOa) {
    	RequestServicePortTypeProxy wfproxy = new RequestServicePortTypeProxy();
        try {
            RequestInfo reqinfo = new RequestInfo();
            reqinfo.setCreatorid(spmsUser.getWorkId());
            /** OA workflow id 3302 : 668 测试；353 正式； */
            reqinfo.setWorkflowid(workflow3302);
            reqinfo.setRequestlevel(doc.getString("urgency"));
            reqinfo.setRemindtype("0");
            reqinfo.setIsNextFlow("1");
            reqinfo.setDescription(doc.getString("subject"));

            Map<String, Object> map = new HashMap<>();
            map.put("riqi", doc.getString("applicationDate"));
            map.put("shenqingren", spmsUser.getWorkId());
            map.put("bumen", spmsUser.getDeptId() == null  ? "" : spmsUser.getDeptId());
            map.put("zhiwu", spmsUser.getPositionId() == null  ? "" : spmsUser.getPositionId());
            map.put("gonghao", spmsUser.getUserId());
            map.put("bumen", spmsUser.getDeptId() == null  ? "" : spmsUser.getDeptId());
            // 申请类别：0一次采购；1年度采购
            map.put("shenqingleibie", doc.get("applicationType") == null ? 0 : (doc.getString("applicationType").length() == 0 ? 0 : Integer.parseInt(doc.getString("applicationType"))));
            // 物品类别 0：海低值易耗品；1：固定资产
            map.put("wupinleibie", doc.get("itemType") == null ? 0 : Integer.parseInt(doc.getString("itemType")));
            // 运输方式, 0海运；1空运；2人带
            //map.put("yunshufangshi", doc.get("shippingFangshi") == null ? 0 : Integer.parseInt(doc.getString("shippingFangshi")));
            // 是否IT物品 0:是；1：否
            map.put("shifouITwupin", doc.get("itItemOrNot") == null ? 0 : Integer.parseInt(doc.getString("itItemOrNot")));
            // 是否本地采购:0是，1否
            map.put("shifouBDCG", doc.get("purchaseLocation") == null ? 0 : Integer.parseInt(doc.getString("purchaseLocation")));
            // 预计总费用（人民币）
            map.put("yujizongfeiyong", doc.get("estimateCost") == null ? 0 : (doc.getString("estimateCost").length() == 0 ? 0 : Double.parseDouble(doc.getString("estimateCost"))));
            map.put("yujizongfeiyongspms", doc.get("estimateCost") == null ? 0 : (doc.getString("estimateCost").length() == 0 ? 0 : Double.parseDouble(doc.getString("estimateCost"))));
            // 要求到货日期
            //map.put("yqdhrq", doc.get("dateRequired") == null ? "" : doc.getString("dateRequired"));
            // 费用承担部门
            map.put("costdept", "");
            // 收货确认
            map.put("confirmation", "");
            // 地址/变量
            //map.put("spmsurl", "");
            // SPMS单据号
            map.put("spmsordernum", spmsId);
            // 申请原因
            map.put("shenqingyuanyin", doc.get("justification") == null ? "" : doc.getString("justification"));
            // 编号
            map.put("bianhao", "");
            // 请购单明细附件
            map.put("fj1", fileUrl == null ? "" : fileUrl);
            // 请购单审批附件
            map.put("fj2", doc.get("attachmentUrl") == null ? "" : doc.getString("attachmentUrl") );
            // 分公司
            map.put("fengongsi", spmsUser.getCompany() == null ? "" : spmsUser.getCompany());
            // 分点
            map.put("fendian", spmsUser.getBranchPoint() == null ? "" : spmsUser.getBranchPoint());
            // 分线
            map.put("fenxian", spmsUser.getBranchLine() == null ? "" : spmsUser.getBranchLine());
            MainTableInfo wmi = new MainTableInfo();
            Property[] wrti = new Property[map.size()];
            int i = 0;
            for (Map.Entry<String, Object> entry : map.entrySet()){
                wrti[i] = new Property();
                wrti[i].setName(entry.getKey());
                wrti[i].setValue(entry.getValue().toString());
                if (entry.getKey().equals("fj1")){
                    wrti[i].setType("http:" + "附件-劳保用品请购单明细表.xlsx");
                }
                if (entry.getKey().equals("fj2")){
                    wrti[i].setType(doc.get("attachmentName") == null ? "" : doc.getString("attachmentName"));
                }
                i ++;
            }
            wmi.setProperty(wrti);
            reqinfo.setMainTableInfo(wmi);
            /** 请求OA内容记录 */
            oaService.iSysLogService.addSubmitOaRecord("3", SPMS_SUBMIT_OA, "添加", spmsUser.getUserId(),
                    "com.sunda.spmsweb.oaservice.createRequest3302()", "", JSON.toJSONString(reqinfo), "WebService", doc.toJSONString(), spmsId);


            String reqid = "0";
            if(newOa){
                Map<String, Object> rl = new HashMap<String, Object>();
                rl.put("requestName", doc.getString("subject"));
                rl.put("workflowId", workflow3302);
                rl.put("requestLevel", doc.getString("urgency"));
                rl.put("remindtype", "0");
                rl.put("isNextFlow", "1");
                rl.put("description",doc.getString("subject"));

                List<Map<String, Object>> aas = new ArrayList<Map<String, Object>>();
                for (Map.Entry<String, Object> entry : map.entrySet()){
                    Map<String, Object> ol = new HashMap<String, Object>();
                    ol.put("fieldName", entry.getKey());
                    if (entry.getKey().equals("fj1")){
                        List<Map<String, Object>> file = new ArrayList<Map<String, Object>>();
                        Map<String, Object> mapFIle = new HashMap<String, Object>();
                        mapFIle.put("filePath",entry.getValue().toString());
                        mapFIle.put("fileName","附件-劳保用品请购单明细表.xlsx");
                        file.add(mapFIle);
                        ol.put("fieldValue", file);
                    }else  if (entry.getKey().equals("fj2")){
                        List<Map<String, Object>> file = new ArrayList<Map<String, Object>>();
                        String filePath = entry.getValue().toString();
                        String fileName = doc.get("attachmentName") == null ? "" : doc.getString("attachmentName");
                        String[] filePaths = filePath.split(",");
                        String[] fileNames = fileName.split(",");
                        for (int s = 0; s < filePaths.length; s ++){
                            Map<String, Object> mapFIle = new HashMap<String, Object>();
                            mapFIle.put("filePath",filePaths[s]);
                            mapFIle.put("fileName",fileNames[s]);
                            file.add(mapFIle);
                        }
                        ol.put("fieldValue", file);
                    }else{
                        ol.put("fieldValue", entry.getValue() == null ? "" : entry.getValue().toString());
                    }
                    aas.add(ol);
                }
                rl.put("mainData", JSONUtil.parseArray(aas).toString());
                String jsonParams = JSONUtil.parseObj(rl).toString();
                System.out.println(jsonParams.toString());
                OAMainUtils oaMainUtils = new OAMainUtils();
                log.info("推送至OA的参数jsonParams()：" + jsonParams);
                String message =  oaMainUtils.oaRestFul(oaUrl, "/api/workflow/paService/doCreateRequest", rl,spmsUser.getUserId());
                log.info("OA返回的参数message：" + message);
                JSONObject messageDoc = JSONObject.parseObject(message);
                if("SUCCESS".equals(messageDoc.getString("code"))){
                    String data = messageDoc.getString("data");
                    JSONObject dataJson = JSONObject.parseObject(data);
                    reqid = dataJson.getString("requestid");
                }else{
                    throw new Exception("保存异常：" + messageDoc.getString("errMsg"));
                }
            }else {
                // 生成待办 ，返回待办id
                reqid = wfproxy.createRequest(reqinfo);
            }
            // 返回大于0 的数字则调用成功
            System.out.println("reqid ======== " + reqid);
            return Integer.parseInt(reqid);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
            return 0;
        }
	}

    public int createRequest0705(JSONObject doc, String spmsId, SpmsUser spmsUser, String workflow0705, String workflow3602, String fileUrl, String oaUrl, boolean newOa,List<Map<String, Object>> orderItem) {
        RequestServicePortTypeProxy wfproxy = new RequestServicePortTypeProxy();
        try {
            RequestInfo reqinfo = new RequestInfo();
            reqinfo.setCreatorid(spmsUser.getWorkId());

            String oaProcessId = doc.getString("oaProcessId");
            if ("0705".equals(oaProcessId)){
                reqinfo.setWorkflowid(workflow0705);
            }else if ("3602".equals(oaProcessId)){
                reqinfo.setWorkflowid(workflow3602);
            }
            reqinfo.setRequestlevel(doc.getString("urgency"));
            reqinfo.setRemindtype("0");
            reqinfo.setIsNextFlow("1");
            reqinfo.setDescription(doc.getString("subject"));

            Map<String, Object> map = new HashMap<>();
            map.put("zd2", doc.getString("applicationDate"));//申请日期
            map.put("zd4", spmsUser.getWorkId());//申请人
            map.put("zd5", spmsUser.getDeptId() == null  ? "" : spmsUser.getDeptId());//部门
            map.put("zd6", spmsUser.getPositionId() == null  ? "" : spmsUser.getPositionId());//岗位
            map.put("zd3", spmsUser.getUserId());//工号
            if ("0705".equals(oaProcessId)){
                map.put("xqzt", doc.getString("prSubject"));//需求主体
            }
            map.put("wltype", doc.get("itemType") == null ? 0 : Integer.parseInt(doc.getString("itemType")));//物品类别
            map.put("gc", doc.get("werks") == null ? "" : doc.getString("werks"));//SPMS需求工厂
            map.put("spmsordernum", spmsId);//SPMS单据号
            //map.put("currency", "CNY");//币种
            for (int j = 0; j < orderItem.size(); j++) {
                Map<String, Object> itemDTO = orderItem.get(j);
                if(itemDTO.get("waers")!=null && itemDTO.get("waers").toString().length()>0){
                    map.put("currency", itemDTO.get("waers"));//币种
                    continue;
                }
            }
            map.put("yjfy", doc.get("estimateCost") == null ? "" : doc.getString("estimateCost"));//预计费用合计
            map.put("yjfyrbm", doc.get("estimateCost") == null ? "" : doc.getString("estimateCost"));//预计费用合计（RMB）
            //map.put("guojia", doc.get("country") == null ? "" : doc.getString("country"));//国家
            //map.put("cgy", "");//采购经理
            map.put("zd10", doc.get("justification") == null ? "" : doc.getString("justification"));//备注
            //map.put("zd11", doc.get("justification") == null ? "" : doc.getString("justification"));//工厂请购单抬头备注
            // 分公司
            map.put("zd6", spmsUser.getCompany() == null ? "" : spmsUser.getCompany());
            // 分点
            map.put("zd7", spmsUser.getBranchPoint() == null ? "" : spmsUser.getBranchPoint());
            // 分线
            map.put("zd8", spmsUser.getBranchLine() == null ? "" : spmsUser.getBranchLine());

            // 请购单明细附件
            //map.put("fj1", fileUrl == null ? "" : fileUrl);
            // 请购单审批附件
            if(doc.get("attachmentUrl") != null && doc.getString("attachmentUrl").length()>0){
                map.put("xgfj", doc.get("attachmentUrl") == null ? "" : doc.getString("attachmentUrl") );
            }
            /** 请求OA内容记录 */
            oaService.iSysLogService.addSubmitOaRecord("3", SPMS_SUBMIT_OA, "添加", spmsUser.getUserId(),
                    "com.sunda.spmsweb.oaservice.createRequest0705()", "", JSON.toJSONString(reqinfo), "WebService", doc.toJSONString(), spmsId);

            String reqid = "0";
            Map<String, Object> rl = new HashMap<String, Object>();
            rl.put("requestName", doc.getString("subject"));
            if ("0705".equals(oaProcessId)){
                rl.put("workflowId", workflow0705);
            }else if ("3602".equals(oaProcessId)){
                rl.put("workflowId", workflow3602);
            }
            rl.put("requestLevel", doc.getString("urgency"));
            rl.put("remindtype", "0");
            rl.put("isNextFlow", "1");
            rl.put("description",doc.getString("subject"));

            List<Map<String, Object>> aas = new ArrayList<Map<String, Object>>();
            for (Map.Entry<String, Object> entry : map.entrySet()){
                Map<String, Object> ol = new HashMap<String, Object>();
                ol.put("fieldName", entry.getKey());
                if (entry.getKey().equals("fj1")){
                    List<Map<String, Object>> file = new ArrayList<Map<String, Object>>();
                    Map<String, Object> mapFIle = new HashMap<String, Object>();
                    mapFIle.put("filePath",entry.getValue().toString());
                    mapFIle.put("fileName","附件-本地采购请购单明细表.xlsx");
                    file.add(mapFIle);
                    ol.put("fieldValue", file);
                }else  if (entry.getKey().equals("xgfj")){
                    List<Map<String, Object>> file = new ArrayList<Map<String, Object>>();
                    String filePath = entry.getValue().toString();
                    String fileName = doc.get("attachmentName") == null ? "" : doc.getString("attachmentName");
                    String[] filePaths = filePath.split(",");
                    String[] fileNames = fileName.split(",");
                    for (int s = 0; s < filePaths.length; s ++){
                        Map<String, Object> mapFIle = new HashMap<String, Object>();
                        mapFIle.put("filePath",filePaths[s]);
                        mapFIle.put("fileName",fileNames[s]);
                        file.add(mapFIle);
                    }
                    ol.put("fieldValue", file);
                }else{
                    ol.put("fieldValue", entry.getValue() == null ? "" : entry.getValue().toString());
                }
                aas.add(ol);
            }
            if ("0705".equals(oaProcessId)){
                rl.put("mainData", JSONUtil.parseArray(aas).toString());
            }else if ("3602".equals(oaProcessId)){
                rl.put("mainData", JSONUtil.parseArray(aas).toString());
            }

            List<Map<String, Object>> mapList = new ArrayList<>();
            for (int j = 0; j < orderItem.size(); j++) {
                Map<String, Object> itemDTO = orderItem.get(j);
                //double discrepancy = Double.parseDouble(itemDTO.get("discrepancy").toString());
                Map<String, Object> mapItem = new HashMap<>();
                mapItem.put("wpmc", itemDTO.get("materialZhDesc"));//物品名称
                //mapItem.put("wpms", itemDTO.get("materialZhDesc"));//规格型号
                mapItem.put("sl", itemDTO.get("approvalQty"));//数量
                mapItem.put("dw", itemDTO.get("basicUnit"));//单位
                if(itemDTO.get("materialPrice")!=null && itemDTO.get("approvalQty")!=null){
                    BigDecimal materialPrice = new BigDecimal(itemDTO.get("materialPrice").toString());
                    BigDecimal approvalQty = new BigDecimal(itemDTO.get("approvalQty").toString());;
                    BigDecimal materialTotalPrice = materialPrice.multiply(approvalQty);
                    mapItem.put("je", materialTotalPrice);//采购金额
                }else{
                    mapItem.put("je", itemDTO.get("materialTotalPrice"));//采购金额
                }
                mapItem.put("dj", itemDTO.get("materialPrice"));//采购单价
                mapItem.put("dhsj", doc.getString("dateRequired"));//到货时间
                mapItem.put("sybm", "");//使用部门
                mapItem.put("sqyy", itemDTO.get("rowComment"));//申请原因及用途
                mapItem.put("gys", "");//供应商
                mapItem.put("wlbm", itemDTO.get("materialNo"));//物料编码
                mapList.add(mapItem);
            }
            List<Map<String, Object>> aasDetailList = new ArrayList<>();
            Map<String, Object> aasDetail = new HashMap<>();
            List<Map<String, Object>> detailTableDb = new ArrayList<Map<String, Object>>();
            for (int k = 0; k < mapList.size(); k++) {
                Map<String, Object> item = mapList.get(k);
                Map<String, Object> workflowRequestTableRecord = new HashMap<>();
                workflowRequestTableRecord.put("recordOrder", 0);
                List<Map<String, Object>> detailTable = new ArrayList<Map<String, Object>>();
                for (Map.Entry<String, Object> entry : item.entrySet()) {
                    Map<String, Object> ol = new HashMap<String, Object>();
                    ol.put("fieldName", entry.getKey());
                    ol.put("fieldValue", entry.getValue() == null ? "" : entry.getValue().toString());
                    detailTable.add(ol);
                }
                workflowRequestTableRecord.put("workflowRequestTableFields", detailTable);
                detailTableDb.add(workflowRequestTableRecord);
            }
            //明细表
            aasDetail.put("workflowRequestTableRecords", detailTableDb);
            if ("0705".equals(oaProcessId)){
                if(oaUrl.contains("fm-oa") || oaUrl.contains("oa-ipo")){
                    aasDetail.put("tableDBName", "formtable_main_703_dt1");
                }else{
                    //集团生产环境是formtable_main_478_dt1
                    //测试环境是formtable_main_479_dt1
                    aasDetail.put("tableDBName", "formtable_main_478_dt1");
                }
            }else if ("3602".equals(oaProcessId)){
                //集团生产环境是formtable_main_479_dt1
                //测试环境是formtable_main_480_dt1
                aasDetail.put("tableDBName", "formtable_main_480_dt1");
            }
            aasDetailList.add(aasDetail);
            rl.put("detailData", JSONUtil.parseArray(aasDetailList).toString());

            String jsonParams = JSONUtil.parseObj(rl).toString();
            System.out.println(jsonParams.toString());
            OAMainUtils oaMainUtils = new OAMainUtils();
            log.info("推送至OA的参数jsonParams()：" + jsonParams);
            String message =  oaMainUtils.oaRestFul(oaUrl, "/api/workflow/paService/doCreateRequest", rl,spmsUser.getUserId());
            log.info("OA返回的参数message：" + message);
            JSONObject messageDoc = JSONObject.parseObject(message);
            if("SUCCESS".equals(messageDoc.getString("code"))){
                String data = messageDoc.getString("data");
                JSONObject dataJson = JSONObject.parseObject(data);
                reqid = dataJson.getString("requestid");
            }else{
                throw new Exception("保存异常：" + messageDoc.getString("errMsg"));
            }
            // 返回大于0 的数字则调用成功
            System.out.println("reqid ======== " + reqid);
            return Integer.parseInt(reqid);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
            return 0;
        }
    }


    public int createRequest3601(JSONObject doc, String spmsId, SpmsUser spmsUser, String workflow3601, String fileUrl, String oaUrl, boolean newOa){
        RequestServicePortTypeProxy wfproxy = new RequestServicePortTypeProxy();
        try {
            RequestInfo reqinfo = new RequestInfo();
            reqinfo.setCreatorid(spmsUser.getWorkId());
            /** OA workflow id 3601 : 592 测试；353 正式； */
            reqinfo.setWorkflowid(workflow3601);
            reqinfo.setRequestlevel(doc.getString("urgency"));
            reqinfo.setRemindtype("0");
            reqinfo.setIsNextFlow("1");
            reqinfo.setDescription(doc.getString("subject"));

            Map<String, Object> map = new HashMap<>();
            map.put("riqi", doc.getString("applicationDate"));
            map.put("shenqingren", spmsUser.getWorkId());
            map.put("bumen", spmsUser.getDeptId() == null  ? "" : spmsUser.getDeptId());
            map.put("zhiwu", spmsUser.getPositionId() == null  ? "" : spmsUser.getPositionId());
            map.put("gonghao", spmsUser.getUserId());
            map.put("xmzt", doc.get("projectStatus") == null ? 0 : (doc.getString("projectStatus").length() == 0 ? 0 : Integer.parseInt(doc.getString("projectStatus"))));
            /**
             * 3601 流程提交OA，取值 项目类别 给 xmlx ————20210525 修改
             * map.put("xmlx", doc.get("projectType") == null ? 0 : (doc.getString("projectType").length() == 0 ? 0 : Integer.parseInt(doc.getString("projectType"))));
             */
            //map.put("xmlx", doc.get("projectCategory") == null ? 0 : (doc.getString("projectCategory").length() == 0 ? 0 : Integer.parseInt(doc.getString("projectCategory"))));
            map.put("xmlx", doc.get("projectCategory") == null ? "" : doc.getString("projectCategory"));
            map.put("yunshu", doc.get("shippingFangshi") == null ? 0 : (doc.getString("shippingFangshi").length() == 0 ? 0 : Integer.parseInt(doc.getString("shippingFangshi"))));
            map.put("sqlb", doc.get("applicationType") == null ? 0 : (doc.getString("applicationType").length() == 0 ? 0 : Integer.parseInt(doc.getString("applicationType"))));
            //设备/物料类别——3备品备件；4行政物资；5工厂设备；6筹建物资。默认值为 3 备品备件。
            map.put("wllb", doc.get("deviceCategory") == null ? 3 : (doc.getString("deviceCategory").length() == 0 ? 0 : Integer.parseInt(doc.getString("deviceCategory"))));
            //map.put("xmh", doc.get("projectCode") == null ? "" : doc.getString("projectCode"));
            map.put("cgdd", doc.get("purchaseLocation") == null ? 0 : Integer.parseInt(doc.getString("purchaseLocation")));
            map.put("hjjeRMB", doc.get("estimateCost") == null ? 0 : (doc.getString("estimateCost").length() == 0 ? 0 : Double.parseDouble(doc.getString("estimateCost"))));
            map.put("yqdhrq", doc.get("dateRequired") == null ? "" : doc.getString("dateRequired"));
            map.put("fydep", 0);
            //map.put("spmsurl", "");
            map.put("spmsordernum", spmsId);
            map.put("facdept", 0);
            map.put("beizhu", "");
            map.put("xiangguanliucheng", "");
            map.put("bianhao", "");
            //map.put("fujian", "");
            //map.put("fengongsi", spmsUser.getSubcompanyId() == null ? "" : spmsUser.getSubcompanyId());
            /** 分公司字段取值修改 20210804 */
            map.put("fengongsi", spmsUser.getCompany() == null ? "" : spmsUser.getCompany());
            map.put("fendian", spmsUser.getBranchPoint() == null ? "" : spmsUser.getBranchPoint());
            map.put("fenxian", spmsUser.getBranchLine() == null ? "" : spmsUser.getBranchLine());
            map.put("fujian", fileUrl == null ? "" : fileUrl);

            MainTableInfo wmi = new MainTableInfo();
            Property[] wrti = new Property[map.size()];
            int i = 0;
            for (Map.Entry<String, Object> entry : map.entrySet()){
                wrti[i] = new Property();
                wrti[i].setName(entry.getKey());
                wrti[i].setValue(entry.getValue().toString());
                if (entry.getKey().equals("fujian")){
                    wrti[i].setType("http:" + "附件-备品备件请购单明细表.xlsx");
                }
                i ++;
            }
            wmi.setProperty(wrti);
            reqinfo.setMainTableInfo(wmi);
            /** 请求OA内容记录 */
            oaService.iSysLogService.addSubmitOaRecord("3", SPMS_SUBMIT_OA, "添加", spmsUser.getUserId(),
                    "com.sunda.spmsweb.oaservice.createRequest3601()", "", JSON.toJSONString(reqinfo), "WebService", doc.toJSONString(), spmsId);

            String reqid = "0";
            if(newOa){
                Map<String, Object> rl = new HashMap<String, Object>();
                rl.put("requestName", doc.getString("subject"));
                rl.put("workflowId", workflow3601);
                rl.put("requestLevel", doc.getString("urgency"));
                rl.put("remindtype", "0");
                rl.put("isNextFlow", "1");
                rl.put("description",doc.getString("subject"));

                List<Map<String, Object>> aas = new ArrayList<Map<String, Object>>();
                for (Map.Entry<String, Object> entry : map.entrySet()){
                    Map<String, Object> ol = new HashMap<String, Object>();
                    ol.put("fieldName", entry.getKey());
                    ol.put("fieldValue", entry.getValue().toString());
                    if (entry.getKey().equals("fujian")){
                        List<Map<String, Object>> file = new ArrayList<Map<String, Object>>();
                        Map<String, Object> mapFIle = new HashMap<String, Object>();
                        mapFIle.put("filePath",entry.getValue().toString());
                        mapFIle.put("fileName","附件-备品备件请购单明细表.xlsx");
                        file.add(mapFIle);
                        ol.put("fieldValue", file);
                    }
                    aas.add(ol);
                }
                rl.put("mainData", JSONUtil.parseArray(aas).toString());
                String jsonParams = JSONUtil.parseObj(rl).toString();
                OAMainUtils oaMainUtils = new OAMainUtils();
                log.info("推送至OA的参数jsonParams()：" + jsonParams);
                String message =  oaMainUtils.oaRestFul(oaUrl, "/api/workflow/paService/doCreateRequest", rl,spmsUser.getUserId());
                log.info("OA返回的参数message：" + message);
                JSONObject messageDoc = JSONObject.parseObject(message);
                if("SUCCESS".equals(messageDoc.getString("code"))){
                    String data = messageDoc.getString("data");
                    JSONObject dataJson = JSONObject.parseObject(data);
                    reqid = dataJson.getString("requestid");
                }else{
                    throw new Exception("保存异常：" + messageDoc.getString("errMsg"));
                }
            }else{
                // 生成待办 ，返回待办id
                reqid = wfproxy.createRequest(reqinfo);
            }
            // 返回大于0 的数字则调用成功
            System.out.println("reqid ======== " + reqid);
            return Integer.parseInt(reqid);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
            return 0;
        }
    }

    /**
     * 创建物料申请流程
     * @param doc
     * @param fileUrl
     * @param spmsUser
     * @return
     */
    public int createRequest0915(JSONObject doc, String fileName, String fileUrl, SpmsUser spmsUser, String workflow0915, String oaUrl, boolean newOa){
        RequestServicePortTypeProxy wfproxy = new RequestServicePortTypeProxy();
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyy-MM-dd");  //日期格式化

            RequestInfo reqinfo = new RequestInfo();
            reqinfo.setCreatorid(spmsUser.getWorkId());
            /** OA workflow id 0915 : 520 正式； */
            reqinfo.setWorkflowid(workflow0915);
            reqinfo.setRequestlevel("0");
            reqinfo.setRemindtype("0");
            reqinfo.setIsNextFlow("1");
            reqinfo.setDescription("0915 SAP新增物料申请单-" + spmsUser.getLastName() + "-" + simpleDateFormat.format(System.currentTimeMillis()) + "-" + doc.getString("applicationId"));

            Map<String, Object> map = new HashMap<>();
            map.put("workflowdate", simpleDateFormat.format(System.currentTimeMillis()));
            map.put("requestuserid", spmsUser.getWorkId() == null ? "" : spmsUser.getWorkId());
            map.put("dep", spmsUser.getDeptId() == null  ? "" : spmsUser.getDeptId());
            map.put("jobtitle", spmsUser.getPositionId() == null  ? "" : spmsUser.getPositionId());
            map.put("workcode", spmsUser.getUserId() == null ? "" : spmsUser.getUserId());
            map.put("remarks", "");
            map.put("bianhao", "");
            map.put("sub", spmsUser.getBranchLine() == null ? "" : spmsUser.getBranchLine());
            map.put("fendian", spmsUser.getBranchPoint() == null ? "" : spmsUser.getBranchPoint());
            map.put("fenxian", spmsUser.getCompany() == null ? "" : spmsUser.getCompany());
            //map.put("cgwl", "0");
            map.put("zb100", "1000");//李桥廷(Qiaoting Li)
            map.put("wlsx", "0");
            map.put("sfbdcg", "4");
            map.put("productline", "3");
            map.put("spmsordernum", doc.getString("applicationId") == null ? "" : doc.getString("applicationId"));
            map.put("workfile", fileUrl == null ? "" : fileUrl);
            map.put("cpx", doc.getString("cpx") == null ? "" : doc.getString("cpx"));
            map.put("cgdd", doc.getString("purchaseLocation") == null ? "" : doc.getString("purchaseLocation"));//采购地点
            map.put("gc", doc.getString("werks") == null ? "" : doc.getString("werks"));//工厂

            MainTableInfo wmi = new MainTableInfo();
            Property[] wrti = new Property[map.size()];
            int i = 0;
            for (Map.Entry<String, Object> entry : map.entrySet()){
                wrti[i] = new Property();
                wrti[i].setName(entry.getKey());
                wrti[i].setValue(entry.getValue().toString());
                if (entry.getKey().equals("workfile")){
                    wrti[i].setType("http:" + "附件10-备品备件SAP物料申请表.xlsx");
                }
                i++;
            }
            wmi.setProperty(wrti);
            reqinfo.setMainTableInfo(wmi);
            /** 请求OA内容记录 */
            oaService.iSysLogService.addSubmitOaRecord("3", MATERIAL_APPLICATION_INIT, "添加", spmsUser.getUserId(),
                    "com.sunda.spmsweb.oaservice.createRequest0915()", "", JSON.toJSONString(reqinfo), "WebService",
                    doc.toJSONString(), doc.getString("applicationUuid"));

            String reqid = "0";
            if(newOa){
                Map<String, Object> rl = new HashMap<String, Object>();
                rl.put("requestName", "0915 SAP新增物料申请单-" + spmsUser.getLastName() + "-" + simpleDateFormat.format(System.currentTimeMillis()) + "-" + doc.getString("applicationId"));
                rl.put("workflowId", workflow0915);
                rl.put("requestLevel", "0");
                rl.put("remindtype", "0");
                rl.put("isNextFlow", "0");
                rl.put("description","0915 SAP新增物料申请单-" + spmsUser.getLastName() + "-" + simpleDateFormat.format(System.currentTimeMillis()) + "-" + doc.getString("applicationId"));

                List<Map<String, Object>> aas = new ArrayList<Map<String, Object>>();
                for (Map.Entry<String, Object> entry : map.entrySet()){
                    Map<String, Object> ol = new HashMap<String, Object>();
                    ol.put("fieldName", entry.getKey());
                    ol.put("fieldValue", entry.getValue().toString());
                    if (entry.getKey().equals("workfile")){
                        List<Map<String, Object>> file = new ArrayList<Map<String, Object>>();
                        Map<String, Object> mapFIle = new HashMap<String, Object>();
                        mapFIle.put("filePath",entry.getValue().toString());
                        mapFIle.put("fileName","http:" + "附件10-备品备件SAP物料申请表.xlsx");
                        file.add(mapFIle);
                        ol.put("fieldValue", file);
                    }
                    aas.add(ol);
                }
                rl.put("mainData", JSONUtil.parseArray(aas).toString());
                String jsonParams = JSONUtil.parseObj(rl).toString();
                OAMainUtils oaMainUtils = new OAMainUtils();
                log.info("推送至OA的参数jsonParams()：" + jsonParams);
                String message =  oaMainUtils.oaRestFul(oaUrl, "/api/workflow/paService/doCreateRequest", rl,spmsUser.getUserId());
                log.info("OA返回的参数message：" + message);
                JSONObject messageDoc = JSONObject.parseObject(message);
                if("SUCCESS".equals(messageDoc.getString("code"))){
                    String data = messageDoc.getString("data");
                    JSONObject dataJson = JSONObject.parseObject(data);
                    reqid = dataJson.getString("requestid");
                }else{
                    throw new Exception("保存异常：" + messageDoc.getString("errMsg"));
                }
            }else{
                // 生成待办 ，返回待办id
                reqid = wfproxy.createRequest(reqinfo);
            }

            // 返回大于0 的数字则调用成功
            System.out.println("reqid ======== " + reqid);
            return Integer.parseInt(reqid);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
            return 0;
        }
    }

    public List<Map<String, Object>> getOALog(String requestId){
        WorkflowDataPortTypeProxy proxy = new WorkflowDataPortTypeProxy();
        try {
            com.sunda.business.soa.hr.po.WorkflowLogs[] hhLogs = proxy.getWorkflowLogsByReqid(requestId);
            List<Map<String, Object>> mapList = new ArrayList<>();
            int i = 1;
            for(com.sunda.business.soa.hr.po.WorkflowLogs hh : hhLogs) {

                Map<String, Object> map = new HashMap<>();
                map.put("requestId", hh.getRequestid());
                map.put("opter", hh.getOpter());
                map.put("nodeName", hh.getNodename());
                //map.put("nodeName", i + "." + hh.getNodename().split("、")[1].trim());
                map.put("operateTime", hh.getOperatetime());
                map.put("optStatus", hh.getOptstatus());
                map.put("receiveTime", hh.getReceivetime());
                mapList.add(map);
                i += 1;
            }
            return mapList;
        } catch (RemoteException e) {
            e.printStackTrace();
            return null;
        }
    }

    public List<Map<String, Object>> getOALogV2(String requestId,String oaUrl,String userId){
        try {
            List<Map<String, Object>> mapList = new ArrayList<>();
            OAMainUtils oaMainUtils = new OAMainUtils();
            String message =  oaMainUtils.getOaProssLog(oaUrl, "/api/workflow/paService/getWorkflowRequest?requestId="+requestId, userId);
            JSONObject messageDoc = JSONObject.parseObject(message);
            if("SUCCESS".equals(messageDoc.getString("code"))){
                String data = messageDoc.getString("data");
                JSONObject dataJson = JSONObject.parseObject(data);
                JSONArray workflowRequestLogs = dataJson.getJSONArray("workflowRequestLogs");
                for (int i = 0; i < workflowRequestLogs.size(); i++) {
                    Map<String, Object> map = new HashMap<>();
                    Object obj = workflowRequestLogs.get(i);
                    Map<String, Object> m = JSONObject.parseObject(JSON.toJSONString(obj));
                    map.put("requestId", m.get("id"));
                    map.put("opter", m.get("operatorName"));
                    map.put("nodeName", m.get("nodeName"));
                    map.put("operateTime", m.get("operateDate")+" "+m.get("operateTime"));
                    map.put("optStatus", m.get("operateType"));
                    //map.put("receiveTime", m.get(""));
                    mapList.add(map);
                }
            }

            return mapList;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}
