package com.engine.tjyh.xc.cmd;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.engine.common.biz.AbstractCommonCommand;
import com.engine.common.entity.BizLogContext;
import com.engine.core.interceptor.CommandContext;
import com.engine.tjyh.xc.util.WorkflowCreateHandler;
import okhttp3.*;
import org.apache.commons.codec.digest.DigestUtils;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.TimeUtil;
import weaver.general.Util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;

/**
 * @Description
 * @Author matrix
 * @Date 2023/6/15 10:09
 **/
public class XcCmd2 extends AbstractCommonCommand<Map<String, Object>> {

    public XcCmd2(JSONObject params) {
        this.params = params;
    }

    @Override
    public BizLogContext getLogContext() {
        return null;
    }

    @Override
    public Map<String, Object> execute(CommandContext commandContext) {
        RecordSet rs = new RecordSet();
        BaseBean bb = new BaseBean();
        Map<String, Object> apimap = new HashMap<String, Object>();
        writeLog("XcCmd--------:"+params);
        String appKey = bb.getPropValue("tjyhxcjc","appKey");
        String appSecurity = bb.getPropValue("tjyhxcjc","appSecurity");
        String url = bb.getPropValue("tjyhxcjc","url");
        String orderurl = bb.getPropValue("tjyhxcjc","orderurl");
        String workflowId = bb.getPropValue("tjyhxcjc","workflowId");
        Map map= new HashMap<>();
        map.put("appKey",appKey);
        map.put("appSecurity",appSecurity);
        String input = JSON.toJSONString(map);
//        String back =" postData(input,url)";
//        JSONObject backObj = JSONObject.parseObject(back);
//        String ticket = backObj.getString("Ticket");
//        bb.writeLog("ticket="+ticket);
//
//        JSONObject obj = (JSONObject) params;
//        String approveScenario = obj.getString("approveScenario");
//        String corpId = obj.getString("corpId");
//        String orderId = obj.getString("orderId");
//        String orderStatus = obj.getString("orderStatus");
//        String productType = obj.getString("productType");
//        String sign = obj.getString("sign");

         String tgq="2"; //1 改签 2:退
//        if("FlightInternational".equals(productType)||"FlightDomestic".equals(productType)){
//            //机票 ，改签成功
//            if("rebookSuccess".equals(orderStatus)){
//                tgq="1";
//            }
//            //退票成功（退款成功）
//            if("refunded".equals(orderStatus)){
//                tgq="2";
//            }
//        }
//        if("HotelContract".equals(productType)||"HotelMember".equals(productType)){
//            // 取消
//                if("Cancelled".equals(orderStatus)){
//                    tgq="2";
//                }
//        }
//        if("Train".equals(productType)){
//             //已改签
//            if("Rebooked".equals(orderStatus)){
//                tgq="1";
//            }
//            //SubmitRefund 退票成功
//            if("SubmitRefund".equals(orderStatus)){
//                tgq="2";
//            }
//        }
//
//        if("0".equals(tgq)){
//            apimap.put("errno","-1");
//            apimap.put("errmsg","不触发流程");
//            return apimap;
//        }
//
//
//        Map orderMap = new HashMap();
//        Map authMap = new HashMap();
//        authMap.put("AppKey",appKey);
//        authMap.put("Ticket",ticket);
//        orderMap.put("Auth",authMap);
//        orderMap.put("JourneyNo","");
//        orderMap.put("OrderID",orderId);
//        orderMap.put("SearchType",1);
//
//        String orderInput = JSON.toJSONString(orderMap);

        String orderBack = JSON.toJSONString(params);
        bb.writeLog("orderBack="+orderBack);
        if(isJsonValid(orderBack)) {
            JSONObject orderObj = JSONObject.parseObject(orderBack);
            JSONArray array = orderObj.getJSONArray("ItineraryList");
            for (int i = 0; i < array.size(); i++) {
                JSONObject detailObj = array.getJSONObject(i);
                JSONArray flightOrderInfoList = detailObj.getJSONArray("FlightOrderInfoList");
                JSONArray hotelOrderInfoList = detailObj.getJSONArray("HotelOrderInfoList");
                JSONArray trainOrderInfoList = detailObj.getJSONArray("TrainOrderInfoList");

                if(flightOrderInfoList!=null){
                    doFlightOrder(flightOrderInfoList,workflowId,tgq);
                }

                if(hotelOrderInfoList!=null){
                    doHotailOrder(hotelOrderInfoList,workflowId,tgq);
                }

                if(trainOrderInfoList!=null){
                    doTrainOrder(trainOrderInfoList,workflowId,tgq);
                }

            }
        }else{
            apimap.put("errno","-1");
            apimap.put("errmsg","订单数据格式不对");
        }


        if("".equals(params.toString())){
            apimap.put("errno","-1");
            apimap.put("errmsg","空数据");
        }else {
            apimap.put("errno", "0");
            apimap.put("errmsg", "");
        }
        return apimap;
    }



    public static String GetSign(String corpId,String productType,String orderStatus,String orderId,String statusIDs ,String refundType,String secret,String approveScenario)
    {
        //构造字典
        HashMap<String,String> hashMap=new HashMap<String,String>();
        hashMap.put("secret",secret);
        hashMap.put("corpId",corpId);
        hashMap.put("productType",productType);
        hashMap.put("orderId",orderId);
        hashMap.put("orderStatus",orderStatus);
        //排序
        Collection<String> collection=hashMap.keySet();
        ArrayList<String> list=new ArrayList<String>(collection);
        Collections.sort(list);
        //拼接
        String str="";
        for( int i=0;i<list.size();i++)
        {
            str+=list.get(i)+"="+hashMap.get(list.get(i));
            if(i!=list.size()-1)
                str+="&";
        }
        //SH1加密
        return DigestUtils.sha1Hex(str).toUpperCase();
    }





    /**
     * 酒店
     * @param hotelOrderInfoList
     * @param workflowId
     * @param tgq
     * @return
     */
    public String doHotailOrder(JSONArray hotelOrderInfoList,String workflowId,String tgq){
        String tgqlx = "2";//飞机　火车　酒店
        String sqlx = "0";//	退单　改签
        if("1".equals(tgq)){
            sqlx = "1";
        }else  if("2".equals(tgq)){
            sqlx = "0";
        }
        String tgqcplx = "5";//	飞机退单　飞机改签　火车退单　火车改签　酒店退单　酒店改签


        String cbzx ="";//成本中心	主表	浏览按钮	分部	1.00
        String ccrbm ="";//出差人部门		主表	浏览按钮	部门	2.00
        String ccr="";//出差人	主表	浏览按钮	人力资源	3.00
        String zwcj="";//职务层级		主表	单行文本框	文本	4.00		加密设置
        String sqrq="";//申请日期		主表	浏览按钮	日期	5.00
        String lcbh="";//流程编号		主表	单行文本框	文本	6.00		加密设置
        String yccsj="-1";//原出差数据		主表	浏览按钮	流程	7.00
        String tgqyy="改签";//退改签原因		主表	多行文本框	多行文本框	8.00
        String str = "";
        //    for(int i=0;i<trainOrderInfoList.size();i++){
        JSONObject obj = hotelOrderInfoList.getJSONObject(0);
//            JSONObject baseInfo = obj.getJSONObject("BasicInfo");
//            String employeeID = baseInfo.getString("EmployeeID");

        //  }

        JSONArray ClientInfoList = obj.getJSONArray("ClientInfo");

        JSONObject ClientInfoEntity = ClientInfoList.getJSONObject(0);
        String employeeID   = ClientInfoEntity.getString("EmployeeID"); //TrainOrderInfoEntity—PassengerInfo
        writeLog("employeeID="+employeeID);
        ccr = getUserId(employeeID)+"";
        cbzx = getCompanyIdDeptId(ccr).split("-")[0];
        ccrbm = getCompanyIdDeptId(ccr).split("-")[1];

        sqrq = TimeUtil.getCurrentDateString();
        String jouneryID = obj.getString("JourneyNo"); //—HotelOrderInfoEntity
        tgqyy = obj.getString("CancelReasonCode");//HotelOrderInfoEntity

        writeLog("tgqyy="+tgqyy);

        Map map = new HashMap();
        map.put("tgqlx",tgqlx);
        map.put("sqlx",sqlx);
        map.put("tgqcplx",tgqcplx);
        map.put("cbzx",cbzx);
        map.put("ccr",ccr);
        map.put("zwcj",zwcj);
        map.put("ccrbm",ccrbm);
        map.put("sqrq",sqrq);
        map.put("yccsj",yccsj);
        map.put("tgqyy",tgqyy);


        if(jouneryID.contains("-")){
            yccsj= jouneryID.split("-")[0];
            writeLog("yccsj="+yccsj);
        }

        WorkflowCreateHandler handler = new WorkflowCreateHandler();
        String tablename = handler.findWorkflowForm(workflowId);

        String IsNextFlow = "1";
        String title = handler.bulidWorkflowTitle(workflowId,ccr);
        String requestId = handler.WorkflowCreateByRequestMap(ccr,workflowId,title,IsNextFlow,map);
        writeLog("requestid="+requestId);
        if(Util.getIntValue(requestId)>1) {
            RecordSet rs = new RecordSet();
            rs.execute("select id from " + tablename +" where requestid="+requestId);
            rs.next();
            String dataId = Util.null2String(rs.getString(1));
            writeLog("dataId="+dataId);


                String StartTime = obj.getString("StartTime");//开始时间
                String EndTime = obj.getString("EndTime");//结束时间
                String CityName = obj.getString("CityName");//入住城市
                String CouponAmount = obj.getString("CouponAmount");//原酒店金额
                JSONObject RefundAmountInfoEnty = obj.getJSONObject("RefundAmountInfo");
                String RefundTotalAmount = RefundAmountInfoEnty.getString("TicketPrice");//退回金额
                String SubcriptionFee = RefundAmountInfoEnty.getString("SubcriptionFee");//退/改签费

                String detailTableName = "";
                Set set = new HashSet();
                List list = new ArrayList();

                detailTableName = tablename + "_dt5";
                Map mapmx = new HashMap();
                mapmx.put("rzsj", StartTime);
                mapmx.put("lksj", EndTime);
                mapmx.put("rzcs", CityName);
                mapmx.put("yjdje", CouponAmount);
                mapmx.put("thje", RefundTotalAmount);
                mapmx.put("tgqf", SubcriptionFee);
                list.add(mapmx);
                set.add("rzsj");
                set.add("lksj");
                set.add("rzcs");
                set.add("yjdje");
                set.add("thje");
                set.add("tgqf");

                handler.insertTableDtMX(list, detailTableName, dataId, set);
        }

        return requestId;
    }



    /**
     * 火车触发流程
     * @param trainOrderInfoList
     * @param workflowId
     * @param tgq
     * @return
     */
    public String doTrainOrder(JSONArray trainOrderInfoList,String workflowId,String tgq){
        String tgqlx = "1";//飞机　火车　酒店
        String sqlx = "1";//	退单　改签
        if("1".equals(tgq)){
            sqlx = "1";
        }else if("2".equals(tgq)){
            sqlx = "0";
        }
        String tgqcplx = "4";//	飞机退单　飞机改签　火车退单　火车改签　酒店退单　酒店改签
        if("1".equals(tgq)){
            tgqcplx="4";
        }else if("2".equals(tgq)){
            tgqcplx="3";
        }

        String cbzx ="";//成本中心	主表	浏览按钮	分部	1.00
        String ccrbm ="";//出差人部门		主表	浏览按钮	部门	2.00
        String ccr="";//出差人	主表	浏览按钮	人力资源	3.00
        String zwcj="";//职务层级		主表	单行文本框	文本	4.00		加密设置
        String sqrq="";//申请日期		主表	浏览按钮	日期	5.00
        String lcbh="";//流程编号		主表	单行文本框	文本	6.00		加密设置
        String yccsj="-1";//原出差数据		主表	浏览按钮	流程	7.00
        String tgqyy="改签";//退改签原因		主表	多行文本框	多行文本框	8.00
        String str = "";
    //    for(int i=0;i<trainOrderInfoList.size();i++){
            JSONObject obj = trainOrderInfoList.getJSONObject(0);
//            JSONObject baseInfo = obj.getJSONObject("BasicInfo");
//            String employeeID = baseInfo.getString("EmployeeID");

      //  }

        JSONArray PassengerInfoList = obj.getJSONArray("PassengerInfoList");
        JSONArray ticketInfoList = obj.getJSONArray("TicketInfoList");



        JSONObject passengerInfoObj = PassengerInfoList.getJSONObject(0);
        String employeeID   = passengerInfoObj.getString("EmployeeID"); //TrainOrderInfoEntity—PassengerInfo
        writeLog("employeeID="+employeeID);
        ccr = getUserId(employeeID)+"";

        cbzx = getCompanyIdDeptId(ccr).split("-")[0];
        ccrbm = getCompanyIdDeptId(ccr).split("-")[1];
        sqrq = TimeUtil.getCurrentDateString();



        JSONObject corpOrderInfo = obj.getJSONObject("CorpOrderInfo");
        String jouneryID = corpOrderInfo.getString("JouneryID"); //—TrainOrderInfoEntity—CorpOrderInfo




        JSONArray OrderTicketList = passengerInfoObj.getJSONArray("OrderTicket");
        JSONObject OrderTicket = OrderTicketList.getJSONObject(0);
        tgqyy = OrderTicket.getString("RefundReasonCodeDesc");//TrainOrderInfoEntity—PassengerInfo—OrderTicketInfo



        Map map = new HashMap();
        map.put("tgqlx",tgqlx);
        map.put("sqlx",sqlx);
        map.put("tgqcplx",tgqcplx);
        map.put("cbzx",cbzx);
        map.put("ccr",ccr);
        map.put("zwcj",zwcj);
        map.put("ccrbm",ccrbm);
        map.put("sqrq",sqrq);
        map.put("yccsj",yccsj);
        map.put("tgqyy",tgqyy);



        if(jouneryID.contains("-")){
            yccsj= jouneryID.split("-")[0];
            writeLog("yccsj="+yccsj);
        }


        WorkflowCreateHandler handler = new WorkflowCreateHandler();
        String tablename = handler.findWorkflowForm(workflowId);


        String IsNextFlow = "1";
        String title = handler.bulidWorkflowTitle(workflowId,ccr);
        String requestId = handler.WorkflowCreateByRequestMap(ccr,workflowId,title,IsNextFlow,map);
        writeLog("requestid="+requestId);
        if(Util.getIntValue(requestId)>1) {
            RecordSet rs = new RecordSet();
            rs.execute("select id from " + tablename +" where requestid="+requestId);
            rs.next();
            String dataId = Util.null2String(rs.getString(1));
            writeLog("dataId="+dataId);


            JSONObject ticketInfo = null;
            for(int i=0;i<ticketInfoList.size();i++){
                ticketInfo = ticketInfoList.getJSONObject(i);
                String TicketInfoID_th = ticketInfo.getString("TicketInfoID");
                writeLog("TicketInfoID_th----"+TicketInfoID_th);
                //D原车次；C改签车次
                String TrainTicketType = ticketInfo.getString("TrainTicketType");
                String trainName = ticketInfo.getString("TrainName");//列车号
                writeLog("trainName="+trainName);
                String departureDateTime = ticketInfo.getString("DepartureDateTime");//开始时间
                String arrivalDateTime = ticketInfo.getString("ArrivalDateTime");//结束时间
                String departureCityName = ticketInfo.getString("DepartureCityName");//出发地
                String arrivalCityName = ticketInfo.getString("ArrivalCityName");//到达地
                String ticketPrice = ticketInfo.getString("TicketPrice");//原火车金额
                String refund = OrderTicket.getString("Refund");//退回金额
                if("".equals(refund)){
                    refund = "0";
                }
                String refundTicketFee = OrderTicket.getString("RefundTicketFee");//退票费：
                if("".equals(refundTicketFee)){
                    refundTicketFee = "0";
                }
                String dealTicketPrice = OrderTicket.getString("DealTicketPrice");//DealTicketPrice（改签车票金额）
                if("".equals(dealTicketPrice)){
                    dealTicketPrice = "0";
                }

                String detailTableName = "";
                Set set = new HashSet();
                List list = new ArrayList();

                if("1".equals(tgq)){
                    if("C".equals(TrainTicketType)) {
                        detailTableName = tablename + "_dt4";
                        Map mapmx = new HashMap();
                        mapmx.put("lch", trainName);
                        mapmx.put("kssj", departureDateTime);
                        mapmx.put("jssj", arrivalDateTime);
                        mapmx.put("cfd", departureCityName);
                        mapmx.put("mdd", arrivalCityName);
                        mapmx.put("gqhcfy", dealTicketPrice);
                        list.add(mapmx);
                        set.add("lch");
                        set.add("kssj");
                        set.add("jssj");
                        set.add("cfd");
                        set.add("mdd");
                        set.add("gqhcfy");
                    }else if("D".equals(TrainTicketType)){
                        detailTableName =tablename + "_dt3";
                        Map mapmx = new HashMap();
                        mapmx.put("lch",trainName);
                        mapmx.put("kssj",departureDateTime);
                        mapmx.put("jssj",arrivalDateTime);
                        mapmx.put("cfd",departureCityName);
                        mapmx.put("mdd",arrivalCityName);
                        mapmx.put("yhcje",ticketPrice);
                        mapmx.put("thje",refund);
                        mapmx.put("tgqf",refundTicketFee);
                        list.add(mapmx);
                        set.add("lch");
                        set.add("kssj");
                        set.add("jssj");
                        set.add("cfd");
                        set.add("mdd");
                        set.add("yhcje");
                        set.add("thje");
                        set.add("tgqf");
                    }
                }else if("2".equals(tgq)){
                    writeLog("tgq="+tgq);
                       String TicketInfoID = "";
                        for(int j=0;j<PassengerInfoList.size();j++){
                            JSONObject PassengerInfo =  PassengerInfoList.getJSONObject(j);
                            JSONArray OrderTicketlist = PassengerInfo.getJSONArray("OrderTicket");
                            for(int k=0;k<OrderTicketlist.size();k++){
                               JSONObject OrderTicket_mx = OrderTicketList.getJSONObject(k);
                               String RefundTicketStatus = OrderTicket_mx.getString("RefundTicketStatus");
                               if("S".equals(RefundTicketStatus)){
                                   TicketInfoID = OrderTicket_mx.getString("TicketInfoID");
                               }
                            }
                        }
                        writeLog("TicketInfoID="+TicketInfoID);
                        writeLog("TicketInfoID_th="+TicketInfoID_th);
                     if(TicketInfoID_th.equals(TicketInfoID)) {
                         detailTableName = tablename + "_dt3";
                         Map mapmx = new HashMap();
                         mapmx.put("lch", trainName);
                         mapmx.put("kssj", departureDateTime);
                         mapmx.put("jssj", arrivalDateTime);
                         mapmx.put("cfd", departureCityName);
                         mapmx.put("mdd", arrivalCityName);
                         mapmx.put("yhcje", ticketPrice);
                         mapmx.put("thje", refund);
                         mapmx.put("tgqf", refundTicketFee);
                         list.add(mapmx);
                         set.add("lch");
                         set.add("kssj");
                         set.add("jssj");
                         set.add("cfd");
                         set.add("mdd");
                         set.add("yhcje");
                         set.add("thje");
                         set.add("tgqf");
                     }

                }
                handler.insertTableDtMX(list, detailTableName, dataId,set);

            }


        }

        return requestId;
    }

    /**
     *
     * @param flightOrderInfoList
     * @param workflowId
     * @param tgq
     * @return
     */
    public String doFlightOrder(JSONArray flightOrderInfoList,String workflowId,String tgq){
        String tgqlx = "0";//飞机　火车　酒店
        String sqlx = "0";//	退单　改签
        if("1".equals(tgq)){
            sqlx = "1";
        }else  if("2".equals(tgq)){
            sqlx = "0";
        }

        String tgqcplx = "4";//	飞机退单　飞机改签　火车退单　火车改签　酒店退单　酒店改签
        if("1".equals(tgq)){
            tgqcplx="4";
        }else if("2".equals(tgq)){
            tgqcplx="3";
        }

        String cbzx ="";//成本中心	主表	浏览按钮	分部	1.00
        String ccrbm ="";//出差人部门		主表	浏览按钮	部门	2.00
        String ccr="";//出差人	主表	浏览按钮	人力资源	3.00
        String zwcj="";//职务层级		主表	单行文本框	文本	4.00		加密设置
        String sqrq="";//申请日期		主表	浏览按钮	日期	5.00
        String lcbh="";//流程编号		主表	单行文本框	文本	6.00		加密设置
        String yccsj="-1";//原出差数据		主表	浏览按钮	流程	7.00
        String tgqyy="改签";//退改签原因		主表	多行文本框	多行文本框	8.00
        String str = "";
        //    for(int i=0;i<trainOrderInfoList.size();i++){
        JSONObject obj = flightOrderInfoList.getJSONObject(0);
//            JSONObject baseInfo = obj.getJSONObject("BasicInfo");
//            String employeeID = baseInfo.getString("EmployeeID");

        //  }

        JSONArray PassengerInfoList = obj.getJSONArray("PassengerInfo");
        JSONArray ticketInfoList = obj.getJSONArray("TicketInfoList");



        JSONObject passengerInfoObj = PassengerInfoList.getJSONObject(0);
        String employeeID   = passengerInfoObj.getJSONObject("PassengerBasic").getString("CorpEid"); //FlightOrderInfoEntity—PassengerInfoEntity—PassengerBasic
        writeLog("employeeID="+employeeID);
        ccr = getUserId(employeeID)+"";

        cbzx = getCompanyIdDeptId(ccr).split("-")[0];
        ccrbm = getCompanyIdDeptId(ccr).split("-")[1];

        sqrq = TimeUtil.getCurrentDateString();

        JSONObject basicInfo = obj.getJSONObject("BasicInfo");
        String jouneryID = basicInfo.getString("JourneyID"); //—FlightOrderInfoEntity—BasicInfo

        JSONObject FlightInfo= obj.getJSONArray("FlightInfo").getJSONObject(0);



        JSONArray RefundInfoEntityList = obj.getJSONArray("RefundInfo");
        JSONObject RefundInfoEntity = null;
        if(RefundInfoEntityList!=null) {
            RefundInfoEntity = RefundInfoEntityList.getJSONObject(0);
            //退票：ItineraryEntity—FlightOrderInfoEntity—RefundInfoEntity；
            //改签：
            //ItineraryEntity—FlightOrderInfoEntity—PassengerInfoEntity—SequenceInfoEntity—ChangeInfoEntity
            tgqyy = RefundInfoEntity.getString("RefundResonDesc");//TrainOrderInfoEntity—PassengerInfo—OrderTicketInfo
        }

        JSONArray SequenceInfoEntityList = passengerInfoObj.getJSONArray("SequenceInfo");
        JSONObject SequenceInfoEntity = SequenceInfoEntityList.getJSONObject(0);
        JSONArray ChangeInfoEntityList = SequenceInfoEntity.getJSONArray("ChangeInfo");
        JSONObject ChangeInfoEntity = ChangeInfoEntityList.getJSONObject(0);


        JSONArray TripRecordInfoList = obj.getJSONArray("TripRecordInfoList");
        JSONObject TripRecordInfoEntity = TripRecordInfoList.getJSONObject(0);


        if("1".equals(tgq)){
            if(ChangeInfoEntity!=null) {
                tgqyy = ChangeInfoEntity.getString("RebookResonDesc");
            }
        }else if("2".equals(tgq)){
            if(RefundInfoEntity!=null) {
                tgqyy = RefundInfoEntity.getString("RefundResonDesc");
            }
        }

        writeLog("tgqyy="+tgqyy);


        Map map = new HashMap();
        map.put("tgqlx",tgqlx);
        map.put("sqlx",sqlx);
        map.put("tgqcplx",tgqcplx);
        map.put("cbzx",cbzx);
        map.put("ccr",ccr);
        map.put("zwcj",zwcj);
        map.put("ccrbm",ccrbm);
        map.put("sqrq",sqrq);
        map.put("yccsj",yccsj);
        map.put("tgqyy",tgqyy);



        if(jouneryID.contains("-")){
            yccsj= jouneryID.split("-")[0];
            writeLog("yccsj="+yccsj);
        }


        WorkflowCreateHandler handler = new WorkflowCreateHandler();
        String tablename = handler.findWorkflowForm(workflowId);


        String IsNextFlow = "1";
        String title = handler.bulidWorkflowTitle(workflowId,ccr);
        String requestId = handler.WorkflowCreateByRequestMap(ccr,workflowId,title,IsNextFlow,map);
        writeLog("requestid="+requestId);
        if(Util.getIntValue(requestId)>1) {
            RecordSet rs = new RecordSet();
            rs.execute("select id from " + tablename +" where requestid="+requestId);
            rs.next();
            String dataId = Util.null2String(rs.getString(1));
            writeLog("dataId="+dataId);


            String detailTableName = "";

            if("1".equals(tgq)){
//            改签明细表	航班号 		CTicketNO	ItineraryEntity—FlightOrderInfoEntity—PassengerInfoEntity—SequenceInfoEntity—ChangeInfoEntity
//            改签明细表	开始时间 		CTakeOffTime	ItineraryEntity—FlightOrderInfoEntity—PassengerInfoEntity—SequenceInfoEntity—ChangeInfoEntity
//            改签明细表	结束时间 		CArrivalTime	ItineraryEntity—FlightOrderInfoEntity—PassengerInfoEntity—SequenceInfoEntity—ChangeInfoEntity
//            改签明细表	出发地 		CDCityName	ItineraryEntity—FlightOrderInfoEntity—PassengerInfoEntity—SequenceInfoEntity—ChangeInfoEntity
//            改签明细表	到达地		CACityName	ItineraryEntity—FlightOrderInfoEntity—PassengerInfoEntity—SequenceInfoEntity—ChangeInfoEntity
//            改签明细表	"改签后机票金额
//            "		CPrintPrice	ItineraryEntity—FlightOrderInfoEntity—PassengerInfoEntity—SequenceInfoEntity—ChangeInfoEntity
                detailTableName =tablename + "_dt1";
                Set set = new HashSet();
                List list = new ArrayList();
                Map mapmx = new HashMap();
                mapmx.put("hbh",FlightInfo.getString("Flight"));//航班号
                mapmx.put("qfsj",FlightInfo.getString("TakeoffTime"));//开始时间
                mapmx.put("ddsj",FlightInfo.getString("ArrivalTime"));//到达时间
                mapmx.put("cfd",FlightInfo.getString("DCityName"));
                mapmx.put("mdd",FlightInfo.getString("ACityName"));
                mapmx.put("yjpje",FlightInfo.getString("Amount"));
                list.add(mapmx);
                set.add("hbh");
                set.add("qfsj");
                set.add("ddsj");
                set.add("cfd");
                set.add("mdd");
                set.add("yjpje");
                handler.insertTableDtMX(list, detailTableName, dataId,set);

                set = new HashSet();
                list = new ArrayList();
                detailTableName =tablename + "_dt2";
                mapmx = new HashMap();
                mapmx.put("hbh",ChangeInfoEntity.getString("CFlight"));//航班号
                mapmx.put("qfsj",ChangeInfoEntity.getString("CTakeOffTime"));//开始时间
                mapmx.put("ddsj",ChangeInfoEntity.getString("CArrivalTime"));//结束时间
                mapmx.put("cfd",ChangeInfoEntity.getString("CDCityName"));//cfd
                mapmx.put("mdd",ChangeInfoEntity.getString("CACityName"));//到达地
                mapmx.put("gqfjfy",ChangeInfoEntity.getString("CPrintPrice"));//改签后机票金额
                list.add(mapmx);
                set.add("tgqf");
                set.add("qfsj");
                set.add("ddsj");
                set.add("cfd");
                set.add("mdd");
                set.add("gqfjfy");
                handler.insertTableDtMX(list, detailTableName, dataId,set);
            }else if("2".equals(tgq)){
//            退单明细表	航班号 		Flight	ItineraryEntity—FlightOrderInfoEntity—TripRecordInfoEntity
//            退单明细表	开始时间 		TakeOffTime	ItineraryEntity—FlightOrderInfoEntity—TripRecordInfoEntity	RecordStatus=R退票
//            退单明细表	结束时间 		ArrivalTime	ItineraryEntity—FlightOrderInfoEntity—TripRecordInfoEntity	RecordStatus=R退票
//            退单明细表	出发地 		DepartureCityName	ItineraryEntity—FlightOrderInfoEntity—TripRecordInfoEntity	RecordStatus=R退票
//            退单明细表	到达地		ArrivalCityName	ItineraryEntity—FlightOrderInfoEntity—TripRecordInfoEntity	RecordStatus=R退票
//            退单明细表	原机票金额		PrintPrice+Oil+Tax	ItineraryEntity—FlightOrderInfoEntity—TripRecordInfoEntity	RecordStatus=R退票
//            退单明细表	退回金额		PayCustomerAmount	ItineraryEntity—FlightOrderInfoEntity—RefundInfoEntity
//            退单明细表	退/改签费		RefundAmount+ChangeAmount	ItineraryEntity—FlightOrderInfoEntity—BasicInfo

                Set set2 = new HashSet();
                List list = new ArrayList();
                detailTableName =tablename + "_dt1";
                Map mapmx = new HashMap();

                double yjpje = Util.getDoubleValue(TripRecordInfoEntity.getString("PrintPrice"))+Util.getDoubleValue(TripRecordInfoEntity.getString("Oil"))+Util.getDoubleValue(TripRecordInfoEntity.getString("Tax"));
                double tgqf = Util.getDoubleValue(basicInfo.getString("RefundAmount"))+Util.getDoubleValue(basicInfo.getString("ChangeAmount"));

                mapmx.put("hbh",TripRecordInfoEntity.getString("Flight"));//航班号
                mapmx.put("qfsj",TripRecordInfoEntity.getString("TakeOffTime"));//开始时间
                mapmx.put("ddsj",TripRecordInfoEntity.getString("ArrivalTime"));//到达时间
                mapmx.put("cfd",TripRecordInfoEntity.getString("DepartureCityName"));
                mapmx.put("mdd",TripRecordInfoEntity.getString("ArrivalCityName"));
                mapmx.put("yjpje",yjpje+"");
                mapmx.put("thje", RefundInfoEntity.getString("PayCustomerAmount"));
                mapmx.put("tgqf",tgqf+"");
                list.add(mapmx);

                set2.add("hbh");
                set2.add("qfsj");
                set2.add("ddsj");
                set2.add("cfd");
                set2.add("mdd");
                set2.add("yjpje");
                set2.add("thje");
                set2.add("tgqf");

                handler.insertTableDtMX(list, detailTableName, dataId,set2);
            }

        }

        return requestId;
    }

    /**
     * 获取用户id
     * @param code
     * @return
     */
    public int getUserId(String code){
        int id= 0;
        RecordSet rs = new RecordSet();
        rs.execute("select id from hrmresource where workcode='"+code+"'");
        rs.next();
        id = Util.getIntValue(rs.getString(1));
        return id;
    }

    /**
     * 提交数据
     * @param input
     * @param url
     * @return
     */
    public String postData2(String input,String url){
        String back = "";
        OkHttpClient client = new OkHttpClient();
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, input);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .addHeader("Content-Type", "application/json")
                .addHeader("cache-control", "no-cache")
                .build();

        try {
            Response response = client.newCall(request).execute();
            back = response.body().string();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return back;
    }


    /**
     * 携程提交数据
     * @param param
     * @param url
     * @return
     */
    public static String postData(String param,String url)
    {
        OutputStreamWriter out = null;
        BufferedReader in =null;
        String result = "";
        try
        {
            URL realUrl = new URL(url);
            HttpURLConnection conn = null;
            conn = (HttpURLConnection) realUrl.openConnection();
            //发送POST请求必须设置如下两行
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            //设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0(compatible;MSIE6.0;WindowsNT5.1;SV1)");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.connect();
            //获取URLConnection对象对应的输出流
            out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            out.write(param);
            //发送请求参数
            out.flush();
            //flush输出流的缓冲
            //定义BufferedReader输入流来读取URL的响应
            in =new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String line;
            while ((line = in.readLine()) != null)
            {
                result += line;
                System.out.println("OK");
            }
        }
        catch(Exception e)
        {
            System.out.println("发送POST请求出现异常！" + e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally
        {
            try
            {
                if (out != null)
                {
                    out.close();
                }
                if ( in !=null)
                {
                    in .close();
                }
            }
            catch(IOException ex)
            {
                ex.printStackTrace();
            }
        }
        return result;
    }



    /**
     * 判断JSON字符串是否合法
     *
     * @param jsonStr JSON字符串
     * @return true：合法；false：不合法
     */
    public static boolean isJsonValid(String jsonStr) {
        try {
            JSON.parse(jsonStr);
            return true;
        } catch (JSONException e) {
            return false;
        }
    }

    /**
     * 获取公司和部门id
     * @param userid
     * @return
     */
    public String getCompanyIdDeptId(String userid){
        RecordSet rs = new RecordSet();
        String str = "";
        rs.execute(" select subcompanyid1,departmentid from hrmresource where id="+userid);
        rs.next();
        str = Util.null2String(rs.getString("subcompanyid1"))+"-"+Util.null2String(rs.getString("departmentid"));
        return str;
    }




}
