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

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

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

import com.billy.cc.core.component.CC;
import com.gingersoft.gsa.cloud.base.common.bean.OrderBean;
import com.gingersoft.gsa.cloud.base.common.bean.OrderDetail;
import com.gingersoft.gsa.cloud.base.common.bean.PayMethod;
import com.gingersoft.gsa.cloud.base.common.bean.TableBean;
import com.gingersoft.gsa.cloud.base.common.bean.mealManage.MyOrderManage;
import com.gingersoft.gsa.cloud.base.common.bean.mealManage.OpenTableManage;
import com.gingersoft.gsa.cloud.base.utils.LanguageUtils;
import com.gingersoft.gsa.cloud.base.utils.MoneyUtil;
import com.gingersoft.gsa.cloud.base.utils.time.TimeUtil;
import com.gingersoft.gsa.cloud.constans.PrintConstans;
import com.gingersoft.gsa.cloud.database.bean.Discount;
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.contract.OrderDetailContract;
import com.gingersoft.gsa.cloud.table.mvp.model.bean.OrderDetailItem;
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.activity.MealStandActivity;
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.BaseActivity;
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 com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;

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 BaseActivity<OrderDetailPresenter> implements OrderDetailContract.View {

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

    @BindView(R2.id.scrollview)
    ScrollView 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 OrderDetailItem 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);
            }
        });
        initOrderDetail(mOrderDetailItem);
    }

    private void initOrderDetail(OrderDetailItem orderDetailItem) {
        if (orderDetailItem != null) {
            String payBill = LanguageUtils.get_language_system(this, "opentable.paybill", "結賬") + "：";
            String tableName = LanguageUtils.get_language_system(this, "table.number", "檯號") + "：";
            String pax = LanguageUtils.get_language_system(this, "Meal.Mannumber", "人數") + "：";
            String orderNumber = LanguageUtils.get_language_system(this, "order.number", "訂單號") + "：";
            String openTable = LanguageUtils.get_language_system(this, "open.table", "開台") + "：";
            tv_table_name.setText(tableName + orderDetailItem.getTableName());
            tv_people_num.setText(pax + orderDetailItem.getPerson());
            tv_order_num.setText(orderNumber + orderDetailItem.getId());
            tv_open_time.setText(openTable + TimeUtil.getStringByFormat(new Date(orderDetailItem.getCreateTime()), TimeUtil.dateFormatYMDHM));
            if (!TextUtils.isEmpty(orderDetailItem.getEndTime())) {
                tv_pay_time.setText(payBill + TimeUtil.getStringByFormat(new Date(orderDetailItem.getEndTime()), TimeUtil.dateFormatYMDHM));
            }
            tv_total_money.setText("$" + orderDetailItem.getAmount());

            setOrderStatus(orderDetailItem);

            mOrderDetailList = OrderAssemblyUtil.assemblyOrder(OrderDetail.orderTransOrderDetails(orderDetailItem.getOrderDetails()));
            setOrderDetailAdapter(mOrderDetailList);

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

            setOrderMoneyAdpater(orderDetailItem, totalMoney);
            setOrderPayMethodAdapter(orderDetailItem);
        }
    }


    private void setOrderMoneyAdpater(OrderDetailItem orderDetailItem, double totalMoney) {
        if (mOrderCenterMoneyList.size() > 0) {
            mOrderCenterMoneyList.clear();
        }
        SectionTextItem3 serviceAmountSection = getOrderServiceAmountSection(orderDetailItem);
        if (serviceAmountSection != null) {
            mOrderCenterMoneyList.add(serviceAmountSection);
        }
        List<SectionTextItem3> discountSections = getOrderDiscountSections(orderDetailItem, totalMoney);
        if (discountSections != null) {
            mOrderCenterMoneyList.addAll(discountSections);
        }
        SectionTextItem3 roudingSection = getOrderRoudingSection(orderDetailItem);
        if (roudingSection != null) {
            mOrderCenterMoneyList.add(roudingSection);
        }
        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);
        } else {
            mOrderCenterMoneyAdapter.notifyDataSetChanged();
        }
    }

    private void setOrderDetailAdapter(List<OrderDetail> orderDetailList) {
        if (mOrderCenterDetailFoodAdapter == null) {
            mOrderCenterDetailFoodList.addAll(SectionTextItem3.orderDetailTransSectionTextItem3(orderDetailList));
            mOrderCenterDetailFoodAdapter = new OrderCenterDetailFoodAdapter(mOrderCenterDetailFoodList);
            recycler_food.setAdapter(mOrderCenterDetailFoodAdapter);
            LinearLayoutManager allOrderRecycleLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
            recycler_food.setLayoutManager(allOrderRecycleLayoutManager);
        } else {
            mOrderCenterDetailFoodList.clear();
            mOrderCenterDetailFoodList.addAll(SectionTextItem3.orderDetailTransSectionTextItem3(orderDetailList));
            mOrderCenterDetailFoodAdapter.notifyDataSetChanged();
        }
    }

    private void setOrderPayMethodAdapter(OrderDetailItem orderDetailItem) {
        List<PayMethod> payMethodList = getPayMethodList(orderDetailItem);
        List<SectionTextItem3> sectionTextItem3List = SectionTextItem3.orderPayMethodTransSectionTextItem3(payMethodList);
        if (mOrderDetailPayMethodAdapter == null) {
            mOrderCenterPayMethodList.addAll(sectionTextItem3List);
            mOrderDetailPayMethodAdapter = new OrderCenterMoneyAdapter(mOrderCenterPayMethodList);
            recycler_pay_method.setAdapter(mOrderDetailPayMethodAdapter);
            LinearLayoutManager allOrderRecycleLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
            recycler_pay_method.setLayoutManager(allOrderRecycleLayoutManager);
        } else {
            mOrderCenterPayMethodList.clear();
            mOrderCenterPayMethodList.addAll(sectionTextItem3List);
            mOrderDetailPayMethodAdapter.notifyDataSetChanged();
        }
        //設置打印所需支付方式
        MyOrderManage.getInstance().setBillMoney(payMethodList);
    }

    /**
     * 獲取支付方式
     *
     * @param orderDetailItem
     * @return
     */
    private List<PayMethod> getPayMethodList(OrderDetailItem orderDetailItem) {
        List<PayMethod> payMethodList = new ArrayList<>();
        PayMethod payMethod = new PayMethod();
        payMethod.setPayName(orderDetailItem.getPayName());
        payMethod.setPayMoney(orderDetailItem.getAmount());
        payMethodList.add(payMethod);
        if (orderDetailItem.getTipsPrice() != 0) {
            //打印添加找零或貼士行
            String linePayType = orderDetailItem.getLinePayType() == 1 ? "找零" : "貼士";
            PayMethod payMethod2 = new PayMethod();
            //這裡打印退一格
            payMethod2.setPayName("     " + linePayType);
            payMethod2.setPayMoney(orderDetailItem.getTipsPrice());
            payMethodList.add(payMethod2);
        }
        return payMethodList;
    }

    /**
     * 獲取賬單折扣列
     * @param orderDetailItem
     * @param totalMoney
     * @return
     */
    private List<SectionTextItem3> getOrderDiscountSections(OrderDetailItem orderDetailItem, double totalMoney) {
        if (orderDetailItem.getRemark() != null) {
            //折扣
            Discount discount = new Discount();
            discount.setType(orderDetailItem.getType());
            discount.setRemark(orderDetailItem.getRemark());
            discount.setDiscount_value(orderDetailItem.getDiscountValue());
            double discountPrice = Discount.calculationDiscount(discount, totalMoney);
            discount.setAmount(discountPrice);
            return SectionTextItem3.discountTransSectionTextItem3(discount);
        }
        return null;
    }

    /**
     * 獲取賬單小數列
     * @param orderDetailItem
     * @return
     */
    private SectionTextItem3 getOrderRoudingSection(OrderDetailItem orderDetailItem) {
        if (orderDetailItem.getRounding() != null && orderDetailItem.getRounding() != 0) {
            return SectionTextItem3.roundingTransSectionTextItem3(orderDetailItem.getRounding());
        }
        return null;
    }

    /**
     * 获取服務費
     * @param orderDetailItem
     * @return
     */
    private SectionTextItem3 getOrderServiceAmountSection(OrderDetailItem orderDetailItem) {
        if (orderDetailItem.getServiceAmount() != null && orderDetailItem.getServiceAmount() != 0) {
            return SectionTextItem3.serviceAmountTransSectionTextItem3(orderDetailItem.getServiceAmount());
        }
        return null;
    }

    /**
     * 返回合計金額
     *
     * @return
     */
    private double getTotalMoney() {
        double otherMoney = 0.0;
        for (SectionTextItem3 item : mOrderCenterDetailFoodList) {
            otherMoney = MoneyUtil.sum(otherMoney, Double.parseDouble(item.getRightText()));
        }
        return otherMoney;
    }

    /**
     * 設置訂單狀態
     *
     * @param item
     */
    private void setOrderStatus(OrderDetailItem item) {
        if (item.getStatus() == 6) {
            btn_print_order.setVisibility(View.GONE);
            btn_modify_order.setVisibility(View.GONE);
            btn_cancel_order.setVisibility(View.GONE);
            tv_order_status.setVisibility(View.VISIBLE);
        } else {
            btn_print_order.setVisibility(View.VISIBLE);
            btn_modify_order.setVisibility(View.VISIBLE);
            btn_cancel_order.setVisibility(View.VISIBLE);
            tv_order_status.setVisibility(View.GONE);
        }
    }

    @OnClick({R2.id.btn_print_order, R2.id.btn_cancel_order, R2.id.btn_modify_order})
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.btn_print_order) {
            startPrintOrder(mOrderDetailItem, mOrderDetailList);
        } else if (id == R.id.btn_cancel_order) {
            showCancelDialog();
        } else if (id == R.id.btn_modify_order) {
            startModifyOrder(mOrderDetailItem);
        }
    }

    private void startModifyOrder(OrderDetailItem datasBean) {
        //設置為修改訂單操作
        MyOrderManage.getInstance().setModifyOrder(true);
        /**
         * 緩存訂單信息
         */
        OrderBean orderBean = new OrderBean();
        orderBean.setId(datasBean.getId());
        orderBean.setStatus(datasBean.getStatus());
        orderBean.setOrderNo(datasBean.getOrderNo());
        orderBean.setPerson(datasBean.getPerson());
        orderBean.setType(datasBean.getType());
        orderBean.setRemark(datasBean.getRemark());
        orderBean.setDiscountAmount(datasBean.getDiscountAmount());
        orderBean.setDiscountValue(datasBean.getDiscountValue());
        orderBean.setCreateTime(datasBean.getCreateTime());
        MyOrderManage.getInstance().setOrderBean(orderBean);

        TableBean.DataBean openTableBean = new TableBean.DataBean();
        openTableBean.setCreateTime(TimeUtil.getStringByFormat(new Date(datasBean.getCreateTime()), TimeUtil.dateFormatYMDHM));
        openTableBean.setTableName(datasBean.getTableName());
        openTableBean.setId(datasBean.getTableId());
        OpenTableManage.getDefault().setTableBean(openTableBean);

        OpenTableManage.getDefault().setPeopleNumber(datasBean.getPerson());
        List<OrderBean.OrderDetailsBean> orderDetailsBeans = datasBean.getOrderDetails();
        List<OrderDetail> orderDetailList = OrderAssemblyUtil.assemblyOrder(OrderDetail.orderTransOrderDetails(orderDetailsBeans));
        MyOrderManage.getInstance().setOrderFoodList(orderDetailList);

        Intent intent = new Intent(this, MealStandActivity.class);
        startActivityForResult(intent, OrderCenterActivity.MODIFY_ORDER_RETURN_CODE);
    }

    /**
     * 打印賬單
     *
     * @param orderDetailItem
     * @param orderDetailList
     */
    private void startPrintOrder(OrderDetailItem orderDetailItem, List<OrderDetail> orderDetailList) {
        MyOrderManage.getInstance().setOrderFoodList(orderDetailList);
        MyOrderManage.getInstance().setOrderId(orderDetailItem.getId());
        OpenTableManage.getDefault().setPeopleNumber(orderDetailItem.getPerson());

        TableBean.DataBean dataBean = new TableBean.DataBean();
        dataBean.setTableName(orderDetailItem.getTableName());
        dataBean.setCreateTime(TimeUtil.getStringByFormat(new Date(orderDetailItem.getCreateTime()), TimeUtil.dateFormatYMDHM));
        OpenTableManage.getDefault().setTableBean(dataBean);

        CC.obtainBuilder("Component.Print")
                .setActionName("printActivity")
                .addParam(PrintConstans.PRINT_TYPE, 2)
                .build()
                .callAsyncCallbackOnMainThread((cc, result) -> {
                    Log.e("error", "是否成功打印：" + result.isSuccess());

                    MyOrderManage.getInstance().clear();
                    OpenTableManage.getDefault().setPeopleNumber(0);
                    OpenTableManage.getDefault().setTableBean(null);
                });
    }

    private void showCancelDialog() {
        QMUIDialog.MessageDialogBuilder dialogBuilder = new QMUIDialog.MessageDialogBuilder(this);
        dialogBuilder.setTitle("溫馨提示");
        dialogBuilder.setTitleIcon(R.drawable.qmui_icon_dialog_doubt);
        dialogBuilder.setMessage("是否取消訂單?");
        dialogBuilder.addAction("取消", (dialog, index) -> dialog.dismiss());
        dialogBuilder.addAction(0, "確認", QMUIDialogAction.ACTION_PROP_NEGATIVE, (dialog, index) -> {
            dialog.dismiss();
            mPresenter.cancelOrder(mOrderDetailItem.getId());
        });
        dialogBuilder.create(R.style.MyDialogTheme2).show();
    }

    @Override
    public void initIntent() {
        Intent intent = getIntent();
        mOrderDetailItem = (OrderDetailItem) 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 returnOrderDetail(OrderDetailItem orderDetailItem) {
        this.mOrderDetailItem = orderDetailItem;
        initOrderDetail(orderDetailItem);
    }

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

}
