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

import android.app.Application;

import com.billy.cc.core.component.CC;
import com.gingersoft.gsa.cloud.base.Api;
import com.gingersoft.gsa.cloud.base.application.GsaCloudApplication;
import com.gingersoft.gsa.cloud.base.common.bean.BaseResult;
import com.gingersoft.gsa.cloud.base.common.bean.FoodBean;
import com.gingersoft.gsa.cloud.base.utils.CommonConfiguration;
import com.gingersoft.gsa.cloud.base.utils.JsonUtils;
import com.gingersoft.gsa.cloud.constans.HttpsConstans;
import com.gingersoft.gsa.cloud.database.bean.Discount;
import com.gingersoft.gsa.cloud.database.bean.Function;
import com.gingersoft.gsa.cloud.database.utils.ComboItemDaoUtils;
import com.gingersoft.gsa.cloud.database.utils.DiscountDaoUtils;
import com.gingersoft.gsa.cloud.database.utils.FoodComboDaoUtils;
import com.gingersoft.gsa.cloud.database.utils.FoodDaoUtils;
import com.gingersoft.gsa.cloud.database.utils.FoodModifierDaoUtils;
import com.gingersoft.gsa.cloud.database.utils.FunctionDaoUtils;
import com.gingersoft.gsa.cloud.database.utils.ModifierDaoUtils;
import com.gingersoft.gsa.cloud.download.mvp.model.bean.ComboItemRespone;
import com.gingersoft.gsa.cloud.download.mvp.model.bean.FoodComboRespone;
import com.gingersoft.gsa.cloud.download.mvp.model.bean.DataDownLoadState;
import com.gingersoft.gsa.cloud.download.mvp.model.bean.FoodModifierRespone;
import com.gingersoft.gsa.cloud.download.mvp.model.bean.FunctionRespone;
import com.gingersoft.gsa.cloud.download.mvp.model.bean.ModifierRespone;
import com.gingersoft.gsa.cloud.download.mvp.model.downmanager.DownloadManager;
import com.gingersoft.gsa.cloud.download.mvp.model.downmanager.DownloadRequest;
import com.gingersoft.gsa.cloud.download.mvp.ui.activity.DownloadActivity;
import com.gingersoft.gsa.cloud.download.mvp.ui.adapter.DataDownLoadAdapter;
import com.jess.arms.integration.AppManager;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.http.imageloader.ImageLoader;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;

import javax.inject.Inject;

import com.gingersoft.gsa.cloud.download.mvp.contract.DownloadContract;
import com.jess.arms.utils.DeviceUtils;
import com.jess.arms.utils.RxLifecycleUtils;

import java.util.ArrayList;
import java.util.List;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 12/26/2019 17:59
 * <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 DownloadPresenter extends BasePresenter<DownloadContract.Model, DownloadContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    private DownloadActivity IActivity;

    private DataDownLoadAdapter mAapter;
    private List<DataDownLoadState> mList = new ArrayList<>();

    private String[] downTitles = {"功能列表", "食品列表", "食品細項", "食品套餐", "套餐食品", "食品細項", "折扣信息"};
    //下載所佔比例
    private int[] ratios = {7, 46, 22, 7, 7, 7,4};
    private String urlList[] = {
            HttpsConstans.ROOT_SERVER_ADDRESS_FORMAL + Api.download_function_list,
            HttpsConstans.ROOT_SERVER_ADDRESS_FORMAL + Api.food_list,
            HttpsConstans.ROOT_SERVER_ADDRESS_FORMAL + Api.modifier,
            HttpsConstans.ROOT_SERVER_ADDRESS_FORMAL + Api.food_package_relation,
            HttpsConstans.ROOT_SERVER_ADDRESS_FORMAL + Api.food_comboItem,
            HttpsConstans.ROOT_SERVER_ADDRESS_FORMAL + Api.food_modifiere_relation,
            HttpsConstans.ROOT_SERVER_ADDRESS_FORMAL + Api.restaurant_discount};


    //当前请求响应成功数
    private int responseSuccessCount;
    //当前所需請求數
    private int requestCount = 7;
    //當前下載進度
    private float currentProgress = 0;

    private List<Disposable> mDownDisposable = new ArrayList<>();

    @Inject
    public DownloadPresenter(DownloadContract.Model model, DownloadContract.View rootView) {
        super(model, rootView);
        this.IActivity = (DownloadActivity) rootView;
    }

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

    public void initAdapter() {
        initDataDownItem();
        if (mAapter == null) {
            mAapter = new DataDownLoadAdapter(mApplication, mList);
            mRootView.setDownLoadListAdapter(mAapter);
        }
    }

    public void downAllList() {
        if (!DeviceUtils.netIsConnected(mApplication)) {
            mRootView.showMessage("Can not connect server, retry?");
        }

        requestCount = urlList.length;
        responseSuccessCount = 0;
        currentProgress = 0;
        IActivity.setTvProgress(0);

        stopDownDisposable();

        initDownState();

        setDownAverageRatio();

        int restaurantId = GsaCloudApplication.getRestaurantId(IActivity);

        List<DownloadRequest> requests = getDownloadRequests(getDownloadUrls(restaurantId), restaurantId);

        DownloadManager.getInstance().takeRequestExecute(IActivity, requests, this);
//                .setDownloadResultListener(new DownloadManager.OnDownloadResultListener() {
//
//                    @Override
//                    public void onSuccess(String respose, int downTag) {
//                        switch (downTag) {
//                            case 0://
//                                FunctionRespone functionBean = GsonUtils.GsonToBean(respose, FunctionRespone.class);
//                                if (functionBean != null) {
//                                    FunctionDaoUtils functionDao = new FunctionDaoUtils(IActivity);
//                                    functionDao.deleteAll();
//                                    if (functionBean.isSuccess() && functionBean.getData() != null) {
//                                        functionDao.insertMultFunction(functionBean.getData());
//                                    }
//                                }
//                                break;
//                            case 1:
//                                FoodBean foodBean = GsonUtils.GsonToBean(respose, FoodBean.class);
//                                if (foodBean != null) {
//                                    FoodDaoUtils foodDao = new FoodDaoUtils(IActivity);
//                                    foodDao.deleteAll();
//                                    if (foodBean.isSuccess() && foodBean.getData() != null) {
//                                        foodDao.insertMultFood(foodBean.getData());
//                                    }
//                                }
//                                break;
//                            case 2:
//                                ModifierRespone modifier = GsonUtils.GsonToBean(respose, ModifierRespone.class);
//                                if (modifier != null) {
//                                    ModifierDaoUtils modifierDao = new ModifierDaoUtils(IActivity);
//                                    modifierDao.deleteAll();
//                                    if (modifier.isSuccess() && modifier.getData() != null) {
//                                        modifierDao.insertMultModifier(modifier.getData());
//                                    }
//                                }
//                                break;
//                            case 3:
//                                FoodComboRespone combo = GsonUtils.GsonToBean(respose, FoodComboRespone.class);
//                                if (combo != null) {
//                                    FoodComboDaoUtils comboDao = new FoodComboDaoUtils(IActivity);
//                                    comboDao.deleteAll();
//                                    if (combo.isSuccess() && combo.getData() != null) {
//                                        comboDao.insertMultCombo(combo.getData());
//                                    }
//                                }
//                                break;
//                            case 4:
//                                FoodModifierRespone foodModifier = GsonUtils.GsonToBean(respose, FoodModifierRespone.class);
//                                if (foodModifier != null) {
//                                    FoodModifierDaoUtils foodModifierDao = new FoodModifierDaoUtils(IActivity);
//                                    foodModifierDao.deleteAll();
//                                    if (foodModifier.isSuccess() && foodModifier.getData() != null) {
//                                        foodModifierDao.insertMultFoodModifier(foodModifier.getData());
//                                    }
//                                }
//                                break;
//                        }
//                        mList.get(downTag).setState(2);
//                        mAapter.notifyItemChanged(downTag);
//                    }
//
//                    @Override
//                    public void onError(Throwable t, int downTag) {
//                        mRootView.showMessage("部分下載失敗，點擊刷新按鈕重新下載");
//                    }
//
//                    @Override
//                    public void noComplete() {
//                        endDownReturn();
//                    }
//                });
    }

    private void stopDownDisposable() {
        for (int i = 0; i < mDownDisposable.size(); i++) {
            if (mDownDisposable.get(i) != null && !mDownDisposable.get(i).isDisposed())
                mDownDisposable.get(i).dispose();
        }
        mDownDisposable.clear();
    }

    private List<Function> getFunctions(){
        List<Function > functions = new ArrayList<>();
        Function function = new Function();
        function.setResName("重置餐檯");
        function.setId((long) 1);
        function.setResUrl("table/bottom/init");
        functions.add(function);

        Function function2 = new Function();
        function2.setResName("轉檯");
        function2.setId((long) 2);
        function2.setResUrl("table/bottom/move");
        functions.add(function2);

        Function function3 = new Function();
        function3.setResName("分檯");
        function3.setId((long) 3);
        function3.setResUrl("table/bottom/splite");
        functions.add(function3);

        Function function4 = new Function();
        function4.setResName("上菜紙");
        function4.setId((long) 4);
        function4.setResUrl("table/bottom/parper");
        functions.add(function4);

        Function function5 = new Function();
        function5.setResName("skyorder");
        function5.setId((long) 5);
        function5.setResUrl("table/bottom/skyorder");
        functions.add(function5);
        return functions;
    }

    public void downFun(int downTag) {

        List<Function > functions = getFunctions();

        mModel.downFunctionList()
                .subscribeOn(Schedulers.io())
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<FunctionRespone>(mErrorHandler) {

                    @Override
                    public void onSubscribe(Disposable d) {
                        super.onSubscribe(d);
                        mDownDisposable.add(d);
                    }

                    @Override
                    public void onNext(@NonNull FunctionRespone functionBean) {
                        if (functionBean.isSuccess()) {
                            FunctionDaoUtils functionDao = new FunctionDaoUtils(IActivity);
                            functionDao.deleteAll();
                            if (functionBean.isSuccess() && functionBean.getData() != null) {
                                functionDao.insertMultFunction(functions);
                            }

                            DataDownLoadState loadState = mList.get(downTag);
                            loadState.setState(2);
                            mAapter.notifyItemChanged(downTag);

                            currentProgress += loadState.getRatio();
                            IActivity.setTvProgress(currentProgress);
                            responseSuccessCount++;
                            if (responseSuccessCount == requestCount) {
                                endDownReturn();
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable t) {
                        super.onError(t);
                        DataDownLoadState loadState = mList.get(downTag);
                        loadState.setState(0);
                        mRootView.showMessage("部分下載失敗，點擊刷新按鈕重新下載");
                    }
                });
    }

    public void downFoodList(int downTag) {
        int restaurantId = GsaCloudApplication.getRestaurantId(IActivity);
        mModel.downFoodList(restaurantId)
                .subscribeOn(Schedulers.io())
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<FoodBean>(mErrorHandler) {

                    @Override
                    public void onSubscribe(Disposable d) {
                        super.onSubscribe(d);
                        mDownDisposable.add(d);
                    }

                    @Override
                    public void onNext(@NonNull FoodBean foodBean) {
                        if (foodBean.isSuccess()) {
                            if (foodBean != null) {
                                FoodDaoUtils foodDao = new FoodDaoUtils(IActivity);
                                foodDao.deleteAll();
                                if (foodBean.isSuccess() && foodBean.getData() != null) {
                                    foodDao.insertMultFood(foodBean.getData());
                                }
                            }

                            DataDownLoadState loadState = mList.get(downTag);
                            loadState.setState(2);
                            mAapter.notifyItemChanged(downTag);

                            currentProgress += loadState.getRatio();
                            IActivity.setTvProgress(currentProgress);
                            responseSuccessCount++;
                            if (responseSuccessCount == requestCount) {
                                endDownReturn();
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable t) {
                        super.onError(t);
                        DataDownLoadState loadState = mList.get(downTag);
                        loadState.setState(0);
                        mRootView.showMessage("部分下載失敗，點擊刷新按鈕重新下載");
                    }
                });
    }

    public void downModifier(int downTag) {
        int restaurantId = GsaCloudApplication.getRestaurantId(IActivity);
        mModel.downModifier(restaurantId)
                .subscribeOn(Schedulers.io())
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<ModifierRespone>(mErrorHandler) {

                    @Override
                    public void onSubscribe(Disposable d) {
                        super.onSubscribe(d);
                        mDownDisposable.add(d);
                    }

                    @Override
                    public void onNext(@NonNull ModifierRespone modifier) {
                        if (modifier.isSuccess()) {
                            if (modifier != null) {
                                ModifierDaoUtils modifierDao = new ModifierDaoUtils(IActivity);
                                modifierDao.deleteAll();
                                if (modifier.isSuccess() && modifier.getData() != null) {
                                    modifierDao.insertMultModifier(modifier.getData());
                                    CommonConfiguration.getInstance().saveModifierTopIdConfiguration(modifier.getData());
                                }
                            }
                            DataDownLoadState loadState = mList.get(downTag);
                            loadState.setState(2);
                            mAapter.notifyItemChanged(downTag);

                            currentProgress += loadState.getRatio();
                            IActivity.setTvProgress(currentProgress);
                            responseSuccessCount++;
                            if (responseSuccessCount == requestCount) {
                                endDownReturn();
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable t) {
                        super.onError(t);
                        DataDownLoadState loadState = mList.get(downTag);
                        loadState.setState(0);
                        mRootView.showMessage("部分下載失敗，點擊刷新按鈕重新下載");
                    }
                });
    }

    public void downFoodCombo(int downTag) {
        int restaurantId = GsaCloudApplication.getRestaurantId(IActivity);
        mModel.downFoodCombo(restaurantId)
                .subscribeOn(Schedulers.io())
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<FoodComboRespone>(mErrorHandler) {

                    @Override
                    public void onSubscribe(Disposable d) {
                        super.onSubscribe(d);
                        mDownDisposable.add(d);
                    }

                    @Override
                    public void onNext(@NonNull FoodComboRespone combo) {
                        if (combo.isSuccess()) {
                            if (combo != null) {
                                FoodComboDaoUtils comboDao = new FoodComboDaoUtils(IActivity);
                                comboDao.deleteAll();
                                if (combo.isSuccess() && combo.getData() != null) {
                                    comboDao.insertMultCombo(combo.getData());
                                    CommonConfiguration.getInstance().saveComboIdConfiguration(combo.getData());
                                }
                            }
                            DataDownLoadState loadState = mList.get(downTag);
                            loadState.setState(2);
                            mAapter.notifyItemChanged(downTag);

                            currentProgress += loadState.getRatio();
                            IActivity.setTvProgress(currentProgress);
                            responseSuccessCount++;
                            if (responseSuccessCount == requestCount) {
                                endDownReturn();
                            }

                        }
                    }

                    @Override
                    public void onError(Throwable t) {
                        super.onError(t);
                        DataDownLoadState loadState = mList.get(downTag);
                        loadState.setState(0);
                        mRootView.showMessage("部分下載失敗，點擊刷新按鈕重新下載");
                    }
                });
    }

    public void downComboItem(int downTag) {
        int restaurantId = GsaCloudApplication.getRestaurantId(IActivity);
        mModel.downComboItem(restaurantId)
                .subscribeOn(Schedulers.io())
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<ComboItemRespone>(mErrorHandler) {

                    @Override
                    public void onSubscribe(Disposable d) {
                        super.onSubscribe(d);
                        mDownDisposable.add(d);
                    }

                    @Override
                    public void onNext(@NonNull ComboItemRespone combo) {
                        if (combo.isSuccess()) {
                            if (combo != null) {
                                ComboItemDaoUtils comboDao = new ComboItemDaoUtils(IActivity);
                                comboDao.deleteAll();
                                if (combo.isSuccess() && combo.getData() != null) {
                                    comboDao.insertMultCombo(combo.getData());
                                }
                            }
                            DataDownLoadState loadState = mList.get(downTag);
                            loadState.setState(2);
                            mAapter.notifyItemChanged(downTag);

                            currentProgress += loadState.getRatio();
                            IActivity.setTvProgress(currentProgress);
                            responseSuccessCount++;
                            if (responseSuccessCount == requestCount) {
                                endDownReturn();
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable t) {
                        super.onError(t);
                        DataDownLoadState loadState = mList.get(downTag);
                        loadState.setState(0);
                        mRootView.showMessage("部分下載失敗，點擊刷新按鈕重新下載");
                    }
                });
    }

    public void downFoodModifier(int downTag) {
        int restaurantId = GsaCloudApplication.getRestaurantId(IActivity);
        mModel.downFoodModifier(restaurantId)
                .subscribeOn(Schedulers.io())
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<FoodModifierRespone>(mErrorHandler) {

                    @Override
                    public void onSubscribe(Disposable d) {
                        super.onSubscribe(d);
                        mDownDisposable.add(d);
                    }

                    @Override
                    public void onNext(@NonNull FoodModifierRespone foodModifier) {
                        if (foodModifier.isSuccess()) {
                            if (foodModifier != null) {
                                FoodModifierDaoUtils foodModifierDao = new FoodModifierDaoUtils(IActivity);
                                foodModifierDao.deleteAll();
                                if (foodModifier.isSuccess() && foodModifier.getData() != null) {
                                    foodModifierDao.insertMultFoodModifier(foodModifier.getData());
                                }
                            }
                            DataDownLoadState loadState = mList.get(downTag);
                            loadState.setState(2);
                            mAapter.notifyItemChanged(downTag);

                            currentProgress += loadState.getRatio();
                            IActivity.setTvProgress(currentProgress);
                            responseSuccessCount++;
                            if (responseSuccessCount == requestCount) {
                                endDownReturn();
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable t) {
                        super.onError(t);
                        DataDownLoadState loadState = mList.get(downTag);
                        loadState.setState(0);
                        mRootView.showMessage("部分下載失敗，點擊刷新按鈕重新下載");
                    }
                });
    }

    public void downDiscount(int downTag) {
        int restaurantId = GsaCloudApplication.getRestaurantId(IActivity);
        mModel.downDiscount(restaurantId)
                .subscribeOn(Schedulers.io())
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<BaseResult>(mErrorHandler) {

                    @Override
                    public void onSubscribe(Disposable d) {
                        super.onSubscribe(d);
                        mDownDisposable.add(d);
                    }

                    @Override
                    public void onNext(@NonNull BaseResult result) {
                        if (result.isSuccess()) {
                            if (result != null) {
                                DiscountDaoUtils discountDaoUtils = new DiscountDaoUtils(IActivity);
                                discountDaoUtils.deleteAll();
                                if (result.isSuccess() && result.getData() != null) {
                                    List<Discount> discountList = JsonUtils.parseArray(result.getData(),Discount.class);
                                    discountDaoUtils.insertMultDiscount(discountList);
                                }
                            }
                            DataDownLoadState loadState = mList.get(downTag);
                            loadState.setState(2);
                            mAapter.notifyItemChanged(downTag);

                            currentProgress += loadState.getRatio();
                            IActivity.setTvProgress(currentProgress);
                            responseSuccessCount++;
                            if (responseSuccessCount == requestCount) {
                                endDownReturn();
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable t) {
                        super.onError(t);
                        DataDownLoadState loadState = mList.get(downTag);
                        loadState.setState(0);
                        mRootView.showMessage("部分下載失敗，點擊刷新按鈕重新下載");
                    }
                });
    }

    private void initDownState() {
        for (int i = 0; i < mList.size(); i++) {
            //初始化下载状态
            mList.get(i).setState(1);
        }
        mAapter.notifyDataSetChanged();
    }

    private String[] getDownloadUrls(int restaurantId) {
        for (int i = 0; i < urlList.length; i++) {
            if (i != 0) {
                urlList[i] += "?restaurantId=" + restaurantId;
            }
        }
        return urlList;
    }

    private List<DownloadRequest> getDownloadRequests(String[] urls, int restaurantId) {
        List<DownloadRequest> requests = new ArrayList<>();
        for (int i = 0; i < urls.length; i++) {
            DownloadRequest request = new DownloadRequest();
            request.setRestaurantId(restaurantId);
            request.setDownTag(i);
            request.setUrl(urls[i]);
            requests.add(request);
        }
        return requests;
    }

    private void endDownReturn() {
        if(IActivity.getFromPage() == 1){
            CC.obtainBuilder("Component.Main")
                    .setActionName("showMainActivity")
                    .build()
                    .call();
        }
        mRootView.killMyself();
    }

    public void initDataDownItem() {
        for (int i = 0; i < downTitles.length; i++) {
            DataDownLoadState downLoadState1 = new DataDownLoadState();
            downLoadState1.setState(0);
            downLoadState1.setText(downTitles[i]);
            mList.add(downLoadState1);
        }
    }

    /**
     * 設置下載進度比例
     */
    public void setDownAverageRatio() {
        if (ratios.length != mList.size()) {
            for (int i = 0; i < mList.size(); i++) {
                //初始化下载状态
                mList.get(i).setRatio(100 / mList.size());
            }
            return;
        }
        for (int i = 0; i < mList.size(); i++) {
            //初始化下载状态
            mList.get(i).setRatio(ratios[i]);
        }
    }

}
