package psdi.app.iface.oa;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import psdi.app.iface.comm.UrlConstants;
import psdi.mbo.MboRemote;
import psdi.mbo.MboSetRemote;
import psdi.util.MXException;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * eam推送委外服务申请信息到oa
 */
public class EAM2OAOutSerHandler {
     //委外服务申请信息
    public JSONObject Z_EAM_OUTSER_REQUISITION(MboRemote mbo) throws IOException, MXException {
        JSONObject doCreReqJso=null;
        try {
            String requestedby=mbo.getString("CREATEBY");
            String orgid=mbo.getString("ORGID");
            String eamcgjl=mbo.getString("CGJL");
            int udoutserid=mbo.getInt("UDOUTSERID");
            SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd");
            String issuedate=sf.format(mbo.getDate("CREATEDATE"));
            String plandate=sf.format(mbo.getDate("PLANDATE"));
            //获取人员信息
            Map heads = new HashMap();
            String token=EamToOaWorkflowUtils.getToken(orgid);
            String userid=EamToOaWorkflowUtils.getUserid("1");//首次调用获取人员接口,id传1
            String appid=UrlConstants.appid;
            heads.put("appid", appid);
            heads.put("token", token);
            heads.put("userid",userid);
            heads.put("workcode",requestedby);
            JSONObject alldata = formatDataPerson(heads,orgid);
            JSONObject result = HttpUtilOa.post(UrlConstants.restEsbUrl, alldata);
            JSONObject RESPONSE = (JSONObject) result.get("RESPONSE");

            //采购经理
            Map cgjlheads = new HashMap();
            cgjlheads.put("appid", appid);
            cgjlheads.put("token", token);
            cgjlheads.put("userid",userid);
            cgjlheads.put("workcode",eamcgjl);
            JSONObject cgjlalldata = formatDataPerson(cgjlheads,orgid);
            JSONObject cgjlresult = HttpUtilOa.post(UrlConstants.restEsbUrl, cgjlalldata);
            JSONObject cgjlRESPONSE = (JSONObject) cgjlresult.get("RESPONSE");

            if(null!=RESPONSE && null!=cgjlRESPONSE){
                JSONObject RETURN_DATA = (JSONObject) RESPONSE.get("RETURN_DATA");
                JSONObject cgjlRETURN_DATA = (JSONObject) cgjlRESPONSE.get("RETURN_DATA");
                if(null!=RETURN_DATA && null!=cgjlRETURN_DATA){
                    String code=RETURN_DATA.getString("msgcode");
                    String cgjlcode=cgjlRETURN_DATA.getString("msgcode");
                    if("1".equalsIgnoreCase(code) && "1".equalsIgnoreCase(cgjlcode)){
                        String data2=RETURN_DATA.getString("data");
                        String cgjldata2=cgjlRETURN_DATA.getString("data");
                        JSONObject jsonObject2 = JSONObject.parseObject(data2);
                        JSONObject cgjljsonObject2 = JSONObject.parseObject(cgjldata2);
                        String user_id=jsonObject2.getString("id");
                        String cgjluser_id=cgjljsonObject2.getString("id");

                        String departmentid=jsonObject2.getString("departmentid");
                        String jobtitleid=jsonObject2.getString("jobtitleid");
                        String company=jsonObject2.getString("company");
                        String point=jsonObject2.getString("point");
                        String line=jsonObject2.getString("line");

                        //调用OA创建流程接口
                        Map<String, String> heads2 = new HashMap<String, String>();
                        Map<String, String> mainMap=new HashMap<String, String>();
                        String userid2=EamToOaWorkflowUtils.getUserid(user_id);//传入当前登录人在OA人员信息接口中的id
                        String str1="[{\"fieldName\":\"bh\",\"fieldValue\":\"\"}," +
                                "{\"fieldName\":\"eamdjh\",\"fieldValue\":\""+udoutserid+"\"}," +
                                "{\"fieldName\":\"gh\",\"fieldValue\":\""+requestedby+"\"}," +
                                "{\"fieldName\":\"rq\",\"fieldValue\":\""+issuedate+"\"}," +
                                "{\"fieldName\":\"sqr\",\"fieldValue\":\""+user_id+"\"}," +
                                "{\"fieldName\":\"bm\",\"fieldValue\":\""+departmentid+"\"}," +
                                "{\"fieldName\":\"gw\",\"fieldValue\":\""+jobtitleid+"\"}," +
                                "{\"fieldName\":\"fgs\",\"fieldValue\":\""+company+"\"}," +
                                "{\"fieldName\":\"fd\",\"fieldValue\":\""+point+"\"}," +
                                "{\"fieldName\":\"fx\",\"fieldValue\":\""+line+"\"}," +
                                "{\"fieldName\":\"sfyjlx\",\"fieldValue\":\""+mbo.getString("ISLX")+"\"}," +
                                "{\"fieldName\": \"cgjl\",\"fieldValue\": \""+cgjluser_id+"\"}," +
                                "{\"fieldName\": \"bz\",\"fieldValue\": \""+mbo.getString("COIN")+"\"}," +
                                "{\"fieldName\": \"hl\",\"fieldValue\": \""+mbo.getString("COIN.RATE")+"\"}," +
                                "{\"fieldName\": \"fyhjbb\",\"fieldValue\": \""+mbo.getDouble("FYHJBB")+"\"}," +
                                "{\"fieldName\": \"cgdd\",\"fieldValue\": \""+mbo.getString("CGDD")+"\"}," +
                                "{\"fieldName\": \"fyhjjermb\",\"fieldValue\": \""+mbo.getDouble("FYHJJERMB")+"\"}," +
                                "{\"fieldName\": \"bzsm\",\"fieldValue\": \""+mbo.getString("REMARK")+"\"}";
                        if("0".equalsIgnoreCase(mbo.getString("ISLX"))){//是否立项等于是传递这三个字段，是否立项,等于否，则不需要传递
                            //传递域值        0：是  1：否
                            str1+=",{\"fieldName\": \"xmmc\",\"fieldValue\": \"\"}," +
                                    "{\"fieldName\":\"xmbm\",\"fieldValue\": \""+mbo.getString("PROJECTNUM")+"\"}," +
                                    "{\"fieldName\":\"xmszdbm\",\"fieldValue\": \"\"}]";
                        }else{
                            str1+="]";
                        }
                        if("FMCG".equalsIgnoreCase(orgid)){
                            //IPO
                            mainMap.put("workflowId",UrlConstants.wwfwlcid_ipo);
                        }else{
                            //非IPO
                            mainMap.put("workflowId",UrlConstants.wwfwlcid);
                        }
                        JSONArray jsonArray = JSONArray.parseArray(str1);
                        mainMap.put("mainData", jsonArray.toString());

                        MboSetRemote lineSet=mbo.getMboSet("FZ");
                        if(null!=lineSet && !lineSet.isEmpty()){
                            JSONArray workflowRequestTableRecords = new JSONArray();
                            for(int i=0;i<lineSet.count();i++){
                                MboRemote lineMbo=lineSet.getMbo(i);
                                JSONArray innerArray = new JSONArray();
                                JSONObject innerObject1 = new JSONObject();
                                innerObject1.put("fieldName", "fycbzx");
                                innerObject1.put("fieldValue", mbo.getString("COSTCENTER"));
                                innerArray.add(innerObject1);

                                //传递域值        0：是  1：否
                                if("0".equalsIgnoreCase(mbo.getString("ISLX"))) {//是否立项等于是传递这三个字段，是否立项,等于否，则不需要传递
                                    JSONObject innerObject2 = new JSONObject();
                                    innerObject2.put("fieldName", "nbdd");
                                    innerObject2.put("fieldValue", mbo.getString("NBDD"));
                                    innerArray.add(innerObject2);
                                }

                                JSONObject innerObject3 = new JSONObject();
                                innerObject3.put("fieldName", "cgms");
                                innerObject3.put("fieldValue", lineMbo.getString("DESCRIPTION"));
                                innerArray.add(innerObject3);

                                JSONObject innerObject4 = new JSONObject();
                                innerObject4.put("fieldName", "xqgc");
                                innerObject4.put("fieldValue", mbo.getString("SITEID"));
                                innerArray.add(innerObject4);

                                JSONObject innerObject5 = new JSONObject();
                                innerObject5.put("fieldName", "wlz");
                                innerObject5.put("fieldValue", mbo.getString("WLZ"));
                                innerArray.add(innerObject5);

                                JSONObject innerObject6 = new JSONObject();
                                innerObject6.put("fieldName", "sl");
                                innerObject6.put("fieldValue", lineMbo.getDouble("SL"));
                                innerArray.add(innerObject6);

                                JSONObject innerObject7 = new JSONObject();
                                innerObject7.put("fieldName", "dw");
                                innerObject7.put("fieldValue", lineMbo.getString("DW"));
                                innerArray.add(innerObject7);

                                JSONObject innerObject8 = new JSONObject();
                                innerObject8.put("fieldName", "ygzje");
                                innerObject8.put("fieldValue", lineMbo.getDouble("YGZJE"));
                                innerArray.add(innerObject8);

                                JSONObject innerObject9 = new JSONObject();
                                innerObject9.put("fieldName", "jhwcrq");
                                innerObject9.put("fieldValue", plandate);
                                innerArray.add(innerObject9);

//                                JSONObject innerObject10 = new JSONObject();
//                                innerObject10.put("fieldName", "fycbzx");
//                                innerObject10.put("fieldValue", mbo.getString("COSTCENTER"));
//                                innerArray.add(innerObject10);

                                JSONObject workflowRequestTableFields1 = new JSONObject();
                                workflowRequestTableFields1.put("workflowRequestTableFields", innerArray);
                                workflowRequestTableFields1.put("recordOrder", 0);

                                workflowRequestTableRecords.add(workflowRequestTableFields1);
                            }
                            JSONObject jsonObject = new JSONObject();
                            if("FMCG".equalsIgnoreCase(orgid)){
                                jsonObject.put("tableDBName", "formtable_main_563_dt1");
                            }else{
                                jsonObject.put("tableDBName", "formtable_main_394_dt1");
                            }

                            jsonObject.put("workflowRequestTableRecords", workflowRequestTableRecords);
                            JSONObject detailData = new JSONObject();
                            JSONArray lineJson= new JSONArray();
                            lineJson.add(jsonObject);
                            detailData.put("detailData",lineJson);
                            mainMap.put("detailData",detailData.get("detailData").toString());
                        }

                        mainMap.put("remark",mbo.getString("REMARK"));
                        mainMap.put("requestLevel",mbo.getString("URGENCY"));
                        mainMap.put("requestName",mbo.getString("DESCRIPTION"));
                        int pcount=mbo.getInt("PCOUNT");
                        if(pcount<=0){
                            mainMap.put("otherParams","{\"eam0729count\":\""+(1+0)+"\"}");
                        }else{
                            mainMap.put("otherParams","{\"eam0729count\":\""+(1+pcount)+"\"}");
                        }
                        heads2.put("appid", appid);
                        heads2.put("token", token);
                        heads2.put("userid",userid2);

                        JSONObject alldata2 = formatDataEsb(heads2,mainMap,orgid);
                        JSONObject result2 = HttpUtilOa.post(UrlConstants.restEsbUrl, alldata2);
                        if(alldata2.toString().getBytes(StandardCharsets.UTF_8).length<=4000){
                            mbo.setValue("OAREQUEST", UrlConstants.restEsbUrl+alldata2.toString(), 2L);
                        }else{
                            mbo.setValue("OAREQUEST", (UrlConstants.restEsbUrl+alldata2.toString()).substring(0,1333), 2L);
                        }
                        return result2;
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            e.getCause();
            e.getMessage();
            return null;
        }
        return doCreReqJso;
    }

    /**
     * 对数据进行格式化
     */
    public JSONObject formatDataEsb(Map<String, String> headMap,Map<String, String> mainMap,String orgid) {
        JSONObject ALLDATA = new JSONObject();
        JSONObject REQUEST = new JSONObject();
        JSONObject ESB_ATTRS = new JSONObject();//ESB报文
        JSONObject REQUEST_DATA = new JSONObject();
        JSONObject Main_DATA = new JSONObject();//主表数据
        JSONArray LINE_DATA = new JSONArray();//子表数据
        JSONObject HEAD = new JSONObject();//包含主、子表数据
        //esb接口平台报文
        ESB_ATTRS.put("App_ID", "EAM"); //源系统
        if("FMCG".equalsIgnoreCase(orgid)){
            ESB_ATTRS.put("Target_ID", "OA-IPO"); //目标系统
        }else{
            ESB_ATTRS.put("Target_ID", "OA"); //目标系统
        }
        ESB_ATTRS.put("Application_ID", "00020000000002"); //固定值
        ESB_ATTRS.put("Transaction_ID", UUID.randomUUID().toString()); //交易id随机生成
        LINE_DATA.add(Main_DATA);
        HEAD.put("appid",headMap.get("appid"));
        HEAD.put("token",headMap.get("token"));
        HEAD.put("userid",headMap.get("userid"));
        REQUEST_DATA.put("SendHead",HEAD);
        REQUEST_DATA.put("SendData",mainMap);
        REQUEST_DATA.put("SendURL",new java.lang.Object());
        REQUEST_DATA.put("Operation", "Z_OA_FLOW_CREATE_REQUEST");
        REQUEST_DATA.put("Type", "Z_OA_FLOW_CREATE_REQUEST");
        REQUEST.put("ESB_ATTRS", ESB_ATTRS);
        REQUEST.put("REQUEST_DATA", REQUEST_DATA);
        ALLDATA.put("REQUEST", REQUEST);
        return ALLDATA;
    }

    /**
     * 发送REST请求到ESB，先进行数据格式化 人员信息
     * @param headMap
     * @return
     */
    public JSONObject formatDataPerson(Map<String, Object> headMap,String orgid) {
        JSONObject ALLDATA = new JSONObject();
        JSONObject REQUEST = new JSONObject();
        JSONObject ESB_ATTRS = new JSONObject();//ESB报文
        JSONObject REQUEST_DATA = new JSONObject();
        JSONObject Main_DATA = new JSONObject();//主表数据
        JSONArray LINE_DATA = new JSONArray();//子表数据
        JSONObject HEAD = new JSONObject();//包含主、子表数据
        JSONObject workcode = new JSONObject();//包含主、子表数据
        //esb接口平台报文
        ESB_ATTRS.put("App_ID", "EAM"); //源系统
        if("FMCG".equalsIgnoreCase(orgid)){
            ESB_ATTRS.put("Target_ID", "OA-IPO"); //目标系统
        }else{
            ESB_ATTRS.put("Target_ID", "OA"); //目标系统
        }
        ESB_ATTRS.put("Application_ID", "00020000000002"); //固定值
        ESB_ATTRS.put("Transaction_ID", UUID.randomUUID().toString()); //交易id随机生成
        LINE_DATA.add(Main_DATA);
        HEAD.put("appid",headMap.get("appid"));
        HEAD.put("token",headMap.get("token"));
        HEAD.put("userid",headMap.get("userid"));
        workcode.put("workcode", headMap.get("workcode"));
        REQUEST_DATA.put("SendHead",HEAD);
        REQUEST_DATA.put("SendData",new Object());
        REQUEST_DATA.put("SendURL",workcode);
        REQUEST_DATA.put("Operation", "Z_OA_GET_USER_INFO_BY_WORKCODE");
        REQUEST_DATA.put("Type", "Z_OA_GET_USER_INFO_BY_WORKCODE");
        REQUEST.put("ESB_ATTRS", ESB_ATTRS);
        REQUEST.put("REQUEST_DATA", REQUEST_DATA);
        ALLDATA.put("REQUEST", REQUEST);
        return ALLDATA;
    }
}
