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.time.TimeUtil;
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.OrderDetailPresenter;
import com.gingersoft.gsa.cloud.table.mvp.ui.activity.MealStandActivity;
import com.gingersoft.gsa.cloud.table.mvp.ui.adapter.OrderDetailItemAdapter;
import com.gingersoft.gsa.cloud.table.mvp.ui.adapter.OrderDetailPayMethodAdapter;
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_discount)
    RecyclerView recycler_discount;
    @BindView(R2.id.recycler_pay_method)
    RecyclerView recycler_pay_method;

    @BindView(R2.id.tv_total_text)
    TextView tv_total_text;
    @BindView(R2.id.tv_server_money_text)
    TextView tv_server_money_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_server_money)
    TextView tv_server_money;
    @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 OrderDetailItemAdapter mOrderDetailFoodAdapter;
    private List<SectionTextItem3> mSectionTextItem3FoodList = new ArrayList<>();
    private List<OrderDetail> mOrderDetailList;

    private OrderDetailPayMethodAdapter mOrderDetailPayMethodAdapter;
    private List<SectionTextItem3> mSectionTextItem3PayMethodList = 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) {

        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.setText("$" + orderDetailItem.getTotalAmount());
            tv_total_money.setText("$" + orderDetailItem.getTotalAmount());

            tv_server_money.setVisibility(View.GONE);
            tv_server_money_text.setVisibility(View.GONE);

            setOrderStatus(orderDetailItem);

            mOrderDetailList = OrderAssemblyUtil.assemblyOrder(OrderDetailItem.orderTransOrderDetails(orderDetailItem.getOrderDetails()));
            setOrderDetailFoodAdapter(mOrderDetailList);
            setOrderPayMethodAdapter(orderDetailItem);
        }
    }

    /**
     * 設置訂單狀態
     *
     * @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);
        }
    }


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

    private void setOrderPayMethodAdapter(OrderDetailItem orderDetailItem) {
        List<PayMethod> payMethodList = getPayMethodList(orderDetailItem);
        List<SectionTextItem3> sectionTextItem3List = SectionTextItem3.orderPayMethodTransSectionTextItem3(payMethodList);
        if (mOrderDetailPayMethodAdapter == null) {
            mSectionTextItem3PayMethodList.addAll(sectionTextItem3List);
            mOrderDetailPayMethodAdapter = new OrderDetailPayMethodAdapter(mSectionTextItem3PayMethodList);
            recycler_pay_method.setAdapter(mOrderDetailPayMethodAdapter);
            LinearLayoutManager allOrderRecycleLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
            recycler_pay_method.setLayoutManager(allOrderRecycleLayoutManager);
        } else {
            mSectionTextItem3PayMethodList.clear();
            mSectionTextItem3PayMethodList.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.getTotalAmount());
        payMethodList.add(payMethod);
        return payMethodList;
    }

    @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.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(OrderDetailItem.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("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.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());
        }
    }

}
