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

import android.app.Activity;
import android.app.Application;
import android.widget.TextView;

import com.gingersoft.gsa.cloud.base.common.bean.BaseResult;
import com.gingersoft.gsa.cloud.base.common.bean.OrderBean;
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.table.mvp.contract.BaseOrderContract;
import com.gingersoft.gsa.cloud.table.mvp.model.bean.BillOrderMoney;
import com.gingersoft.gsa.cloud.base.common.bean.OrderDetail;
import com.gingersoft.gsa.cloud.table.mvp.model.bean.request.OrderRequest;
import com.gingersoft.gsa.cloud.table.mvp.ui.activity.OrderContentActivity;
import com.gingersoft.gsa.cloud.table.mvp.ui.adapter.OrderMoneyAdapter;
import com.gingersoft.gsa.cloud.table.mvp.ui.adapter.meal.SelectMealAdapter;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.http.imageloader.ImageLoader;
import com.jess.arms.integration.AppManager;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.RxLifecycleUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import javax.inject.Inject;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;
import okhttp3.FormBody;
import okhttp3.RequestBody;

/**
 * 作者：ELEGANT_BIN
 * 版本：1.6.0
 * 创建日期：2020-01-11
 * 修订历史：2020-01-11
 * 描述：
 */

@ActivityScope
public class BaseOrderPresenter<M extends BaseOrderContract.Model, V extends BaseOrderContract.View> extends BasePresenter<BaseOrderContract.Model, BaseOrderContract.View> {

    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    protected M mModel;
    protected V mRootView;

    private Activity IActivity;
    private OrderContentActivity mOrderContentActivity;

    //订单数据管理类
    protected MyOrderManage myOrderManage;

    //訂單食品適配器
    protected SelectMealAdapter mSelectMealAdapter;
    protected List<OrderDetail> orderFoodList;

    //整單相關金額適配器
    protected OrderMoneyAdapter mOrderMoneyAdapter;
    protected List<BillOrderMoney> mOrderMoneyList = new ArrayList<>();

    //選中操作的食品下標
    protected int orderSelectPosition = -1;

    //食品數量
    protected int foodCount;
    //總金額
    protected double totalMoney;
    //币種
    public String cashStr = "$";

    @Inject
    public BaseOrderPresenter(BaseOrderContract.Model model, BaseOrderContract.View rootView) {
        super(model, rootView);
        this.mModel = (M) model;
        this.mRootView = (V) rootView;
        this.IActivity = (Activity) mRootView;
        this.myOrderManage = MyOrderManage.getInstance();
        this.orderFoodList = myOrderManage.getOrderFoodList();

        if (IActivity instanceof OrderContentActivity) {
            mOrderContentActivity = (OrderContentActivity) IActivity;
        }

        foodCount = initFoodCount();
        totalMoney = initFoodTotalMoney();

        resetSelected();
        initOrderAdapter();
    }

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

    private void initOrderAdapter() {
        if (mSelectMealAdapter == null) {
            mSelectMealAdapter = new SelectMealAdapter(IActivity, orderFoodList, this);
            //設置子父級下標
            mSelectMealAdapter.setIndex();
        }
        if (mOrderMoneyAdapter == null) {
            mOrderMoneyAdapter = new OrderMoneyAdapter(IActivity, mOrderMoneyList, cashStr);
        }
        initItemClickListener();
    }

    private void initItemClickListener() {
        mSelectMealAdapter.setOnItemClickListener(new SelectMealAdapter.OnItemClickListener() {

            @Override
            public void onItemClick(OrderDetail datasBean, int position) {
                orderSelectPosition = position;
                mSelectMealAdapter.setMyOrderManageSelectPosition();
            }

            @Override
            public void onMealCountDelete(OrderDetail datasBean, int position) {
                if (datasBean.getNumber() == 1) {
                    mSelectMealAdapter.removeFoodItem();
                } else {
                    MyOrderManage.getInstance().changeNumber(datasBean.getNumber() - 1);
                }
                mSelectMealAdapter.notifyItemChanged(position);
//                recalcOrderMoneyCount(false, true);
                if (mOrderContentActivity != null) {
                    mOrderContentActivity.initOrderDetail();
                }
            }

            @Override
            public void onMealCountAdd(OrderDetail datasBean, int position) {
                MyOrderManage.getInstance().changeNumber(datasBean.getNumber() + 1);
                mSelectMealAdapter.notifyItemChanged(position);
                if (mOrderContentActivity != null) {
                    mOrderContentActivity.initOrderDetail();
                }
//                recalcOrderMoneyCount(false, true);
            }
        });
    }

    /**
     * 修改訂單
     *
     * @param //orderId 訂單號
     * @param //person  人數
     */
    public void updateOrderPerson(String peopleNumber, TextView textView) {
        RequestBody requestBody = new FormBody.Builder()
                .add("orderId", MyOrderManage.getInstance().getOrderId() + "")
                .add("person", peopleNumber + "")
                .build();
        mModel.updateOrderStatus(requestBody)
                .subscribeOn(Schedulers.io())
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<BaseResult>(mErrorHandler) {
                    @Override
                    public void onNext(BaseResult baseResult) {
                        if (baseResult.isSuccess()) {
                            textView.setText("人數:" + peopleNumber);
                            OpenTableManage.getDefault().setPeopleNumber(Integer.parseInt(peopleNumber));
                        }
                    }
                });
    }

    public void changeNumber(int number) {
        if (!changeNumberCondition(number)) {
            return;
        }
        myOrderManage.changeNumber(number);
        mSelectMealAdapter.notifyDataSetChanged();
    }

    public boolean changeNumberCondition(int i) {
        if (MyOrderManage.getInstance().getSize() <= 0) {
            return false;
        }
        if (mSelectMealAdapter.getSelect_start_position() == -1 || mSelectMealAdapter.getSelect_start_position() >= mSelectMealAdapter.getInfos().size()) {
            return false;
        }
        if (myOrderManage.getOrderFoodList().get(mSelectMealAdapter.getSelect_start_position()).isIsfood() == false) {
            return false;
        }
        //旧食品不可以修改数量
        if (i != 0 && myOrderManage.getOrderFoodList().get(mSelectMealAdapter.getSelect_start_position()).isNew() == false) {
            return false;
        }
        if (mSelectMealAdapter.getSelect_position() == -1) {
            return false;
        }
        return true;
    }

    public void resetSelected() {
        for (int i = 0; i < orderFoodList.size(); i++) {
            OrderDetail datasBean = orderFoodList.get(i);
            datasBean.setSelected(0);
        }
    }

    public double initFoodTotalMoney() {
        double total = 0.0;
        for (OrderDetail food : myOrderManage.getOrderFoodList()) {
            total += food.getPrice();
        }
        return total;
    }

    private int initFoodCount() {
        int cout = 0;
        for (OrderDetail food : myOrderManage.getOrderFoodList()) {
            cout += food.getNumber();
        }
        return cout;
    }

    protected String getDeleteFoodIds() {
        StringBuilder builder = new StringBuilder();
        List<OrderDetail> orderDetails = getOldOrderFoodLists();
        int start_position = mSelectMealAdapter.getSelect_full_start_position() + 1;
        int end_position = mSelectMealAdapter.getSelect_full_end_position() + 1;
        for (int i = orderDetails.size() - 1; i >= 0; i--) {
            int my_index = orderDetails.get(i).getMyIndex();
            if (start_position <= my_index && my_index <= end_position) {
                OrderDetail orderDetail1 = orderDetails.get(i);
                builder.append(orderDetail1.getId());
                if (i <= (orderDetails.size() - 1)) {
                    builder.append(",");
                }
            }
        }
        String str = builder.toString();
        if (str.endsWith(",")) {
            str = str.substring(0, str.length() - 1);
        }
        return str;
    }

    protected OrderRequest getCreateOrderRequest(List<OrderDetail> foodList) {
        OrderRequest request = new OrderRequest();
        request.setOrderDetails(orderDetailBeanToFoodRequest(foodList));
        request.setPerson(OpenTableManage.getDefault().getPeopleNumber());
        request.setTableId(OpenTableManage.getDefault().getTableBean().getId());
        return request;
    }

    private List<OrderBean.OrderDetailsBean> orderDetailBeanToFoodRequest(List<OrderDetail> foodList) {
        List<OrderBean.OrderDetailsBean> requests = new ArrayList<>();
        if (foodList != null) {
            for (OrderDetail food : foodList) {
                OrderBean.OrderDetailsBean request = new OrderBean.OrderDetailsBean();
                request.setProductName(food.getProductName());
                request.setProductId(food.getId());
                request.setParentId(food.getParentId());
                request.setNumber(food.getNumber());
                request.setPrice(food.getPrice());
                request.setType(food.getType());
                request.setLunchboxPrice(0);
                requests.add(request);
            }
        }
        return requests;
    }

    protected List<OrderDetail> getNewOrderFoodLists() {
        List<OrderDetail> orderDetails = new ArrayList<>();
        for (int i = 0; i < getOrderFoodLists().size(); i++) {
            OrderDetail orderDetail = getOrderFoodLists().get(i);
            if (orderDetail.isNew()) {
                orderDetails.add(orderDetail);
            }
        }
        return orderDetails;
    }

    protected List<OrderDetail> getOldOrderFoodLists() {
        List<OrderDetail> orderDetails = new ArrayList<>();
        for (int i = 0; i < getOrderFoodLists().size(); i++) {
            OrderDetail orderDetail = getOrderFoodLists().get(i);
            if (!orderDetail.isNew()) {
                orderDetails.add(orderDetail);
            }
        }
        return orderDetails;
    }

    public List<OrderDetail> getOrderFoodLists() {
        return myOrderManage.getOrderFoodList();
    }

    protected void sortSelectMealByIsNew() {
        List<OrderDetail> orderDetail = orderFoodList;
        List<OrderDetail> sortOrderList = new ArrayList<>();
        for (int i = 0; i < orderDetail.size(); i++) {
            sortOrderList.add(orderDetail.get(i));
        }
        Comparator c = new Comparator<OrderDetail>() {
            @Override
            public int compare(OrderDetail o1, OrderDetail o2) {
                Boolean isnew1 = o1.isNew();
                Boolean isnew2 = o2.isNew();
                return isnew1.compareTo(isnew2);
            }
        };
        Collections.sort(sortOrderList, c);
        orderDetail.clear();
        for (int i = 0; i < sortOrderList.size(); i++) {
            orderDetail.add(sortOrderList.get(i));
        }
    }

    protected String getTableName() {
        String tablename = "";
        if (OpenTableManage.getDefault().isSplite()) {
            tablename = OpenTableManage.getDefault().getTableBean().getTableName() + "-" + OpenTableManage.getDefault().getSplitNo();
        } else {
            tablename = OpenTableManage.getDefault().getTableBean().getTableName();
        }
        return tablename;
    }

    public int getFoodCount() {
        return foodCount;
    }

    public void setFoodCount(int foodCount) {
        this.foodCount = foodCount;
    }

    public double getTotalMoney() {
        return totalMoney;
    }

    public void setTotalMoney(double totalMoney) {
        this.totalMoney = totalMoney;
    }
}

