package com.gingersoft.gsa.cloud.table.mvp.ui.activity.orderManager;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.gingersoft.gsa.cloud.common.constans.OrderTypeConstans;
import com.gingersoft.gsa.cloud.common.logan.LoganManager;
import com.gingersoft.gsa.cloud.common.utils.AppDevices;
import com.gingersoft.gsa.cloud.common.utils.LanguageUtils;
import com.gingersoft.gsa.cloud.common.utils.time.TimeUtils;
import com.gingersoft.gsa.cloud.order.commodity.OrderDetail;
import com.gingersoft.gsa.cloud.order.contract.OrderStatusContract;
import com.gingersoft.gsa.cloud.pay.bean.PayMethod;
import com.gingersoft.gsa.cloud.pay.bean.PosActionStatusExceptionParam;
import com.gingersoft.gsa.cloud.pay.pos.fragment.PosActionStatusExceptionFragment;
import com.gingersoft.gsa.cloud.table.R;
import com.gingersoft.gsa.cloud.table.R2;
import com.gingersoft.gsa.cloud.table.di.component.DaggerOrderDetailComponent;
import com.gingersoft.gsa.cloud.table.mvp.action.order.CancelOrder;
import com.gingersoft.gsa.cloud.table.mvp.action.order.RefundOrder;
import com.gingersoft.gsa.cloud.table.mvp.action.order.TipsOrder;
import com.gingersoft.gsa.cloud.table.mvp.contract.OrderDetailContract;
import com.gingersoft.gsa.cloud.table.mvp.model.bean.response.OrderManagerResponse;
import com.gingersoft.gsa.cloud.table.mvp.model.utils.OrderAssemblyUtil;
import com.gingersoft.gsa.cloud.table.mvp.presenter.orderManager.OrderDetailPresenter;
import com.gingersoft.gsa.cloud.table.mvp.ui.adapter.OrderCenterDetailFoodAdapter;
import com.gingersoft.gsa.cloud.table.mvp.ui.adapter.OrderCenterMoneyAdapter;
import com.gingersoft.gsa.cloud.ui.bean.view.SectionTextItem3;
import com.gingersoft.gsa.cloud.ui.widget.dialog.LoadingDialog;
import com.jess.arms.base.BaseFragmentActivity;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.qmuiteam.qmui.alpha.QMUIAlphaButton;
import com.qmuiteam.qmui.widget.QMUITopBar;

import org.simple.eventbus.Subscriber;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.jess.arms.utils.Preconditions.checkNotNull;


/**
 * ================================================
 * Description: 訂單詳情頁#顯示單條該餐廳下已結賬單
 * <p>
 * Created by MVPArmsTemplate on 03/13/2020 14:29
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
public class OrderDetailActivity extends BaseFragmentActivity<OrderDetailPresenter> implements OrderDetailContract.View {

    @BindView(R2.id.topbar)
    QMUITopBar mTopBar;

    @BindView(R2.id.rl_container)
    FrameLayout rl_container;
    @BindView(R2.id.tv_reload_exception_status)
    TextView tv_reload_exception_status;

    @BindView(R2.id.scrollview)
    NestedScrollView scrollview;
    @BindView(R2.id.tv_table_name)
    TextView tv_table_name;
    @BindView(R2.id.tv_people_num)
    TextView tv_people_num;
    @BindView(R2.id.tv_order_num)
    TextView tv_order_num;
    @BindView(R2.id.tv_open_time)
    TextView tv_open_time;
    @BindView(R2.id.tv_pay_time)
    TextView tv_pay_time;

    @BindView(R2.id.tv_food_detail_text)
    TextView tv_food_detail_text;
    @BindView(R2.id.recycler_food)
    RecyclerView recycler_food;
    @BindView(R2.id.recycler_order_moeny)
    RecyclerView recycler_order_moeny;
    @BindView(R2.id.recycler_pay_method)
    RecyclerView recycler_pay_method;

    @BindView(R2.id.tv_total_text)
    TextView tv_total_text;
    @BindView(R2.id.tv_total_money_text)
    TextView tv_total_money_text;

    @BindView(R2.id.tv_total)
    TextView tv_total;
    @BindView(R2.id.tv_total_money)
    TextView tv_total_money;

    @BindView(R2.id.btn_print_order)
    QMUIAlphaButton btn_print_order;
    @BindView(R2.id.btn_tips)
    QMUIAlphaButton btn_tips;
    @BindView(R2.id.btn_refund)
    QMUIAlphaButton btn_refund;
    @BindView(R2.id.btn_cancel_order)
    QMUIAlphaButton btn_cancel_order;
    @BindView(R2.id.btn_modify_order)
    QMUIAlphaButton btn_modify_order;

    @BindView(R2.id.ll_bottom)
    LinearLayout ll_bottom;
    @BindView(R2.id.tv_order_status)
    TextView tv_order_status;

    private OrderManagerResponse mOrderDetailItem;
    private List<OrderDetail> mOrderDetailList;

    private OrderCenterDetailFoodAdapter mOrderCenterDetailFoodAdapter;
    private List<SectionTextItem3> mOrderCenterDetailFoodList = new ArrayList<>();

    private OrderCenterMoneyAdapter mOrderCenterMoneyAdapter;
    private List<SectionTextItem3> mOrderCenterMoneyList = new ArrayList<>();

    private OrderCenterMoneyAdapter mOrderDetailPayMethodAdapter;
    private List<SectionTextItem3> mOrderCenterPayMethodList = new ArrayList<>();

    @Override
    public void setupActivityComponent(@NonNull AppComponent appComponent) {
        DaggerOrderDetailComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .view(this)
                .build()
                .inject(this);
    }

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_order_detail; //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        scrollview.post(new Runnable() {
            @Override
            public void run() {
                scrollview.scrollTo(0, 0);
            }
        });

        mOrderDetailList = OrderAssemblyUtil.assemblyOrder(OrderDetail.orderTransOrderDetails(mOrderDetailItem.getOrderDetails()));

        initOrderItemAdapter();
        updateOrderItems(mOrderDetailItem, mOrderDetailList);
        initOrderDetail(mOrderDetailItem);
        setBtnVisible();
        btn_refund.setVisibility(View.GONE);
    }

    @Subscriber(tag = PosActionStatusExceptionFragment.REFREAFSH_ORDER_EVENT)
    private void refreafshOrder(boolean refreafsh) {
        refreafshOrderDetail();
    }

    @OnClick({R2.id.btn_print_order, R2.id.btn_cancel_order, R2.id.btn_modify_order, R2.id.btn_tips, R2.id.btn_refund})
    public void onClick(View v) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            LoganManager.w_order(TAG, LoganManager.EVENT_CLICK, "按鈕：" + v.getTransitionName());
        }
        int id = v.getId();
        if (id == R.id.btn_print_order) {
            mPresenter.printOrder(this, mOrderDetailItem);
        } else if (id == R.id.btn_modify_order) {
            if (mOrderDetailItem.getRestaurantTable() == null) {
                showMessage("餐檯不存在,無法修改訂單");
                return;
            }
            mPresenter.modifyOrder(this, mOrderDetailItem);
        } else if (id == R.id.btn_cancel_order) {
            mPresenter.orderCancel(this, mOrderDetailItem, new CancelOrder.OnCancelListener() {
                @Override
                public void cancel(long orderId) {
                    mPresenter.cancelOrder(orderId);
                }

                @Override
                public void refeshOrders() {
                    refreafshOrderDetail();
                }
            });
        } else if (id == R.id.btn_refund) {
            if (mOrderDetailItem.withHywebPay()) {
                mPresenter.orderRefund(this, mOrderDetailItem, new RefundOrder.OnRefundListener() {
                    @Override
                    public void refeshOrders() {
                        refreafshOrderDetail();
                    }
                });
            }
        } else if (id == R.id.btn_tips) {
            mPresenter.orderTips(this, mOrderDetailItem, new TipsOrder.OnRefundListener() {
                @Override
                public void refeshOrders() {
                    refreafshOrderDetail();
                }
            });
        }
    }

    private void initOrderDetail(OrderManagerResponse orderDetailItem) {
        String payBill = LanguageUtils.get_language_system(this, "opentable.paybill", "結賬") + "：" + TimeUtils.getStringByFormat(new Date(orderDetailItem.getEndTime()), TimeUtils.DEFAULT_DATE_FORMAT_YMDHM);
        String pax = LanguageUtils.get_language_system(this, "Meal.Mannumber", "人數") + "：" + orderDetailItem.getPerson();
        String openTable = LanguageUtils.get_language_system(this, "open.table", "開台") + "：" + TimeUtils.getStringByFormat(new Date(orderDetailItem.getCreateTime()), TimeUtils.DEFAULT_DATE_FORMAT_YMDHM);
        String orderCode = LanguageUtils.get_language_system(mContext, "order.code", "訂單碼") + ": ";
        String mealCode = LanguageUtils.get_language_system(mContext, "meal.code", "取餐碼") + ": ";

        if (orderDetailItem.getOrderType() == OrderTypeConstans.order_type_2) {
            tv_table_name.setText("外賣");
            tv_order_num.setText(orderCode + orderDetailItem.getTakeFoodCode());
        } else if (orderDetailItem.getOrderType() == OrderTypeConstans.order_type_7) {
            tv_table_name.setText("自取");
            tv_order_num.setText(orderCode + orderDetailItem.getBillNo() + "  " + mealCode + orderDetailItem.getTakeFoodCode());
        } else {
            String tableName = LanguageUtils.get_language_system(this, "table.number", "檯號") + ": ";
            String orderNumber = LanguageUtils.get_language_system(this, "order.number", "單號") + ": ";
            tv_table_name.setText(tableName + orderDetailItem.getTableName());
            tv_order_num.setText(orderNumber + orderDetailItem.getOrderNo());
        }
        tv_people_num.setText(pax);
        tv_open_time.setText(openTable);
        if (!TextUtils.isEmpty(orderDetailItem.getEndTime())) {
            tv_pay_time.setText(payBill);
        }
        tv_total_money.setText("$" + orderDetailItem.getTotalAmount());

        double totalMoney = mPresenter.getTotalMoney(mOrderCenterDetailFoodList);
        tv_total.setText("$" + totalMoney);
    }

    private void initOrderItemAdapter() {
        if (mOrderCenterDetailFoodAdapter == null) {
            mOrderCenterDetailFoodAdapter = new OrderCenterDetailFoodAdapter(mOrderCenterDetailFoodList);
            recycler_food.setAdapter(mOrderCenterDetailFoodAdapter);
            LinearLayoutManager allOrderRecycleLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
            recycler_food.setLayoutManager(allOrderRecycleLayoutManager);
        }
        if (mOrderDetailPayMethodAdapter == null) {
            mOrderDetailPayMethodAdapter = new OrderCenterMoneyAdapter(mOrderCenterPayMethodList);
            recycler_pay_method.setAdapter(mOrderDetailPayMethodAdapter);
            LinearLayoutManager allOrderRecycleLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
            recycler_pay_method.setLayoutManager(allOrderRecycleLayoutManager);
        }
        if (mOrderCenterMoneyAdapter == null) {
            mOrderCenterMoneyAdapter = new OrderCenterMoneyAdapter(mOrderCenterMoneyList);
            recycler_order_moeny.setAdapter(mOrderCenterMoneyAdapter);
            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
            recycler_order_moeny.setLayoutManager(linearLayoutManager);
        }
    }

    public void updateOrderItems(OrderManagerResponse orderDetailItem, List<OrderDetail> orderDetailList) {
        if (mOrderCenterDetailFoodList.size() > 0) {
            mOrderCenterDetailFoodList.clear();
        }
        if (mOrderCenterMoneyList.size() > 0) {
            mOrderCenterMoneyList.clear();
        }
        if (mOrderCenterPayMethodList.size() > 0) {
            mOrderCenterPayMethodList.clear();
        }
        SectionTextItem3 serviceAmountSection = mPresenter.getOrderServiceAmountSection(orderDetailItem);
        if (serviceAmountSection != null) {
            mOrderCenterMoneyList.add(serviceAmountSection);
        }
        List<SectionTextItem3> discountSections = mPresenter.getOrderDiscountSections(orderDetailItem);
        if (discountSections != null) {
            mOrderCenterMoneyList.addAll(discountSections);
        }
        SectionTextItem3 roudingSection = mPresenter.getOrderRoudingSection(orderDetailItem);
        if (roudingSection != null) {
            mOrderCenterMoneyList.add(roudingSection);
        }
        List<PayMethod> payMethodList = mPresenter.getPayMethodList(orderDetailItem.getOrderPays());
        List<SectionTextItem3> orderPayMethodList = mPresenter.orderPayMethodTransSectionTextItem3(payMethodList);
        mOrderCenterDetailFoodList.addAll(mPresenter.orderDetailTransSectionTextItem3(orderDetailList));
        mOrderCenterPayMethodList.addAll(orderPayMethodList);

        mOrderCenterDetailFoodAdapter.notifyDataSetChanged();
        mOrderCenterMoneyAdapter.notifyDataSetChanged();
        mOrderDetailPayMethodAdapter.notifyDataSetChanged();
    }

    private void setBtnVisible() {
        if (mOrderDetailItem.getRestaurantOperationId() != null) {
            setWithSettlementLayoutVisible();
        } else {
            if (mOrderDetailItem.withHywebPay() && AppDevices.isHywebPos()) {
                if (mOrderDetailItem.isCurrDeviceOrder()) {
                    setCurrPosDeviceLayoutVisible();
                } else {
                    setNotCurrPosDeviceLayoutVisible();
                }
            } else {
                setNomalDeviceLayoutVisible();
            }
            setPublicLayoutVisible();
        }
    }

    @Override
    public void initIntent() {
        Intent intent = getIntent();
        mOrderDetailItem = (OrderManagerResponse) intent.getSerializableExtra("orderDetailItem");
    }

    @Override
    public void initTopBar() {
        mTopBar.setBackgroundColor(ContextCompat.getColor(this, R.color.theme_color));
        mTopBar.addLeftBackImageButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                killMyself();
//                overridePendingTransition(R.anim.slide_still, R.anim.slide_out_right);
            }
        });
        mTopBar.setTitle(LanguageUtils.get_language_system(this, "function.order.detail", "賬單詳情")).setTextColor(ArmsUtils.getColor(this, R.color.theme_white_color));
    }

    @Override
    public void initLanguage() {

        tv_food_detail_text.setText(LanguageUtils.get_language_system(this, "food.detail.text", "食品詳情"));
        tv_total_text.setText(LanguageUtils.get_language_system(this, "total.text", "合計"));
//        tv_server_money_text.setText(LanguageUtils.get_language_system(this, "service.fee.text", "服務費"));
        tv_total_money_text.setText(LanguageUtils.get_language_system(this, "order.countall_all", "總金額"));

        btn_print_order.setText(LanguageUtils.get_language_system(this, "print.order", "打印賬單"));
        btn_tips.setText(LanguageUtils.get_language_system(this, "public.tips", "貼士"));
        btn_modify_order.setText(LanguageUtils.get_language_system(this, "modify.order", "修改訂單"));
    }

    @Override
    public void initLayoutParams() {

    }

    @Override
    public void initLayoutVisible() {

    }

    @Override
    public void showLoading(String message) {
        if (message != null)
            LoadingDialog.showDialogForLoading(this, message, true);
        else
            LoadingDialog.showDialogForLoading(this);
    }

    @Override
    public void hideLoading() {
        LoadingDialog.cancelDialogForLoading();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.makeText(this, message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    @Override
    public void setWithSettlementLayoutVisible() {
        btn_modify_order.setVisibility(View.GONE);
        btn_tips.setVisibility(View.GONE);
        btn_cancel_order.setVisibility(View.GONE);
//        btn_refund.setVisibility(View.VISIBLE);
    }

    @Override
    public void setCurrPosDeviceLayoutVisible() {
        //N5 POS異常重試
        if (mOrderDetailItem.getMatterStatus() == OrderManagerResponse.MATTER_STATUS_EXCEPTION) {
            tv_reload_exception_status.setText(mOrderDetailItem.getExceptionReloadText());
            tv_reload_exception_status.setVisibility(View.VISIBLE);
            tv_reload_exception_status.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    PosActionStatusExceptionFragment statusExceptionFragment = findFragment(PosActionStatusExceptionFragment.class);
                    if (statusExceptionFragment == null) {
                        PosActionStatusExceptionParam statusExceptionParam = new PosActionStatusExceptionParam();
                        statusExceptionParam.setTxnId(mOrderDetailItem.getMatterTxnId());
                        statusExceptionParam.setAmount(mOrderDetailItem.getTotalAmount());
                        statusExceptionParam.setOrderId(mOrderDetailItem.getId());
                        statusExceptionParam.setOrderNo(mOrderDetailItem.getOrderNo());
                        statusExceptionParam.setPayMethodName(mOrderDetailItem.getPayNames());
                        statusExceptionParam.setPosAction(mOrderDetailItem.getPosActionByMatterId());
                        loadRootFragment(R.id.fl_container, PosActionStatusExceptionFragment.newInstance(statusExceptionParam));
                    } else {
                        start(statusExceptionFragment);
                    }
                }
            });
            rl_container.setVisibility(View.VISIBLE);
            rl_container.setBackgroundResource(R.color.transparent);
            ll_bottom.setVisibility(View.GONE);
        } else {
            tv_reload_exception_status.setText("");
            tv_reload_exception_status.setVisibility(View.GONE);
            tv_reload_exception_status.setOnClickListener(null);
            rl_container.setVisibility(View.GONE);
            rl_container.setBackgroundResource(R.color.trans);
            ll_bottom.setVisibility(View.VISIBLE);

            boolean containCard = mPresenter.containCardPayment(mOrderDetailItem.getOrderPays());
            if (containCard) {
                //當前設備訂單，且只有卡片支付才支持補小費
                btn_tips.setVisibility(View.VISIBLE);
            } else {
                btn_tips.setVisibility(View.GONE);
            }
            if (!TextUtils.isEmpty(mOrderDetailItem.getCancelTxnId())) {
                tv_order_status.setText("已取消");
                tv_order_status.setVisibility(View.VISIBLE);
                ll_bottom.setVisibility(View.GONE);
            } else if (!TextUtils.isEmpty(mOrderDetailItem.getRefundTxnId())) {
                tv_order_status.setVisibility(View.VISIBLE);
                tv_order_status.setText("已退款");
                ll_bottom.setVisibility(View.GONE);
            }
        }
    }

    @Override
    public void setNotCurrPosDeviceLayoutVisible() {
        btn_modify_order.setVisibility(View.GONE);
        btn_tips.setVisibility(View.GONE);
        btn_cancel_order.setVisibility(View.GONE);
        btn_refund.setVisibility(View.GONE);
    }

    @Override
    public void setNomalDeviceLayoutVisible() {
        btn_tips.setVisibility(View.GONE);
        btn_refund.setVisibility(View.GONE);
    }

    @Override
    public void setPublicLayoutVisible() {
        if (mOrderDetailItem.getStatus() == OrderStatusContract.STATUS_6) {
            //訂單已取消
            tv_order_status.setVisibility(View.VISIBLE);
            ll_bottom.setVisibility(View.GONE);
        } else {
            tv_order_status.setVisibility(View.GONE);
            ll_bottom.setVisibility(View.VISIBLE);
            int orderType = mOrderDetailItem.getOrderType();
            if (orderType == OrderTypeConstans.order_type_2 || orderType == OrderTypeConstans.order_type_7) {
                //外賣自取 不可以修改訂單 取消訂單
                btn_modify_order.setVisibility(View.GONE);
                btn_cancel_order.setVisibility(View.GONE);
            }
        }
    }

    private void setOrderBtnVisbilityByTxnId(String cancelTxnId, String refundTxnId) {
        if (!TextUtils.isEmpty(cancelTxnId)) {
            tv_order_status.setText("已取消");
            tv_order_status.setVisibility(View.VISIBLE);
            ll_bottom.setVisibility(View.GONE);
            return;
        }
        if (!TextUtils.isEmpty(refundTxnId)) {
            tv_order_status.setVisibility(View.VISIBLE);
            tv_order_status.setText("已退款");
            ll_bottom.setVisibility(View.GONE);
            return;
        }
    }

    @Override
    public void returnOrderDetail(OrderManagerResponse orderDetailItem) {
        this.mOrderDetailItem = orderDetailItem;
        mOrderDetailList = OrderAssemblyUtil.assemblyOrder(OrderDetail.orderTransOrderDetails(orderDetailItem.getOrderDetails()));
        initOrderDetail(orderDetailItem);
        updateOrderItems(orderDetailItem, mOrderDetailList);
        setBtnVisible();
        btn_refund.setVisibility(View.GONE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == OrderCenterActivity.MODIFY_ORDER_RETURN_CODE) {
            //修改訂單返回,刷新訂單數據
            refreafshOrderDetail();
        }
    }

    private void refreafshOrderDetail() {
        mPresenter.getOrderDetailItem(mOrderDetailItem.getId());
    }

}
