package yem.wmc.ydn.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.entity.cache.AppCache;
import kd.bos.entity.cache.IAppCache;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.OperationServiceHelper;
import yem.base.common.utils.HttpHelper;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static yem.wmc.ydn.utils.CommonUtils.getToken;

/**
 * @author 金亮
 * @date 2024/5/6 14:26
 * @relevantfile 海运接口 工具类
 * @description
 * @versions 1.0
 */
public class SeaTransportationUtils {

    /**
     * 船舶历史挂港
     *
     * @param poldate 启运时间(开始时间)
     * @param dtpdate 到港时间(结束时间)
     * @param mmsi    MMSI号
     * @return
     */
    public static String getPortofcall(Date poldate, Date dtpdate, String mmsi) {
        IAppCache appCache = AppCache.get("yem_ydn");//获取缓存
        String value1 = appCache.get("accessToken", String.class);
        String access_token = null;
        if (value1 != null) {
            access_token = value1;
        } else {
            access_token = getToken();
        }
        if (poldate == null || dtpdate == null || mmsi.isEmpty()) {
            return "启运时间,到港时间,MMSI号都不得为空";
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String poldateStr = sdf.format(poldate);
        String dtpdateStr = sdf.format(dtpdate);
        try {
            JSONObject requestJson = new JSONObject();
            requestJson.put("mmsi", mmsi.trim());
            requestJson.put("begin", poldateStr);
            requestJson.put("end", dtpdateStr);
            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);
            NewMiddlelayerdata(strReult,"船舶历史挂港",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 "插入数据失败";
                    } else {
                        return "插入数据成功，单据编号为:" + portdata.getString("billno");
                    }
                } else {
                    return dataOne.getString("message");
                }
            } else {
                return strReult;
            }
        } catch (Exception exception) {
            exception.printStackTrace();
            return exception.getMessage();
        }
    }

    /**
     * 港区数据订阅
     *
     * @param pkValue     单据主键id
     * @param referenceno 港区提单/订舱号
     * @param ieid        进出口标识
     * @param portcd      云当港口代码
     * @return
     */
    public static String getPortdatabooking(Object pkValue, String referenceno, String ieid, DynamicObject portcd) {
        IAppCache appCache = AppCache.get("yem_ydn");//获取缓存
        String value1 = appCache.get("accessToken", String.class);
        String access_token = null;
        if (value1 != null) {
            access_token = value1;
        } else {
            access_token = getToken();
        }
        if (portcd == null || ieid.isEmpty() || referenceno.isEmpty()) {
            return "港区提单/订舱号,进出口标识,云当港口都不得为空";
        }
        try {
            JSONObject JObject = new JSONObject();
            JObject.put("localkeyid", pkValue);
            JObject.put("referenceno", referenceno);
            JObject.put("portcd", portcd.getString("number"));
            JObject.put("ieid", ieid);
            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);
            NewMiddlelayerdata(Portdatabooking,"港区数据订阅",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) {
                        return "插入数据失败";
                    } else {
                        return "插入数据成功，单据编号为:" + portdatabooking.getString("billno");
                    }
                } else {
                    return Portdatabooking;
                }
            } else {
                if (body.containsKey("msg")) {
                    return body.getString("msg");
                } else {
                    return "插入数据失败";
                }
            }
        } catch (Exception exception) {
            exception.printStackTrace();
            return exception.getMessage();
        }
    }

    /**
     * 港区数据（港区数据订阅下载）
     *
     * @param referenceno 港区提单/订舱号
     * @param portcd      云当港口代码
     * @return
     */
    public static String getPortdata(String referenceno, DynamicObject portcd) {
        IAppCache appCache = AppCache.get("yem_ydn");//获取缓存
        String value1 = appCache.get("accessToken", String.class);
        String access_token = null;
        if (value1 != null) {
            access_token = value1;
        } else {
            access_token = getToken();
        }
        if (referenceno == null || referenceno.isEmpty()) {
            return "港区提单/订舱号,进出口标识,云当港口都不得为空";
        }
        try {
            JSONObject JObject = new JSONObject();
            JObject.put("referenceno", referenceno);
            JObject.put("portcd", portcd.getString("number"));
            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);
            NewMiddlelayerdata(Portdatabookingdownload,"港区数据订阅下载",param);
            JSONObject body = JSON.parseObject(Portdatabookingdownload);
            String code = body.getString("code");//获取状态
            if ("0".equals(code)) {
                JSONObject Data = JSONObject.parseObject(body.getString("data"));
                if (Data.getInteger("status") != 0) {
                    return Data.getString("message");
                }
                DynamicObject portdata = JsonToDataUtils.jsonToData("yem_ydn_portdata", Data, null);//
                if (portdata == null) {
                    return "插入数据失败";
                } else {
                    return "插入数据成功，单据编号为:" + portdata.getString("billno");
                }
            } else {
                if (body.containsKey("msg")) {
                    return body.getString("msg");
                } else {
                    return "插入数据失败";
                }
            }
        } catch (Exception exception) {
            exception.printStackTrace();
            return exception.getMessage();
        }
    }

    /**
     * 海运跟踪订阅
     *
     * @param pkValue     单据主键id
     * @param referenceno 港区提单/订舱号
     * @param ctnrno      上传订阅的箱号
     * @param carriercd   船东代码（云当代码）
     * @param pol         启运港
     * @param dtp         目的港
     */
    public static String getShiptracking(Object pkValue, String referenceno, String ctnrno, String carriercd, DynamicObject pol, DynamicObject dtp) {
        IAppCache appCache = AppCache.get("yem_ydn");//获取缓存
        String value1 = appCache.get("accessToken", String.class);
        String access_token = null;
        String message = null;
        if (value1 != null) {
            access_token = value1;
        } else {
            access_token = getToken();
        }
        if (carriercd == null || pol == null || dtp == null || (referenceno.isEmpty() && ctnrno.isEmpty())) {
            return "云当港口(船东代码),启运港,目的港都不得为空,港区提单/订舱号和上传订阅的箱号不得同时为空";
        }
        try {
            JSONObject JObject = new JSONObject();
            JObject.put("keyid", pkValue);
            JObject.put("carriercd", carriercd);
            JObject.put("referenceno", referenceno);
            JObject.put("ctnrno", ctnrno);//箱号
            JObject.put("pol", pol.getString("yem_enname"));
            JObject.put("dtp", pol.getString("yem_enname"));
            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);
            NewMiddlelayerdata(Portdatabookingdownload,"海运跟踪订阅",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;
                ArrayList<DynamicObject> list = new ArrayList<>();
                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++;
                            list.add(portdata);
                        }
                    } else {
                        return rowJsonObj.getString("message");
                    }
                }
                DynamicObject dynamicObject = list.get(0);
                return "共" + jsonResult.size() + "条数据,成功插入" + sum + "条数据,失败" + (jsonResult.size() - sum) + "条！第一条数据的单据编号为:" + dynamicObject.getString("billno");
            } else { //错误数据
                if (body.containsKey("msg")) {
                    return body.getString("msg");
                } else {
                    return "插入数据失败";
                }
            }
        } catch (Exception exception) {
            exception.printStackTrace();
            return exception.getMessage();
        }
    }

    /**
     * 海运跟踪下载 shipdownload
     *
     * @param pkValue     单据主键id
     * @param referenceno 港区提单/订舱号
     * @param ctnrno      上传订阅的箱号
     * @param carriercd   船东代码（云当代码）
     * @param pol         启运港
     * @param dtp         目的港
     */
    public static String getShipdownload(Object pkValue, String referenceno, String ctnrno, String carriercd, DynamicObject pol, DynamicObject dtp) {
        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();
        }
        if (carriercd == null || pol == null || dtp == null || (referenceno.isEmpty() && ctnrno.isEmpty())) {
            return "云当港口(船东代码),启运港,目的港都不得为空,港区提单/订舱号和上传订阅的箱号不得同时为空";
        }
        try {
            JSONObject JObject = new JSONObject();
            JObject.put("localkeyid", pkValue);
            JObject.put("carriercd", carriercd);
            JObject.put("referenceno", referenceno);
            JObject.put("ctnrno", ctnrno);//箱号
            JObject.put("pol", pol.getString("yem_enname"));
            JObject.put("dtp", dtp.getString("yem_enname"));
            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);
            NewMiddlelayerdata(Portdatabookingdownload,"海运跟踪下载",param);
            JSONObject body = JSON.parseObject(Portdatabookingdownload);
            String code = body.getString("code");//获取状态
            if ("0".equals(code)) {
                JSONArray data = body.getJSONArray("data");
                if (data.size() == 0) {
                    return "返回数据为空，请检查请求参数是否正确";
                }
//                JSONObject Data = data.getJSONObject(0);
                int sum = data.size();
                int succeedsum = sum;
                ArrayList<DynamicObject> list = new ArrayList<>();
                for (Object datum : data) {
                    JSONObject Data = (JSONObject) datum;
                    if (!Data.getBoolean("success")) {
                        return body.getString("msg");
                    }
                    DynamicObject portdata = JsonToDataUtils.jsonToData("yem_ydn_shipdownload", Data.getJSONObject("objlinertracking"), null);//
                    if (portdata == null) {
                        succeedsum--;
                    } else {
                        list.add(portdata);
                    }
                    if (list.size() > 0) {
                        DynamicObject dynamicObject = list.get(0);
                        return "共" + sum + "条数据，成功插入" + succeedsum + "条，失败" + (sum - succeedsum) + "条！第一条数据的单据编号为:" + dynamicObject.getString("billno");
                    } else {
                        return "共" + sum + "条数据，成功插入" + succeedsum + "条，失败" + (sum - succeedsum) + "条！";
                    }
                }
            } else { //错误数据
                if (body.containsKey("msg")) {
                    return body.getString("msg");
                } else {
                    return "插入数据失败";
                }
            }
        } catch (Exception exception) {
            exception.printStackTrace();
            return exception.getMessage();
        }
        return "插入数据失败";
    }


    public static void NewMiddlelayerdata(String msg,String type,String data) {
        DynamicObject bill= BusinessDataServiceHelper.newDynamicObject("yem_ydn_middlelayerdata");
        bill.set("yem_msg",msg);
        bill.set("yem_type",type);
        bill.set("yem_data",data);
        OperationResult operationResult = OperationServiceHelper.executeOperate("save", "yem_ydn_middlelayerdata", new DynamicObject[]{bill},
                OperateOption.create());
        boolean success = operationResult.isSuccess();


    }


}

