package com.unibuy.smartdevice.external;

import android.content.Context;
import android.os.Bundle;
import android.os.Message;

import androidx.core.app.NotificationCompat;

import com.unibuy.smartdevice.MyApp;
import com.unibuy.smartdevice.exception.ErrorCode;
import com.unibuy.smartdevice.exception.Logs;
import com.unibuy.smartdevice.exception.LogsParseException;
import com.unibuy.smartdevice.exception.LogsSettingEmptyException;
import com.unibuy.smartdevice.structure.GreenpayMerchantStructure;
import com.unibuy.smartdevice.structure.GreenpaySettingStructure;
import com.unibuy.smartdevice.tools.ApiPostMainScheduler;
import com.unibuy.smartdevice.tools.HandlerMain;
import com.unibuy.smartdevice.ui.dialog.CheckoutTapPayDialog;

import org.json.JSONException;
import org.json.JSONObject;

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

public class HttpTapPay {
    public enum PayType {
        LINE_PAY(30),
        JKO_PAY(31),
        EASY_PAY(32),
        PI_PAY(33),
        PLUS_PAY(34),
        ;
            /*
        myApp.PayType == 3 現金
        myApp.PayType == 3 this.txtHint.setText("請掃描條碼");
        myApp.PayType == 30 this.SwipeData = "LinePay";
        myApp.PayType == 31 this.SwipeData = "街口支付";
        myApp.PayType == 32 this.SwipeData = "悠遊付";
        myApp.PayType == 33 this.SwipeData = "Pi拍錢包";
        myApp.PayType == 34 this.SwipeData = "全盈+PAY";
    */
        private int type;

        public int getType() {
            return type;
        }

        PayType(int type) {
            this.type = type;
        }
    }
    private Logs logs;
    private Context context;
    public final int ConnectTimeout = 4000;
    public final int ReadTimeout = 30000;
    public final String BACKEND_NOTIFY_URL_EXAMPLE = "https://example.com/back-end-notify";
    public final String FRONTEND_REDIRECT_URL_EXAMPLE = "https://example.com/front-end-redirect";
    private final String TAPPAY_DOMAIN = "https://prod.tappaysdk.com";
    private final String TAPPAY_DOMAIN_SANDBOX = "https://sandbox.tappaysdk.com";
    public final String TAPPAY_PAY_BY_PRIME_URL = "/tpc/payment/pay-by-prime";
    private HandlerMain srcHandlerMain;

    public HandlerMain getSrcHandlerMain() {
        return srcHandlerMain;
    }

    public void checkMachineInfo() throws LogsSettingEmptyException {
        if (MyApp.getInstance().getMachine().getApiKey().isEmpty() ||
                MyApp.getInstance().getMachine().getMachineID().isEmpty()) {
            throw new LogsSettingEmptyException(logs, "machine data empty");
        }
    }

    //    public final String TAPPAY_LINEPAY_RESULT_CALLBACK_URI = "linepayexample://tech.cherri";
//    public String RESULT_CALLBACK_URI = TAPPAY_LINEPAY_RESULT_CALLBACK_URI;
//    public final String TAPPAY_EasyWalle_RESULT_CALLBACK_URI = "ewexample://ew.app:8888/test";
//    public final String TAPPAY_JkoPay_RESULT_CALLBACK_URI = "jkoexample://jko.uri:8888/test";
//    public final String TAPPAY_PiWallet_RESULT_CALLBACK_URI = "piwalletexample://tech.cherri.piwalletexample";
//    public final String TAPPAY_PlusPay_RESULT_CALLBACK_URI = "tpdirectexamplepluspay://tech.cherri/myaccount/detail";
    //-------------- 設定 -----------------
//    public String PARTNER_KEY = "partner_v1T5HZGz65di4GAMVAtvN6rCPzlpdDKNv3It1BNog0WTxPUgKG1S3KSq";
//    public String APP_KEY = "app_F70rEjuAAyvj1BeJck9HeyF1EJTzdknTPmXMSlodZKwvM8PoniUMXbqP8l9m";
//    public Integer APP_ID = 136289;
    //-------------- 設定 -----------------
//    public String CTBC_MERCHANT_ID = "wilson461973_CTBC"; //奇怪的帳號
//    public String NCCC_MERCHANT_ID = "wilson461973_NCCC"; //奇怪的帳號
//    public String TAISHIN_MERCHANT_ID = "wilson461973_TAISHIN"; //奇怪的帳號
//    public String ESUN_MERCHANT_ID = "wilson461973_ESUN"; //奇怪的帳號
//    public String GPUSD_MERCHANT_ID = "wilson461973_GP_USD_Only"; //奇怪的帳號
//    public String LINE_MERCHANT_ID = "wilson461973_LINEPAY";
//    public String JKO_MERCHANT_ID = "wilson461973_JKOPAY";
//    public String EASY_MERCHANT_ID = "wilson461973_EASY_WALLET";
//    public String PI_MERCHANT_ID = "wilson461973_PI_WALLET_Manual_CAP";
//    public String PS_MERCHANT_ID = "wilson461973_PLUSPAY";
//    public String DIRECT_MERCHANT_ID = "";
//    public String APPLE_MERCHANT_ID = "";
//    public String GOOGLE_MERCHANT_ID = "";
//    public String SAMSUNG_MERCHANT_ID = "";
//    public String ATOME_MERCHANT_ID = "";

//    public static boolean isEnabled() {
//        GreenpaySettingStructure greenpaySetting = MyApp.getInstance().getGreenpaySetting();
//        GreenpayMerchantStructure greenpayMerchant = MyApp.getInstance().getGreenpayMerchant();
//
//        boolean hasMerchantID = (greenpayMerchant.getLineMerchantId().isEmpty()
//                && greenpayMerchant.getJkoMerchantId().isEmpty()
//                && greenpayMerchant.getEasyMerchantId().isEmpty()
//                && greenpayMerchant.getPiMerchantId().isEmpty()
//                && greenpayMerchant.getPsMerchantId().isEmpty()
//                && greenpayMerchant.getDirectMerchantId().isEmpty()
//                && greenpayMerchant.getAppleMerchantId().isEmpty()
//                && greenpayMerchant.getGoogleMerchantId().isEmpty()
//                && greenpayMerchant.getSamsungMerchantId().isEmpty()
//                && greenpayMerchant.getAtomeMerchantId().isEmpty()) ? false : true;
//
//        return (!hasMerchantID
//                || greenpaySetting.getPartnerKey().isEmpty()
//                || greenpaySetting.getAppId().isEmpty()) ? false : true;
//    }

    public HttpTapPay(HandlerMain srcHandlerMain) {
        this.logs = new Logs(this.getClass());
        this.srcHandlerMain = srcHandlerMain;
    }
    private boolean isSandbox(String merchantId) {
        return merchantId.contains("_LINEPAY") ||
                merchantId.contains("_JKOPAY") ||
                merchantId.contains("_EASY_WALLET") ||
                merchantId.contains("_PI_WALLET") ||
                merchantId.contains("_PLUSPAY") ||
                merchantId.contains("_ATOME");
    }
    private String getUrlString(String urlString, String merchantId) {
        String domainUrlString = isSandbox(merchantId) ? TAPPAY_DOMAIN_SANDBOX : TAPPAY_DOMAIN;
        return domainUrlString + urlString;
    }

//    private void checkMachineInfo() throws LogsSettingEmptyException {
//        if (MyApp.getInstance().getMachine().getApiKey().isEmpty() ||
//                MyApp.getInstance().getMachine().getMachineID().isEmpty()) {
//            throw new LogsSettingEmptyException(logs, "machine data empty");
//        }
//    }

    /*
        <item>Unibuy,https://unibuy.com.tw/Unibuy/api/app/,KahnEwjhfDBHUYS7,AAT</item>
        <item>Beast,https://bkstore.com.tw/BeastKingdom/api/app/,KahnEwjhfDBHUYS7,野獸國</item>
        <item>Lever,https://hysi.com.tw/lever/api/app/,KahnEwjhfDBHUYS7,銓寶</item>
        <item>Love69,https://unibuy.com.tw/Love69sexy/api/app/,K232E91hHDBgUsx2,格子機</item>
        <item>Test,http://hysi.com.tw/Unibuy/api/app/,KahnEwjhfDBHUYS7,測試版</item>
        <item>Z0,https://unibuy.com.tw/Unibuy/api/app/,KahnEwjhfDBHUYS7,喜鵲[通行碼限定]版</item>
        <item>Z1,https://unibuy.com.tw/Unibuy/api/app/,KahnEwjhfDBHUYS7,喜鵲[香菸問卷]版</item>
        <item>Z2,https://unibuy.com.tw/Unibuy/api/app/,KahnEwjhfDBHUYS7,喜鵲[點數兌換]版</item>
     */

//    public String getPrimeUrlByWeb(int payType, String merchantId, String products, int totalPrice) {
//        String urlString = getPrimeUrl(payType, merchantId, products, totalPrice);
//
//        String timeStamp = new SimpleDateFormat("yyyyMMddhhmmss", Locale.US).format(new Date());
//        String callBackStr = MyApp.getInstance().getMachine().getMachineID() + timeStamp;
//        urlString += "&order_number=" + callBackStr;
//
//        return urlString;
//    }

    public String getPrimeUrl(String products, int totalPrice) throws LogsSettingEmptyException {
        checkMachineInfo();

        String owner = "AAT";
        int payType = MyApp.getInstance().getReportFlowInfoData().getFlowType();
        GreenpaySettingStructure greenpaySetting = MyApp.getInstance().getGreenpaySetting();
        String greenpayMerchantId = MyApp.getInstance().getMachine().getMachineID();
        logs.info("aaaaaaaaaaaaaaaaaaaaaa1"+ MyApp.getInstance().getGreenpayMerchant().getLineMerchantId());
        logs.info("aaaaaaaaaaaaaaaaaaaaaa2"+ MyApp.getInstance().getGreenpayMerchant().getJkoMerchantId());
        logs.info("aaaaaaaaaaaaaaaaaaaaaa3"+ MyApp.getInstance().getGreenpayMerchant().getPiMerchantId());
        logs.info("aaaaaaaaaaaaaaaaaaaaaa4"+ MyApp.getInstance().getGreenpayMerchant().getPsMerchantId());
        logs.info("aaaaaaaaaaaaaaaaaaaaaa5"+ MyApp.getInstance().getGreenpayMerchant().getEasyMerchantId());
        switch (payType) {
            case 30:
                if (MyApp.getInstance().getGreenpayMerchant() != null && !MyApp.getInstance().getGreenpayMerchant().getLineMerchantId().isEmpty()) {
                    greenpayMerchantId = MyApp.getInstance().getGreenpayMerchant().getLineMerchantId();
                } else {
                    return "";
                }
                break;
            case 31:
                if (MyApp.getInstance().getGreenpayMerchant() != null && !MyApp.getInstance().getGreenpayMerchant().getJkoMerchantId().isEmpty()) {
                    greenpayMerchantId = MyApp.getInstance().getGreenpayMerchant().getJkoMerchantId();
                } else {
                    return "";
                }
                break;
            case 32:
                if (MyApp.getInstance().getGreenpayMerchant() != null && !MyApp.getInstance().getGreenpayMerchant().getEasyMerchantId().isEmpty()) {
                    greenpayMerchantId = MyApp.getInstance().getGreenpayMerchant().getEasyMerchantId();
                } else {
                    return "";
                }
                break;
            case 33:
                if (MyApp.getInstance().getGreenpayMerchant() != null && !MyApp.getInstance().getGreenpayMerchant().getPiMerchantId().isEmpty()) {
                    greenpayMerchantId = MyApp.getInstance().getGreenpayMerchant().getPiMerchantId();
                } else {
                    return "";
                }
                break;
            case 34:
                if (MyApp.getInstance().getGreenpayMerchant() != null && !MyApp.getInstance().getGreenpayMerchant().getPsMerchantId().isEmpty()) {
                    greenpayMerchantId = MyApp.getInstance().getGreenpayMerchant().getPsMerchantId();
                } else {
                    return "";
                }
                break;
            default:
                logs.info("未設定TapPay商店代碼：" + payType);
                return "";
        }

        StringBuilder s = new StringBuilder("");
        //s.append("https://unibuy.com.tw/tools/bROPi9rxqM6EyxBd.html");
        s.append("https://unibuy.com.tw/chi-hai/tools/bROPi9rxqM6EyxBd.html");
        s.append("?key=");
        s.append(MyApp.getInstance().getMachine().getApiKey());
        s.append("&partner_key=");
        s.append(greenpaySetting.getPartnerKey());
        s.append("&APP_KEY=");
        s.append(greenpaySetting.getAppKey());
        s.append("&APP_ID=");
        s.append(greenpaySetting.getAppId());
        s.append("&merchant_id=");
        s.append(greenpayMerchantId); //廠商ID
        s.append("&SERVER_TYPE=");
        s.append(isSandbox(greenpayMerchantId) ? "sandbox" : "production");
        s.append("&details=");
        s.append(products.replace("\"", "\\\"")); //產品名稱
        s.append("&amount=");
        s.append(totalPrice); //總金額
        s.append("&type=");
        s.append(payType);

        if (owner.equals("Beast")) {
            s.append("&api_type=1"); //野獸國自己的平台
        } else {
            s.append("&api_type=0"); //AAT自己的平台
        }

        s.append("&order_number=");
        s.append(MyApp.getInstance().getReportFlowInfoData().getOrderId());

        logs.info("prime:" + s.toString());

        return s.toString();
    }

    /*
        myApp.PayType == 3 現金
        myApp.PayType == 3 this.txtHint.setText("請掃描條碼");
        myApp.PayType == 30 this.SwipeData = "LinePay";
        myApp.PayType == 31 this.SwipeData = "街口支付";
        myApp.PayType == 32 this.SwipeData = "悠遊付";
        myApp.PayType == 33 this.SwipeData = "Pi拍錢包";
        myApp.PayType == 34 this.SwipeData = "全盈+PAY";
    */

    public void newOrder(String products, int totalPrice, ApiPostMainScheduler apiPostRunMain) throws LogsParseException, LogsSettingEmptyException {
        checkMachineInfo();
        String phone = "";

        String prime = getPrimeUrl(products, totalPrice);

        try {
//            String timeStamp = new SimpleDateFormat("yyyyMMddhhmmss", Locale.US).format(new Date());
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("prime", prime);
            jsonObject.put("partner_key", MyApp.getInstance().getGreenpaySetting().getPartnerKey());
            jsonObject.put("merchant_id", MyApp.getInstance().getMachine().getMachineID());
            jsonObject.put("order_number", MyApp.getInstance().getReportFlowInfoData().getOrderId());
            jsonObject.put("details", products);
            jsonObject.put("amount", totalPrice);
            JSONObject cardHolderJO = new JSONObject();
            cardHolderJO.put("phone_number", phone);
            cardHolderJO.put("name", "");
            cardHolderJO.put("email", "");
            jsonObject.put("cardholder", cardHolderJO);
            JSONObject resultUrlJO = new JSONObject();
            resultUrlJO.put("frontend_redirect_url", FRONTEND_REDIRECT_URL_EXAMPLE);
            resultUrlJO.put("backend_notify_url", BACKEND_NOTIFY_URL_EXAMPLE);
            jsonObject.put("result_url", resultUrlJO);
            logs.info("json:" + jsonObject.toString());
            apiPostRunMain.start(getUrlString(TAPPAY_PAY_BY_PRIME_URL, MyApp.getInstance().getMachine().getMachineID()), jsonObject.toString(), null, null);
        } catch (JSONException e) {
            throw new LogsParseException(logs, ErrorCode.JSON_FORMAT_ERROR);
        }
    }

//    public void doRefund(String tradeID, String merchant_id, ApiPostMainScheduler apiPostMainScheduler) throws JSONException {
//        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("partner_key", MyApp.getInstance().getGreenpaySetting().getPartnerKey());
//        jsonObject.put("rec_trade_id", tradeID);
//        apiPostMainScheduler.start(getUrlString("/tpc/transaction/refund", merchant_id), jsonObject.toString(), null, null);
//    }

    public void getRecord() throws LogsParseException, LogsSettingEmptyException {
        getRecord(new ApiPostMainScheduler(getSrcHandlerMain()) {
            @Override
            protected HandlerMain setHandlerMain() {
                return getSrcHandlerMain();
            }

            @Override
            protected Class<?> setCls() {
                return getClass();
            }

            @Override
            public void response(int responseCode, String receive, HandlerMain handlerMain) {
                if (responseCode == 200) {
                    try {
                        JSONObject jsonObjectByReceive = new JSONObject(receive);
                        getLogs().info(jsonObjectByReceive.toString());

                        if (jsonObjectByReceive.getInt(NotificationCompat.CATEGORY_STATUS) == 2) {
                            if (jsonObjectByReceive.getInt("number_of_transactions") == 0) {
                                //五秒後重新詢問
                                getSrcHandlerMain().send(getClass().getSimpleName(), CheckoutTapPayDialog.Option.TRANSACTION_AGAIN.getOption(), "五秒後再次查詢");
                                return;
                            }
                            JSONObject j = jsonObjectByReceive.getJSONArray("trade_records").getJSONObject(0);
                            int n = j.getInt("record_status");

                            switch (n) {
                                case -1:
                                    //TapPay交易錯誤
                                    getSrcHandlerMain().send(getClass().getSimpleName(), CheckoutTapPayDialog.Option.TRANSACTION_FAILED.getOption(), "TRANSACTION_SUCCESSFUL");
                                    break;
                                case 0:
                                case 1:
                                    //付款成功
                                    String message = j.toString().replace("\t", "ⓣ");
                                    getSrcHandlerMain().send(getClass().getSimpleName(), CheckoutTapPayDialog.Option.TRANSACTION_SUCCESSFUL.getOption(), message);
                                    return;
                                case 2:
                                    //TapPay部分退款
                                    getSrcHandlerMain().send(getClass().getSimpleName(), CheckoutTapPayDialog.Option.TRANSACTION_FAILED.getOption(), "TapPay部分退款");
                                    break;
                                case 3:
                                    //TapPay完全退款
                                    getSrcHandlerMain().send(getClass().getSimpleName(), CheckoutTapPayDialog.Option.TRANSACTION_FAILED.getOption(), "TapPay完全退款");
                                    break;
                                case 4:
                                    //五秒後重新詢問
                                    getSrcHandlerMain().send(getClass().getSimpleName(), CheckoutTapPayDialog.Option.TRANSACTION_AGAIN.getOption(), "五秒後再次查詢");
                                    return;
                                case 5:
                                    //TapPay取消付款
                                    getSrcHandlerMain().send(getClass().getSimpleName(), CheckoutTapPayDialog.Option.TRANSACTION_FAILED.getOption(), "TapPay取消付款");
                                    break;
                                default:
                                    //TapPay(" + n + ")"
                                    getSrcHandlerMain().send(getClass().getSimpleName(), CheckoutTapPayDialog.Option.TRANSACTION_FAILED.getOption(), "TapPay(\" + n + \")\"");
                                    break;
                            }
                        }
                    } catch (JSONException e) {
                        getLogs().error(ErrorCode.JSON_FORMAT_ERROR, e.getLocalizedMessage());
                    }
                }
            }
        });
    }

    private void getRecord(ApiPostMainScheduler apiPostMainScheduler) throws LogsParseException, LogsSettingEmptyException {
        checkMachineInfo();

        try {
            String merchantId = MyApp.getInstance().getMachine().getMachineID();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("partner_key", MyApp.getInstance().getGreenpaySetting().getPartnerKey());
            JSONObject filtersJO = new JSONObject();
            filtersJO.put("order_number", MyApp.getInstance().getReportFlowInfoData().getOrderId());

//            Date dt = new Date();
//            dt.setTime(1698905493742L);
//            JSONObject timeJO = new JSONObject();
//            timeJO.put("start_time", 1698905493742L - 3000000);
//            timeJO.put("end_time", 3000000 + 1698905493742L);

            Date dt = new Date();
            long baseTime = dt.getTime(); // 取得現在的毫秒時間
            long thirtyMinutesMillis = 30 * 60 * 1000; // 30分鐘 = 1800000 毫秒
            JSONObject timeJO = new JSONObject();
            timeJO.put("start_time", baseTime - thirtyMinutesMillis); // 30分鐘前
            timeJO.put("end_time", baseTime + thirtyMinutesMillis);   // 30分鐘後
            jsonObject.put("time", timeJO);
            jsonObject.put("filters", filtersJO);
            Map<String, String> mapByRequestProperty = new HashMap<>();
            mapByRequestProperty.put("x-api-key",  MyApp.getInstance().getGreenpaySetting().getPartnerKey());
            apiPostMainScheduler.start(getUrlString("/tpc/transaction/query", merchantId), jsonObject.toString(), null, null, mapByRequestProperty);
        } catch (JSONException e) {
            throw new LogsParseException(logs, ErrorCode.JSON_FORMAT_ERROR);
        }
    }

    public void getRecord(String orderNumber) throws LogsSettingEmptyException, JSONException {
        getRecord(orderNumber, new ApiPostMainScheduler(getSrcHandlerMain()) {
            @Override
            protected HandlerMain setHandlerMain() {
                return getSrcHandlerMain();
            }

            @Override
            protected Class<?> setCls() {
                return getClass();
            }

            @Override
            public void response(int responseCode, String receive, HandlerMain handlerMain) {
                if (responseCode == 200) {
                    try {
                        JSONObject jsonObject = new JSONObject(receive);
                        if (jsonObject.getInt(NotificationCompat.CATEGORY_STATUS) == 2) {
                            jsonObject.getJSONArray("trade_records").getJSONObject(0);
                        }
                    } catch (JSONException e) {
                        getLogs().error(ErrorCode.JSON_FORMAT_ERROR, e.getLocalizedMessage());
                    }
                }
            }
        });
    }

    private void getRecord(String orderNumber, ApiPostMainScheduler apiPostMainScheduler) throws JSONException, LogsSettingEmptyException {
        checkMachineInfo();

        String merchantId = MyApp.getInstance().getMachine().getMachineID();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("partner_key", MyApp.getInstance().getGreenpaySetting().getPartnerKey());
        JSONObject filtersJO = new JSONObject();
        filtersJO.put("order_number", orderNumber);
        long now = new Date().getTime();
        JSONObject timeJO = new JSONObject();
        timeJO.put("start_time", now - 300000);
        timeJO.put("end_time", now);
        jsonObject.put("time", timeJO);
        jsonObject.put("filters", filtersJO);
        apiPostMainScheduler.start(getUrlString("/tpc/transaction/query", merchantId), jsonObject.toString(), null, null);
    }
}
