package yem.wmc.ydn.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.entity.cache.AppCache;
import kd.bos.entity.cache.IAppCache;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import yem.base.common.utils.HttpHelper;
import yem.base.common.utils.YEM;

import java.util.*;

import static yem.wmc.ydn.utils.APIAddressUtils.Portdatabookingdownload;


/**
 * 公共类
 *  todo 调用第三方接口 传参给与固定值仅用于测试阶段
 */
public class CommonUtils {

    public static final String COSCO = "COSCO";

    /**
     * 获取当前登录用户主键
     */
    public static Long getCurrentUserId() {
        return RequestContext.get().getCurrUserId();
    }
    /**
     * 获取登录令牌
     *
     * @return 令牌字符串
     */
    public static String getToken() {
        String Token = "";
        DynamicObject middlelayerdata = null;
        try {
            JSONObject JObject = new JSONObject();
            JObject.put("username", "admin");
            JObject.put("password", "admin123");
            String param = JObject.toString();
            Map<String, String> map = new HashMap<>();
            map.put("tenant-id", "1");
            String TokenStr = HttpHelper.httpPost(APIAddressUtils.Getlogin, map, param);
            if (TokenStr != null) {
                JSONObject jsondata = JSONObject.parseObject(TokenStr);
                String code = jsondata.getString("code");
                if (code.equals("0")) {
                    JSONObject Data = JSONObject.parseObject(jsondata.getString("data"));
                    Token = Data.getString("accessToken");
                    IAppCache appCache = AppCache.get("yem_ydn");
                    appCache.put("accessToken", Token);
                }
                middlelayerdata = JsonToDataUtils.jsonToData("yem_ydn_middlelayerdata", jsondata, null);
            }
        } catch (Exception e) {
            e.printStackTrace();
            //记录日志
        }
        return Token;
    }
    /**
     * 港区数据订阅
     */
    public static String getPortdatabooking() {
        IAppCache appCache = AppCache.get("yem_ydn");//获取缓存
        String value1 = appCache.get("accessToken", String.class);
        String access_token = null;
        String message = null;
        DynamicObject middlelayerdata = null;
        if (value1 != null) {
            access_token = value1;
        } else {
            access_token = getToken();
        }
        try {
            JSONObject JObject = new JSONObject();
            JObject.put("localkeyid", "123");
            JObject.put("referenceno", "COAU8036422250");
            JObject.put("portcd", "CNSHA");
            JObject.put("ieid", "I");
            String param = JObject.toString();
            Map<String, String> map = new HashMap<>();
            map.put("tenant-id", "1");
            //map.put("Authorization", access_token);
            String Portdatabooking = HttpHelper.httpPost(APIAddressUtils.Portdatabooking, map, param);
            JSONObject body = JSON.parseObject(Portdatabooking);//将结果转换为JSONObject
            String code = body.getString("code");//获取状态
            if ("0".equals(code)) {
                JSONObject Data = JSONObject.parseObject(body.getString("data"));
                if (Data.containsKey("status")) {
                    if (Data.getString("status").equals("1")) {
                        access_token = getToken();
                        Portdatabooking = HttpHelper.httpPost(APIAddressUtils.Portdatabooking, map, param);
                        body = JSON.parseObject(Portdatabooking);//将结果转换为JSONObject
                        Data = JSONObject.parseObject(body.getString("data"));
                        code = body.getString("code");//获取状态
                    }
                }
                if ("0".equals(code) && !Data.containsKey("status")) {
                    DynamicObject portdatabooking = JsonToDataUtils.jsonToData("yem_ydn_portdatabooking", Data, null);//
                    if (portdatabooking == null) {
                        message = "插入数据失败";
                    } else {
                        message = "插入数据成功，单据编号为:" + portdatabooking.getString("billno");
                    }
                } else {
                    message = Portdatabooking;
                }
                middlelayerdata = JsonToDataUtils.jsonToData("yem_ydn_middlelayerdata", body, null);//中间层数据
            }
        } catch (Exception exception) {
            //exception.printStackTrace();
            message = YEM.exceptionToStr(exception);
        }
        return message;
    }


    /**
     * 港区数据（港区数据订阅下载）
     */
    public static String getPortdata() {
        IAppCache appCache = AppCache.get("yem_ydn");//获取缓存
        String value1 = appCache.get("accessToken", String.class);
        String access_token = null;
        String message = null;
        DynamicObject middlelayerdata = null;
        if (value1 != null) {
            access_token = value1;
        } else {
            access_token = getToken();
        }
        try {
            JSONObject JObject = new JSONObject();
            JObject.put("referenceno", "COAU8036422250");
            JObject.put("portcd", "CNSHA");
            String param = JObject.toString();
            Map<String, String> map = new HashMap<>();
            map.put("tenant-id", "1");
            //map.put("Authorization", access_token);
            String Portdatabookingdownload = HttpHelper.httpPost(APIAddressUtils.Portdatabookingdownload, map, param);
            JSONObject body = JSON.parseObject(Portdatabookingdownload);//将结果转换为JSONObject
            String code = body.getString("code");//获取状态
            if ("0".equals(code)) {
                JSONObject Data = JSONObject.parseObject(body.getString("data"));
                if (Data.getInteger("status") != 0) {
                    return message = Data.getString("message");
                }
                DynamicObject portdata = JsonToDataUtils.jsonToData("yem_ydn_portdata", Data, null);//
                if (portdata == null) {
                    message = "插入数据失败";
                } else {
                    message = "插入或更新数据成功，单据编号为:" + portdata.getString("billno");
                }
                middlelayerdata = JsonToDataUtils.jsonToData("yem_ydn_middlelayerdata", body, null);//中间层数据
            } else {
                message = Portdatabookingdownload;
            }
        } catch (Exception exception) {
            //exception.printStackTrace();
            message = YEM.exceptionToStr(exception);
        }
        return message;

    }


    /**
     * 海运跟踪订阅
     */
    public static String getShiptracking() {
        IAppCache appCache = AppCache.get("yem_ydn");//获取缓存
        String value1 = appCache.get("accessToken", String.class);
        String access_token = null;
        String message = null;
        DynamicObject middlelayerdata = null;
        if (value1 != null) {
            access_token = value1;
        } else {
            access_token = getToken();
        }
        try {
            JSONObject JObject = new JSONObject();
            JObject.put("localkeyid", "123");
            JObject.put("carriercd", "COSCO");
            JObject.put("referenceno", "6135761320");
            JObject.put("ctnrno", "CSNU1552621");
            JObject.put("pol", "CNNGB");
            JObject.put("dtp", "CNNGB");
            JSONArray jsonArray = new JSONArray();
            jsonArray.add(JObject);
            String param = jsonArray.toString();
            Map<String, String> map = new HashMap<>();
            map.put("tenant-id", "1");
            //map.put("Authorization", access_token);
            String Portdatabookingdownload = HttpHelper.httpPost(APIAddressUtils.Pookingsv2, map, param);
            JSONObject body = JSON.parseObject(Portdatabookingdownload);
            String code = body.getString("code");//获取状态
            if ("0".equals(code)) {
                JSONObject Data = body.getJSONObject("data");
                JSONArray jsonResult = Data.getJSONArray("result");//存储多条数据的集合
                int sum =0;
                for (Object object : jsonResult) {
                    JSONObject rowJsonObj = (JSONObject) object;
                    if (rowJsonObj.getBoolean("success")) {
                        DynamicObject portdata = JsonToDataUtils.jsonToData("yem_ydn_shiptracking", rowJsonObj, null);
                        if (portdata != null) {
                            sum++;
                        }
                    } else{
                        return message = rowJsonObj.getString("message");
                    }
                }
                message = "共" + jsonResult.size() + "条数据,成功插入" + sum + "条数据,失败" + (jsonResult.size() - sum) + "条！";
                middlelayerdata = JsonToDataUtils.jsonToData("yem_ydn_middlelayerdata", body, null);//中间层数据
            } else { //错误数据
                message = Portdatabookingdownload;
            }
        } catch (Exception exception) {
            //exception.printStackTrace();
            message = YEM.exceptionToStr(exception);
        }
        return message;
    }


    /**
     * 海运跟踪下载 shipdownload
     */
    public static String getShipdownload() {
        IAppCache appCache = AppCache.get("yem_ydn");//获取缓存
        String value1 = appCache.get("accessToken", String.class);
        String access_token = null;
        String message = null;
        DynamicObject middlelayerdata = null;
        if (value1 != null) {
            access_token = value1;
        } else {
            access_token = getToken();
        }
        try {
            JSONObject JObject = new JSONObject();
            JObject.put("keyid", "123");
            JObject.put("carriercd", "COSCO");
            JObject.put("referenceno", "6135761320");
            JObject.put("ctnrno", "CSNU1552621");
            JObject.put("pol", "CNNGB");
            JObject.put("dtp", "CNNGB");
            JSONArray jsonArr = new JSONArray();
            jsonArr.add(JObject);
            String param = jsonArr.toString();
            Map<String, String> map = new HashMap<>();
            map.put("tenant-id", "1");
            //map.put("Authorization", access_token);
            String Portdatabookingdownload = HttpHelper.httpPost(APIAddressUtils.Bookingv3liner, map, param);
            int length = Portdatabookingdownload.length();
            JSONObject body = JSON.parseObject(Portdatabookingdownload);
            String code = body.getString("code");//获取状态
            if ("0".equals(code)) {
                JSONArray data = body.getJSONArray("data");
                if (data.size() == 0) {
                    return message = "返回数据为空，请检查请求参数是否正确";
                }
                JSONObject Data = data.getJSONObject(0);
                if (!Data.getBoolean("success")) {
                    return message = "调用失败，请检查请求参数是否正确";
                }
                DynamicObject portdata = JsonToDataUtils.jsonToData("yem_ydn_shipdownload", Data.getJSONObject("objlinertracking"), null);//
                if (portdata == null) {
                    message = "插入数据失败";
                } else {
                    message = "插入或更新数据成功，单据编号为:" + portdata.getString("billno");
                }

                middlelayerdata = JsonToDataUtils.jsonToData("yem_ydn_middlelayerdata", body, null);//中间层数据
            } else { //错误数据
                message = Portdatabookingdownload;
            }
        } catch (Exception exception) {
            message = YEM.exceptionToStr(exception);
        }
        return message;

    }

    /**
     * 单船搜索
     */
    public static String getQueryShip() {
        IAppCache appCache = AppCache.get("yem_ydn");//获取缓存
        String value1 = appCache.get("accessToken", String.class);
        String access_token = null;
        String message = null;
        DynamicObject middlelayerdata = null;
        if (value1 != null) {
            access_token = value1;
        } else {
            access_token = getToken();
        }
        JSONObject JObject = new JSONObject();
//        JObject.put("keyword", "ONE ORINOCO");
        JObject.put("keyword", "LUCKY");
        String param = JObject.toString();
        Map<String, String> map = new HashMap<>();
        map.put("tenant-id", "1");
        //map.put("Authorization", access_token);
        try {
            String jsonResult = HttpHelper.httpPost(APIAddressUtils.Queryship, map, param);
            JSONObject body = JSON.parseObject(jsonResult);
            int code = body.getInteger("code");//获取状态
            if (code == 0) {
                JSONObject data = body.getJSONObject("data");
                Boolean aBoolean = data.getBoolean("success");
                if (data.containsKey("data") && aBoolean) {
                    JSONArray dataJSONArray = data.getJSONArray("data");
                    ArrayList<DynamicObject> list = new ArrayList<>();
                    int size = dataJSONArray.size();
                    int succeedSum = size;
                    for (Object object : dataJSONArray) {
                        JSONObject Data = (JSONObject) object;
                        DynamicObject portdata = JsonToDataUtils.jsonToData("yem_ydn_queryship", Data, null);
                        if (portdata == null) {
                            succeedSum--;
                        } else {
                            list.add(portdata);
                        }
                    }
                    if (list.size() > 0) {
                        DynamicObject dynamicObject = list.get(0);
                        message = "共" + size + "条数据，成功插入" + succeedSum + "条，失败" + (size - succeedSum) + "条！第一条数据的单据编号为:" + dynamicObject.getString("billno");
                    } else {
                        return message = "返回的数据为空，请检查参数是否正确";
                    }
                } else {
                   return message = data.getString("message");
                }
                middlelayerdata = JsonToDataUtils.jsonToData("yem_ydn_middlelayerdata", body, null);//中间层数据
            } else {
                message = jsonResult;
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
            message = YEM.exceptionToStr(e);
        }
        return message;
    }

    /**
     * 船舶历史挂港
     *
     * @return
     */
    public static String getPortofcall() {
        IAppCache appCache = AppCache.get("yem_ydn");//获取缓存
        String value1 = appCache.get("accessToken", String.class);
        String access_token = null;
        String message = null;
        DynamicObject middlelayerdata = null;
        if (value1 != null) {
            access_token = value1;
        } else {
            access_token = getToken();
        }
        try {
            JSONObject requestJson = new JSONObject();
            requestJson.put("mmsi", "477836900");
            requestJson.put("begin", "2023-10-01 00:00:00");
            requestJson.put("end", "2023-11-30 00:00:00");
            String param = requestJson.toString();
            Map<String, String> map = new HashMap<>();
            map.put("tenant-id", "1");
            //map.put("Authorization", access_token);
            String strReult = HttpHelper.httpPost(APIAddressUtils.Portofcall, map, param);
            JSONObject jsonReult = JSON.parseObject(strReult);
            String code = jsonReult.getString("code");//获取状态
            if ("0".equals(code)) {
                JSONObject dataOne = jsonReult.getJSONObject("data");
                if (dataOne.containsKey("data") && dataOne.getBoolean("success")) {
                    DynamicObject portdata = JsonToDataUtils.jsonToData("yem_ydn_shipdocking", dataOne, requestJson);//
                    if (portdata == null) {
                        return message = "插入数据失败";
                    } else {
                        message = "插入数据成功，单据编号为:" + portdata.getString("billno");
                    }
                } else {
                   return message = dataOne.getString("message");
                }
                middlelayerdata = JsonToDataUtils.jsonToData("yem_ydn_middlelayerdata", jsonReult, null);//中间层数据
            } else {
                message = strReult;
            }
        } catch (Exception exception) {
            //exception.printStackTrace();
            message = YEM.exceptionToStr(exception);
        }
        return message;

    }


    /**
     * 获取当前登录用户对象
     */
    public static DynamicObject getCurrentUser() {
        final long currentUserId = RequestContext.get().getCurrUserId();
        return BusinessDataServiceHelper.loadSingleFromCache((Object) currentUserId, "bos_user");
    }

    /**
     * 判断对象是否为空
     *
     * @param o
     * @return
     */
    public static boolean isNull(final Object o) {
        return o == null || (o instanceof String && ((String) o).length() == 0)
                || (o instanceof StringBuffer && ((StringBuffer) o).length() == 0)
                || (o instanceof List && ((List) o).size() == 0)
                || (o instanceof Collection && ((Collection) o).size() == 0)
                || (o instanceof Object[] && ((Object[]) o).length == 0) || (o instanceof Map && ((Map) o).size() == 0);
    }
}
