package com.gingersoft.gsa.cloud.table.mvp.presenter.orderManager;

import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
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.time.TimeUtil;
import com.gingersoft.gsa.cloud.table.R;
import com.gingersoft.gsa.cloud.table.mvp.contract.AllOrderContract;
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.ui.activity.MealStandActivity;
import com.gingersoft.gsa.cloud.table.mvp.ui.activity.orderManager.OrderCenterActivity;
import com.gingersoft.gsa.cloud.table.mvp.ui.activity.orderManager.OrderDetailActivity;
import com.gingersoft.gsa.cloud.table.mvp.ui.adapter.OrderCenterAdapter;
import com.gingersoft.gsa.cloud.table.mvp.ui.fragment.AllOrderFragment;
import com.jess.arms.di.scope.FragmentScope;
import com.jess.arms.http.imageloader.ImageLoader;
import com.jess.arms.integration.AppManager;
import com.jess.arms.mvp.BasePresenter;
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 javax.inject.Inject;

import me.jessyan.rxerrorhandler.core.RxErrorHandler;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 03/13/2020 16:25
 * <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>
 * ================================================
 */
@FragmentScope
public class AllOrderPresenter extends BasePresenter<AllOrderContract.Model, AllOrderContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    private OrderCenterActivity IActivity;
    private OrderCenterAdapter mOrderCenterAdapter;
    private List<OrderDetailItem> mOrderItemList = new ArrayList<>();

    @Inject
    public AllOrderPresenter(AllOrderContract.Model model, AllOrderContract.View rootView) {
        super(model, rootView);
        AllOrderFragment allOrderFragment = (AllOrderFragment) rootView;
        this.IActivity = (OrderCenterActivity) allOrderFragment.getActivity();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;
    }

    public void initOrderAdapter(Context context) {
        if (mOrderCenterAdapter == null) {
            mOrderCenterAdapter = new OrderCenterAdapter(context, mOrderItemList);
            mRootView.setAllOrderAdapter(mOrderCenterAdapter);
        }
        mOrderCenterAdapter.setOnItemClickListener(new OrderCenterAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(OrderDetailItem datasBean, int position) {
                Intent intent = new Intent(IActivity, OrderDetailActivity.class);
                intent.putExtra("orderDetailItem", datasBean);
                mRootView.launchActivity(intent);
            }

            @Override
            public void onPrintClick(OrderDetailItem datasBean, int position) {
                List<OrderDetail> orderDetailList = OrderAssemblyUtil.assemblyOrder(OrderDetail.orderTransOrderDetails(datasBean.getOrderDetails()));
                startPrintOrder(datasBean, orderDetailList);
            }

            @Override
            public void onModifyClick(OrderDetailItem datasBean, int position) {
                //設置為修改訂單操作
                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(OrderDetail.orderTransOrderDetails(orderDetailsBeans));
                MyOrderManage.getInstance().setOrderFoodList(orderDetailList);

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

            @Override
            public void onCancelClick(OrderDetailItem datasBean, int position) {
                showCancelDialog(datasBean.getId());
            }
        });
    }

    private void showCancelDialog(long orderId) {
        QMUIDialog.MessageDialogBuilder dialogBuilder = new QMUIDialog.MessageDialogBuilder(IActivity);
        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();
            IActivity.cancelOrder(orderId, mRootView.getStatus());
        });
        dialogBuilder.create(R.style.MyDialogTheme2).show();
    }

    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);
        List<PayMethod> payMethodList = getPayMethodList(orderDetailItem);
        //設置打印所需支付方式
        MyOrderManage.getInstance().setBillMoney(payMethodList);
        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);
                });
    }

    /**
     * 獲取支付方式
     *
     * @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);
        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;
    }

    public void updateOrderData(List<OrderDetailItem> orderItemList) {
        if (orderItemList != null) {
            mOrderItemList.clear();
            mOrderItemList.addAll(orderItemList);
            mOrderCenterAdapter.notifyDataSetChanged();
        }
    }

    public void addOrderItem(List<OrderDetailItem> orderItemList) {
        if (orderItemList != null) {
            mOrderItemList.addAll(orderItemList);
            mOrderCenterAdapter.notifyDataSetChanged();
        }
    }

}
