package com.unibuy.smartdevice.ui.dialog;

import android.content.Context;

import androidx.recyclerview.widget.LinearLayoutManager;

import com.unibuy.smartdevice.DialogAbstract;
import com.unibuy.smartdevice.MyApp;
import com.unibuy.smartdevice.databinding.DialogCmuhTakeMedicineBinding;
import com.unibuy.smartdevice.external.HttpAPI;
import com.unibuy.smartdevice.tools.HandlerMain;
import com.unibuy.smartdevice.tools.HandlerMainCountdown;
import com.unibuy.smartdevice.tools.ToastHandlerMain;
import com.unibuy.smartdevice.tools.Tools;
import com.unibuy.smartdevice.ui.recycler.RecyclerDialogTakeMedicineListAdpter;

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

import java.util.HashMap;
import java.util.Map;

public class TakeMedicineDialog extends DialogAbstract {
    public enum Option {
        TOAST(0),
        COUNTDOWN_CANCEL(1),
        SET_COUNTDOWN_TEXT(2),
        SET_PRICE(3),
        RESET_COUNTDOWM(4),
        RESET_COUNTDOWM_TOAST(5),
        CHANGE_DISPATCH(6),
        REPORT_FLOW(8),
        ;

        private int option;

        public int getOption() {
            return option;
        }

        Option(int option) {
            this.option = option;
        }
    }

    public static final Map<Integer, Option> optionMap = new HashMap<>();
    static {
        for (Option option : Option.values()) {
            optionMap.put(option.getOption(), option);
        }
    }

    @Override
    protected Context setCtx() {
        return getContext();
    }

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

    private boolean isChangeDispatch;
    private boolean isRun;

    boolean isResponse;
    private HttpAPI httpAPI;

    @Override
    protected HandlerMain setHandlerMain() {
        return new ToastHandlerMain(getContext(), getLogs()) {
            @Override
            protected void execute(Context context, int commandCode, String message) {
                if (MyApp.getInstance().getBuyList().size() <= 0) {
                    getSrcHandlerMain().start("這裡會出現貨道無貨提示警語","@再刷一次，若不行，請洽發藥窗口!");
                    dialogCancel();
                } else {
                    Option option = optionMap.get(commandCode);

                    switch (option) {
                        case TOAST:
                                super.execute(context, commandCode, message);
                            break;
                        case COUNTDOWN_CANCEL:
                                cancelOnThreadCountdown();
                            break;
                        case SET_COUNTDOWN_TEXT:
                                setButtonCancelText(Integer.valueOf(message));
                            break;
                        case SET_PRICE:
                                closeDialogCountdown.setCountdown(40);
                            break;
                        case RESET_COUNTDOWM:
                                closeDialogCountdown.setCountdown(40);
                            break;
                        case RESET_COUNTDOWM_TOAST:
                                super.execute(context, commandCode, message);
                                closeDialogCountdown.setCountdown(40);
                            break;
                        case CHANGE_DISPATCH:
                            changeDispatch();
                            break;
                        case REPORT_FLOW:
                            getLogs().info(MyApp.getInstance().getReportFlowInfoData().toString());
                            if (MyApp.getInstance().getReportFlowInfoData().getFlowStatusType() == 0) {
                                start(getSrcClassName(), CheckoutCashDialog.Option.CHANGE_BUY.getOption(), "change buy");
                            } else {
                                if (MyApp.getInstance().getReportFlowInfoData().getInvoiceInfo().isEmpty()) {
                                    start(getSrcClassName(), CheckoutCashDialog.Option.CHANGE_DISPATCH.getOption(), "change dispatch");
                                } else {
                                    start(getSrcClassName(), CheckoutCashDialog.Option.POST_INVOICE.getOption(), "post invoice");
                                }
                            }

//                            new HandlerMainCountdown(this) {
//                                @Override
//                                protected Class<?> setCls() {
//                                    return this.getClass();
//                                }
//
//                                @Override
//                                protected HandlerMain setHandlerMain() {
//                                    return getSrcHandlerMain();
//                                }
//
//                                @Override
//                                protected void execute(long countdown, HandlerMain handlerMain) {
//
//                                }
//
//                                @Override
//                                protected void close(HandlerMain handlerMain) {
//                                    if (MyApp.getInstance().getReportFlowInfoData().getFlowStatusType() == 0) {
//                                        handlerMain.start(getSrcClassName(), CheckoutCashDialog.Option.CHANGE_BUY.getOption(), "change buy");
//                                    } else {
//                                        if (MyApp.getInstance().getReportFlowInfoData().getInvoiceInfo().isEmpty()) {
//                                            handlerMain.start(getSrcClassName(), CheckoutCashDialog.Option.CHANGE_DISPATCH.getOption(), "change dispatch");
//                                        } else {
//                                            handlerMain.start(getSrcClassName(), CheckoutCashDialog.Option.POST_INVOICE.getOption(), "post invoice");
//                                        }
//                                    }
//                                }
//                            }.start(2);

                            break;
                       }
                  }
            }
        };
    }

    private DialogCmuhTakeMedicineBinding binding;
    private RecyclerDialogTakeMedicineListAdpter recyclerDialogTakeMedicineListAdpter;
    private CloseDialogOnThreadHandler closeDialogCountdown;

    public TakeMedicineDialog(Context context, HandlerMain srcHandlerMain) {
        super(context, srcHandlerMain);
        getLogs().info("open:" + getClass().getSimpleName());
    }

    @Override
    protected void onCreate(Context context) {
        binding = DialogCmuhTakeMedicineBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        this.isChangeDispatch = true;
        this.isRun = true;
        isResponse = true;
        this.httpAPI = new HttpAPI(getHandlerMain());

        this.recyclerDialogTakeMedicineListAdpter = new RecyclerDialogTakeMedicineListAdpter(getCtx(), MyApp.getInstance().getBuyList(), getHandlerMain());
        this.binding.recyclerDialogBuyList.setAdapter(recyclerDialogTakeMedicineListAdpter);
        this.binding.recyclerDialogBuyList.setLayoutManager(new LinearLayoutManager(context));

        MyApp.getInstance().initialReportData();
        MyApp.getInstance().getReportFlowInfoData().setOrderId(Tools.generateTimeBasedUUID());
        MyApp.getInstance().getPostInvoiceByGreenData().setOrderId(MyApp.getInstance().getReportFlowInfoData().getOrderId());

        String decryptedStr = MyApp.getInstance().getDecryptedData();
        JSONObject jsonObject = null;
        try {
            jsonObject = new JSONObject(decryptedStr);
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
        binding.tvHostId.setText("管理單位ID："+jsonObject.optString("HOSP_ID"));
        binding.tvSn.setText("序號："+jsonObject.optString("SN"));
        binding.tvName.setText("姓名："+jsonObject.optString("NAME"));
        binding.tvDrgno.setText("領藥號："+jsonObject.optString("DRGNO"));
        binding.tvData.setText("備註："+jsonObject.optString("DATA"));
        binding.tvPrintTime.setText("列印時間："+jsonObject.optString("PRINT_TIME"));

        this.binding.buttonAddProduct.setOnClickListener(v -> gotoAddProduct());
        //this.binding.buttonCancel.setOnClickListener(v -> dialogCancel());

        closeDialogCountdown = new CloseDialogOnThreadHandler(getHandlerMain());
        closeDialogCountdown.start(40);

//        if (MyApp.getInstance().getDevSet().isShoppingCar()) {
//            binding.buttonAddProduct.setVisibility(View.VISIBLE);
//        } else {
//            binding.buttonAddProduct.setVisibility(View.GONE);
//        }
    }

    public void gotoAddProduct() {
        //getSrcHandlerMain().start(getClass().getSimpleName(), FontendActivity.Option.ADD_PRODUCT.getOption(), "請在40秒內完成加購動作");
        changeDispatch();
        closeDialogCountdown.shutdown();
        cancel();
    }

    public void changeDispatch() {
        if (isChangeDispatch){
            isRun = false;
            isChangeDispatch = false;
            //closeMoneyType();
            closeDialogCountdown.shutdown();
            changeDialog(DispatchDialog.class);
        }
    }

    public void dialogCancel() {
        closeDialogCountdown.shutdown();
        int buyListSize = MyApp.getInstance().getBuyList().size();
        MyApp.getInstance().getBuyList().clear();
        if (buyListSize > 0) {
            recyclerDialogTakeMedicineListAdpter.notifyItemRangeRemoved(0, buyListSize);
        }
        cancel();
    }



    public void cancelOnThreadCountdown() {
        int buyListSize = MyApp.getInstance().getBuyList().size();
        MyApp.getInstance().getBuyList().clear();
        if (buyListSize > 0) {
            recyclerDialogTakeMedicineListAdpter.notifyItemRangeRemoved(0, buyListSize);
        }
        getTools().dialogClose();
        cancel();
    }

    public void setButtonCancelText(long countdown) {
        binding.buttonCancel.setText("取消("+countdown+")");
    }

    public static class CloseDialogOnThreadHandler extends HandlerMainCountdown {
        public CloseDialogOnThreadHandler(HandlerMain handlerMain) {
            super(handlerMain);
        }

        @Override
        protected HandlerMain setHandlerMain() {
            return getSrcHandlerMain();
        }

        @Override
        protected void close(HandlerMain handlerMain) {
            handlerMain.start(getClass().getSimpleName(), Option.COUNTDOWN_CANCEL.getOption(), "close dialog");
        }

        @Override
        protected void execute(long countdown, HandlerMain handlerMain) {
            handlerMain.start(getClass().getSimpleName(), Option.SET_COUNTDOWN_TEXT.getOption(), String.valueOf(countdown));
        }

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