package com.engine.htsc.ReimbursementFlow.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.engine.htsc.ReimbursementFlow.Esb.Dao.UfzbbxesblocalDao;
import com.engine.htsc.ReimbursementFlow.Esb.ThreadAsync.Ufzbbxesblocalinsert;
import com.engine.htsc.ReimbursementFlow.model.UfZbtybxsp;
import com.engine.workflowDesign.entity.xmlEntity.Array;
import org.apache.xpath.operations.Bool;
import weaver.general.Util;
import weaver.interfaces.htsc.GlobatTools.JAVATools;
import weaver.interfaces.htsc.comInfo.PropBean;
import weaver.interfaces.htsc.cus.HTUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class OldToTravelList {

    private UfzbbxesblocalDao ufzbbxesblocalDao = new UfzbbxesblocalDao();

    @POST
    @Path("/GetTravelList")
    @Produces({MediaType.TEXT_PLAIN})
    public String GetOldTotravelList(@Context HttpServletRequest request,
                                     @Context HttpServletResponse response) {
        PropBean pb = new PropBean();
        HTUtil htUtil = new HTUtil();
        String jsonvalue = "";
        String teamID = Util.null2String(request.getParameter("teamID"));
        String teamName = Util.null2String(request.getParameter("teamName"));
        String userCode = Util.null2String(request.getParameter("userCode"));
        String sysCode = Util.null2String(request.getParameter("sysCode"));
        String flowType = Util.null2String(request.getParameter("flowType"));
        String departmentCode = Util.null2String(request.getParameter("departmentCode"));
        int pageNo = Util.getIntValue(Util.null2String(request.getParameter("pageNo")));
        int pagesize = Util.getIntValue(Util.null2String(request.getParameter("pagesize")));
        String travelCode = Util.null2String(request.getParameter("travelCode"));
        JAVATools.SetCmdwritelog("查看参数:", "userCode:" + userCode + " sysCode：" + sysCode + " travelCode:" + travelCode);

        if ("".equals(userCode) || "".equals(sysCode)) {
            // return jsonvalue;
            sysCode = "1";
        }
        if (pageNo < 0) {
            pageNo = 0;
        }
        if (pageNo >= 1) {
            pageNo = pageNo - 1;
        }
        if (pagesize <= 0) {
            pagesize = 20;
        }

  /*  if(!"".equals(travelCode)) {
       // pagesize = 10;
//        if(IsBoollocalGetTotravelList(travelCode)){
//            //如果条件满足的话则从本地取数据
//          String returnstr=  localGetTotravelList(travelCode);
//          if(!"".equals(returnstr)){
//              System.out.println("是不是走这个里面");
//              return returnstr;
//          }
//
//        }
    }*/
        JSONObject jsonObject = new JSONObject();

        jsonObject.put("sysCode", sysCode);
        jsonObject.put("start", pageNo);
        jsonObject.put("count", pagesize);
        jsonObject.put("teamID",teamID);
        jsonObject.put("teamName",teamName);
        jsonObject.put("flowType",flowType);

        if (!"".equals(travelCode)) {
            jsonObject.put("travelCodeList", Arrays.asList(travelCode.split(",")));
        }
        if (!"".equals(departmentCode)) {

            jsonObject.put("departmentCode", departmentCode);
        }
        if (!"".equals(userCode)) {
            jsonObject.put("userCode", userCode);
        }
        String urllistrl = pb.getPropName("travelexpense_oldlist");
        Map<String, String> handermap = htUtil.getAppHeader();
        if (handermap != null && handermap.size() > 0) {
            for (Map.Entry<String, String> entry : handermap.entrySet()) {
                System.out.println(entry.getKey() + ":" + entry.getValue());
            }
        }
        String responsestr = htUtil.httpPostRaw(urllistrl, jsonObject.toJSONString(), handermap, null);
        //异步插入数据
        //new Ufzbbxesblocalinsert(responsestr).start();
        if (!"".equals(travelCode)) {
            JSONArray retjsonarray = new JSONArray();
            JSONObject retjsonobject = new JSONObject();
            JSONObject jsonObjectstr = JSONObject.parseObject(responsestr);
            JSONArray jsonArray = (JSONArray) jsonObjectstr.get("travelList");

            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonobj = (JSONObject) jsonArray.get(i);
                String travelCodedetail = Util.null2String(jsonobj.get("travelCode"));
                if (!"".equals(travelCodedetail) && travelCode.indexOf(travelCodedetail) >= 0) {
                    retjsonarray.add(jsonobj);
                }
            }
            retjsonobject.put("message", Util.null2String(jsonObjectstr.get("message")));
            retjsonobject.put("errorMessage", Util.null2String(jsonObjectstr.get("errorMessage")));
            //  retjsonobject.put("count", retjsonarray.size());
            retjsonobject.put("travelList", retjsonarray);
            retjsonobject.put("success", Util.null2String(jsonObjectstr.get("success")));
            responsestr = JSON.toJSONString(retjsonobject, SerializerFeature.WriteMapNullValue);


        }
        JAVATools.SetCmdwritelog("差旅付款接口回写", responsestr);
        return responsestr;
    }

    public Boolean IsBoollocalGetTotravelList(String travelCode) {
        boolean flag = false;
        if ("".equals(travelCode)) {
            return false;
        }
        String params = Arrays.stream(travelCode.split(",")).map(s -> "\'" + s + "\'").collect(Collectors.joining(","));
        int psum = ufzbbxesblocalDao.gettravelcodesum(params);
        if (psum > 0 && psum == travelCode.split(",").length) {
            flag = true;
        }
        return flag;
    }

    public String localGetTotravelList(String travelCode) {
        String value = "";
        JSONObject jsonObject = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        String params = Arrays.stream(travelCode.split(",")).map(s -> "\'" + s + "\'").collect(Collectors.joining(","));

        List<Map<String, Object>> list = ufzbbxesblocalDao.gettravelcodelist(params);

        if (list.size() <= 0) {
            return value;
        }
        for (Map<String, Object> map : list) {
            String nrvalue = Util.null2String(map.get("nr"));
            jsonArray.add(JSONObject.parse(nrvalue));
        }
        if (jsonArray.size() != travelCode.split(",").length) {
            return value;
        }


        jsonObject.put("message", "");
        jsonObject.put("errorMessage", "");
        // jsonObject.put("count", jsonArray.size());
        jsonObject.put("travelList", jsonArray);
        jsonObject.put("success", "true");
        value = JSON.toJSONString(jsonObject, SerializerFeature.WriteMapNullValue);


        return value;


    }

    @POST
    @Path("/GetTraveInfo")
    @Produces({MediaType.TEXT_PLAIN})
    public String GetOldTotravelInfo(@Context HttpServletRequest request,
                                     @Context HttpServletResponse response) {
        PropBean pb = new PropBean();
        HTUtil htUtil = new HTUtil();
        String jsonvalue = "";
        String userCode = Util.null2String(request.getParameter("userCode"));
        String sysCode = Util.null2String(request.getParameter("sysCode"));
        String travelCodeStr = Util.null2String(request.getParameter("travelCodeList"));

        if ("".equals(userCode) || "".equals(sysCode) || "".equals(travelCodeStr)) {
            return jsonvalue;
        }
        List travelCodeList = Arrays.asList(travelCodeStr.split(","));
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("userCode", userCode);
        jsonObject.put("sysCode", sysCode);
        jsonObject.put("travelCodeList", travelCodeList);
        String urllistinfo = pb.getPropName("travelexpense_oldinfo");
        Map<String, String> handermap = htUtil.getAppHeader();
        if (handermap != null && handermap.size() > 0) {
            for (Map.Entry<String, String> entry : handermap.entrySet()) {
                System.out.println(entry.getKey() + ":" + entry.getValue());
            }
        }

        JSONArray retjsonarray = new JSONArray();
        JSONObject retjsonobject = new JSONObject();
        String responsestr = htUtil.httpPostRaw(urllistinfo, jsonObject.toJSONString(), handermap, null);
        JSONObject jsonObjectstr = JSONObject.parseObject(responsestr);
        JSONArray jsonArray = (JSONArray) jsonObjectstr.get("travelList");
        //调用 增加范围自己的用户id
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonobj = (JSONObject) jsonArray.get(i);
            String applicantListdetail = Util.null2String(jsonobj.get("applicantList"));
            if (!"".equals(applicantListdetail)) {
                JSONArray jsonArray1 = (JSONArray) jsonobj.get("applicantList");
                if (jsonArray1.size() >= 1) {
                    for (int k = 0; k < jsonArray1.size(); k++) {
                        String workcode = ((JSONObject) jsonArray1.get(k)).get("userId").toString();
                        String deptCode = ((JSONObject) jsonArray1.get(k)).get("deptCode").toString();
                        String fwdeptid = JAVATools.getdepartmentcodetoid(deptCode);
                        String fwuserid = JAVATools.gethrmworkcodetoid(workcode, fwdeptid);

                        ((JSONObject) ((JSONArray) jsonobj.get("applicantList")).get(k)).put("fwusderid", fwuserid);
                        ((JSONObject) ((JSONArray) jsonobj.get("applicantList")).get(k)).put("fwdeptid", fwdeptid);

                    }

                }
            }
            retjsonarray.add(jsonobj);
        }
        retjsonobject.put("message", Util.null2String(jsonObjectstr.get("message")));
        retjsonobject.put("errorMessage", Util.null2String(jsonObjectstr.get("errorMessage")));
        retjsonobject.put("travelList", retjsonarray);
        retjsonobject.put("success", jsonObjectstr.get("success"));
        retjsonobject.put("orderSettlementList", reloadorderSettlementList(jsonObjectstr.get("orderSettlementList")));
        responsestr = JSON.toJSONString(retjsonobject, SerializerFeature.WriteMapNullValue);


        return responsestr;
    }


    public JSONArray reloadorderSettlementList(Object orderSettlementList) {

        if (orderSettlementList == null) {
            return null;
        }
        JSONArray jsonarray = (JSONArray) orderSettlementList;
        if (jsonarray.size() <= 0) {
            return jsonarray;
        }
        for (int i = 0; i < jsonarray.size(); i++) {
            //第一步遍历
            Object empOrderSettlementModels = jsonarray.get(i);
            if (empOrderSettlementModels != null) {
                Object empOrderSettlementModelsobj = ((JSONObject) empOrderSettlementModels).get("empOrderSettlementModels");
                if (empOrderSettlementModelsobj != null) {
                    JSONArray jsonSettlementModelsobj = (JSONArray) empOrderSettlementModelsobj;
                    for (int j = 0; j < jsonSettlementModelsobj.size(); j++) {
                        Object modelsobj = jsonSettlementModelsobj.get(j);
                        if (modelsobj != null && ((JSONObject) modelsobj).size() > 0) {
                            Object carOrderSett = ((JSONObject) modelsobj).get("carOrderSettlementModels");
                            Object trainOrder = ((JSONObject) modelsobj).get("trainOrderSettlementModels");
                            Object hotelOrder = ((JSONObject) modelsobj).get("hotelOrderSettlementModels");
                            Object flightOrder = ((JSONObject) modelsobj).get("flightOrderSettlementModels");
                            //因为有一些情况，所以不用循环来赋值

                            if (getfwuserid(carOrderSett) != null) {
                                ((JSONObject) modelsobj).put("carOrderSettlementModels", getfwuserid(carOrderSett));
                            }
                            if (getfwuserid(trainOrder) != null) {
                                ((JSONObject) modelsobj).put("trainOrderSettlementModels", getfwuserid(trainOrder));
                            }
                            if (getfwuserid(hotelOrder) != null) {
                                ((JSONObject) modelsobj).put("hotelOrderSettlementModels", getfwuserid(hotelOrder));
                            }
                            if (getfwuserid(flightOrder) != null) {
                                ((JSONObject) modelsobj).put("flightOrderSettlementModels", getfwuserid(flightOrder));
                            }

                        }
                    }
                    // JSONObject  (JSONObject)empOrderSettlementModelsobj
                }
            }
        }


        return jsonarray;
    }

    public Object getfwuserid(Object obj) {
        String value = "";
        if (obj == null || ((JSONArray) obj).size() <= 0) {
            return null;
        }
        JSONArray jsonArray = (JSONArray) obj;
        //stream

        for (int i = 0; i < jsonArray.size(); i++) {
            if (jsonArray.get(i) != null) {
                JSONObject objvalue = (JSONObject) jsonArray.get(i);
                String employeeIdstr = Util.null2String(objvalue.get("employeeId"));
                String empDeptCodestr = Util.null2String(objvalue.get("empDeptCode"));
                String fwdeptid = JAVATools.getdepartmentcodetoid(empDeptCodestr);
                value = JAVATools.gethrmworkcodetoid(employeeIdstr, fwdeptid);
                ((JSONObject) (JSONObject) jsonArray.get(i)).put("fwuserid", value);

            }
        }
        return jsonArray;
    }
}
