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

import android.app.Application;

import com.gingersoft.gsa.cloud.common.bean.BaseResult;
import com.gingersoft.gsa.cloud.common.core.table.TableBean;
import com.gingersoft.gsa.cloud.common.rxjava.MyRxSchedulerUtils;
import com.gingersoft.gsa.cloud.order.order.MealOrder;
import com.gingersoft.gsa.cloud.table.mvp.contract.MealBillContract;
import com.gingersoft.gsa.cloud.table.mvp.model.bean.response.BaseOrderResponse;
import com.gingersoft.gsa.cloud.table.mvp.model.service.MealService;
import com.gingersoft.gsa.cloud.table.mvp.model.service.MemberService;
import com.gingersoft.gsa.cloud.table.mvp.model.service.TableService;
import com.google.gson.Gson;
import com.google.gson.internal.LinkedTreeMap;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.integration.IRepositoryManager;
import com.xuexiang.rxutil2.rxjava.RxSchedulerUtils;

import java.util.Date;

import javax.inject.Inject;

import io.reactivex.Observable;
import io.reactivex.Single;
import io.reactivex.functions.Function;
import okhttp3.RequestBody;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 01/09/2020 19:23
 * <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>
 * ================================================
 */
@ActivityScope
public class MealBillModel extends BaseMealModel implements MealBillContract.Model {
    @Inject
    Gson mGson;
    @Inject
    Application mApplication;

    @Inject
    public MealBillModel(IRepositoryManager repositoryManager) {
        super(repositoryManager);
    }

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

    private void saveCreateTime(long createTime) {
        MealOrder mealOrder = MealOrder.getInstance();
        if (mealOrder == null) {
            mealOrder.setOpenTableInfo(new TableBean.DataBean());
            String dateTime = new Date(createTime).toString();
            mealOrder.getOrderPlaced().setCreateTime(dateTime);
        }
    }

    @Override
    public Single<BaseOrderResponse> loadOrder(long orderId) {
        return mRepositoryManager.obtainRetrofitService(MealService.class)
                .loadOrder(orderId)
                .compose(MyRxSchedulerUtils._io_main_f());
    }

    @Override
    public Single<BaseOrderResponse> createOrder(RequestBody requestBody) {
        Single ob = mRepositoryManager.obtainRetrofitService(MealService.class)
                .createOrder(requestBody)
                .compose(MyRxSchedulerUtils._io_main_f())
                .flatMap(new Function<BaseResult, Single<BaseOrderResponse>>() {
                    @Override
                    public Single<BaseOrderResponse> apply(BaseResult info) throws Exception {
                        if (info != null && info.isSuccess()) {
                            saveCreateTime(info.getSysTime());
                            if (info.getData() != null) {
                                if (info.getData() instanceof Double) {
                                    //未上線，避免正式版閃退
                                    MealOrder.getInstance().setOrderId((long) info.getData());
                                    MealOrder.getInstance().setOrderNo(((Double) info.getData()).longValue() + "");
                                } else {
                                    LinkedTreeMap tm = (LinkedTreeMap) info.getData();
                                    for (Object o : tm.keySet()) {
                                        String key = (String) o;
                                        if (key.equals("id")) {
                                           double orderId = (double) tm.get(key);
                                            MealOrder.getInstance().setOrderId((long) orderId);
                                        } else if (key.equals("orderNo")) {
                                            MealOrder.getInstance().setOrderNo((String) tm.get(key));
                                        }
                                    }
                                }
                            }
                            return loadOrder(MealOrder.getInstance().getOrderId());
                        }
                        BaseOrderResponse baseOrderRespose = new BaseOrderResponse();
                        baseOrderRespose.setSuccess(info.isSuccess());
                        baseOrderRespose.setErrMsg(info.getErrMsg());
                        return Single.just(baseOrderRespose);
                    }
                });
        return ob;
    }

    @Override
    public Single<BaseOrderResponse> addOrderFood(RequestBody requestBody) {
        Single ob = mRepositoryManager.obtainRetrofitService(MealService.class)
                .addOrderFood(requestBody)
                .compose(MyRxSchedulerUtils._io_main_f())
                .flatMap(new Function<BaseResult, Single<BaseOrderResponse>>() {
                    @Override
                    public Single<BaseOrderResponse> apply(BaseResult info) throws Exception {
                        if (info != null && info.isSuccess()) {
                            saveCreateTime(info.getSysTime());
                            return loadOrder(MealOrder.getInstance().getOrderId());
                        }
                        BaseOrderResponse baseOrderRespose = new BaseOrderResponse();
                        baseOrderRespose.setSuccess(info.isSuccess());
                        baseOrderRespose.setErrMsg(info.getErrMsg());
                        return Single.just(baseOrderRespose);
                    }
                });
        return ob;
    }

    @Override
    public Single<BaseOrderResponse> printOrder(RequestBody request) {
        return mRepositoryManager.obtainRetrofitService(MealService.class)
                .printOrder(request)
                .compose(MyRxSchedulerUtils._io_main_f());
    }

    @Override
    public Observable<TableBean> getTables(int restaurantId) {
        return mRepositoryManager.obtainRetrofitService(TableService.class)
                .getTables(restaurantId)
                .compose(RxSchedulerUtils._io_main_o());
    }

    @Override
    public Single<BaseResult> getTable(int tableId, String tableNumber) {
        return mRepositoryManager.obtainRetrofitService(TableService.class)
                .getTable(tableId, tableNumber)
                .compose(MyRxSchedulerUtils._io_main_f());
    }

    @Override
    public Single<BaseOrderResponse> transferFood(RequestBody requestBody) {
        Single ob = mRepositoryManager.obtainRetrofitService(MealService.class)
                .transferFood(requestBody)
                .compose(MyRxSchedulerUtils._io_main_f())
                .flatMap(new Function<BaseOrderResponse, Single<BaseOrderResponse>>() {
                    @Override
                    public Single<BaseOrderResponse> apply(BaseOrderResponse info) throws Exception {
                        if (info != null && info.isSuccess()) {
                            return loadOrder(MealOrder.getInstance().getOrderId());
                        }
                        return Single.just(info);
                    }
                });
        return ob;
    }

    @Override
    public Single<BaseResult> getSplitTables(int tableId) {
        return mRepositoryManager.obtainRetrofitService(TableService.class)
                .getSplitTables(tableId)
                .compose(MyRxSchedulerUtils._io_main_f());
    }

    @Override
    public Single<BaseResult> queryCoupon(int tableId,Long memberId, long couponMemberId, String couponNo, int restaurantId) {
        return mRepositoryManager.obtainRetrofitService(MemberService.class)
                .queryCoupon(tableId,memberId, couponMemberId, couponNo, restaurantId)
                .compose(MyRxSchedulerUtils._io_main_f());
    }

}