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

import android.app.Application;
import com.gingersoft.gsa.cloud.common.core.restaurant.RestaurantInfoManager;
import com.billy.cc.core.component.CC;
import com.gingersoft.gsa.cloud.common.core.user.UserContext;
import com.gingersoft.gsa.cloud.common.Api;
import com.gingersoft.gsa.cloud.common.bean.BaseResult;
import com.gingersoft.gsa.cloud.common.utils.CommonConfiguration;
import com.gingersoft.gsa.cloud.common.utils.JsonUtils;
import com.gingersoft.gsa.cloud.common.core.restaurant.utils.RestaurantExpandInfoUtils;
import com.gingersoft.gsa.cloud.common.utils.gson.GsonUtils;
import com.gingersoft.gsa.cloud.component.ComponentName;
import com.gingersoft.gsa.cloud.common.constans.HttpsConstans;
import com.gingersoft.gsa.cloud.database.bean.ColorBean;
import com.gingersoft.gsa.cloud.database.bean.Discount;
import com.gingersoft.gsa.cloud.database.bean.ExpandInfo;
import com.gingersoft.gsa.cloud.database.bean.Food;
import com.gingersoft.gsa.cloud.database.bean.PrinterListBean;
import com.gingersoft.gsa.cloud.database.utils.ColorDaoUtils;
import com.gingersoft.gsa.cloud.database.utils.ComboItemDaoUtils;
import com.gingersoft.gsa.cloud.database.utils.DiscountDaoUtils;
import com.gingersoft.gsa.cloud.database.utils.ExpandInfoDaoUtils;
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.database.utils.PrinterDeviceDaoUtils;
import com.gingersoft.gsa.cloud.download.mvp.contract.DownloadContract;
import com.gingersoft.gsa.cloud.download.mvp.model.bean.ComboItemRespone;
import com.gingersoft.gsa.cloud.download.mvp.model.bean.DataDownLoadState;
import com.gingersoft.gsa.cloud.download.mvp.model.bean.FoodComboRespone;
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.gingersoft.gsa.cloud.common.function.XFunctionManager;
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.DeviceUtils;
import com.jess.arms.utils.RxLifecycleUtils;

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

import javax.inject.Inject;

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


/**
 * ================================================
 * 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 = {5, 46, 22, 5, 5, 5, 3, 3, 3, 3};
    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,
            HttpsConstans.ROOT_SERVER_ADDRESS_FORMAL + Api.expand_info,
            HttpsConstans.ROOT_SERVER_ADDRESS_FORMAL + Api.printerDevice_list,
            HttpsConstans.ROOT_SERVER_ADDRESS_FORMAL + Api.color_list};

    //当前请求响应成功数
    private int responseSuccessCount;
    //当前所需請求數
    private int requestCount = 0;
    //當前下載進度
    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 = RestaurantInfoManager.newInstance().getRestaurantId();

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

        DownloadManager.getInstance().takeRequestExecute(requests, new DownloadManager.OnRunnableListener() {

            @Override
            public void run(Object o) {
                DownloadRequest request = (DownloadRequest) o;
                switch (request.getDownTag()) {
                    case 0:
                        downFun(request.getDownTag());
                        break;
                    case 1:
                        downFoodList(request.getDownTag());
                        break;
                    case 2:
                        downModifier(request.getDownTag());
                        break;
                    case 3:
                        downFoodCombo(request.getDownTag());
                        break;
                    case 4:
                        downComboItem(request.getDownTag());
                        break;
                    case 5:
                        downFoodModifier(request.getDownTag());
                        break;
                    case 6:
                        downDiscount(request.getDownTag());
                        break;
                    case 7:
                        downExpandInfo(request.getDownTag());
                        break;
                    case 8:
                        downPrinterList(request.getDownTag());
                        break;
                    case 9:
                        downColorList(request.getDownTag());
                        break;
                }
            }
        });
    }

    public 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();
    }


    public void downFun(int downTag) {

        long userId = UserContext.newInstance().getMemberId();

        mModel.downFunctionList(userId)
                .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()) {
                            if (functionBean.getData() != null) {
                                Observable.just(0)
                                        .observeOn(Schedulers.io())
                                        .subscribe(new Consumer<Integer>() {
                                            @Override
                                            public void accept(@NonNull Integer integer) throws Exception {
                                                FunctionDaoUtils functionDao = new FunctionDaoUtils(IActivity);
                                                functionDao.deleteAll();
                                                functionDao.insertMultFunction(functionBean.getData());
                                            }
                                        });
                                XFunctionManager.newInstance().updateFunctions(functionBean.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 downFoodList(int downTag) {
        int restaurantId = RestaurantInfoManager.newInstance().getRestaurantId();
        mModel.downFoodList(restaurantId)
                .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()) {
                            List<Food> foodList = GsonUtils.jsonToList(result.getData(), Food.class);
                            if (foodList != null) {
                                Observable.just(0)
                                        .observeOn(Schedulers.io())
                                        .subscribe(new Consumer<Integer>() {
                                            @Override
                                            public void accept(@NonNull Integer integer) throws Exception {
                                                FoodDaoUtils foodDao = new FoodDaoUtils(IActivity);
                                                foodDao.deleteAll();
                                                foodDao.insertMultFood(foodList);
                                            }
                                        });
                            }

                            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 = RestaurantInfoManager.newInstance().getRestaurantId();
        mModel.downModifier(restaurantId)
                .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.getData() != null) {
                                Observable.just(0)
                                        .observeOn(Schedulers.io())
                                        .subscribe(new Consumer<Integer>() {
                                            @Override
                                            public void accept(@NonNull Integer integer) throws Exception {
                                                ModifierDaoUtils modifierDao = new ModifierDaoUtils(IActivity);
                                                modifierDao.deleteAll();
                                                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 = RestaurantInfoManager.newInstance().getRestaurantId();
        mModel.downFoodCombo(restaurantId)
                .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.getData() != null) {
                                Observable.just(0)
                                        .observeOn(Schedulers.io())
                                        .subscribe(new Consumer<Integer>() {
                                            @Override
                                            public void accept(@NonNull Integer integer) throws Exception {
                                                FoodComboDaoUtils comboDao = new FoodComboDaoUtils(IActivity);
                                                comboDao.deleteAll();
                                                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 = RestaurantInfoManager.newInstance().getRestaurantId();
        mModel.downComboItem(restaurantId)
                .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.getData() != null) {
                                Observable.just(0)
                                        .observeOn(Schedulers.io())
                                        .subscribe(new Consumer<Integer>() {
                                            @Override
                                            public void accept(@NonNull Integer integer) throws Exception {
                                                ComboItemDaoUtils comboDao = new ComboItemDaoUtils(IActivity);
                                                comboDao.deleteAll();
                                                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 = RestaurantInfoManager.newInstance().getRestaurantId();
        mModel.downFoodModifier(restaurantId)
                .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.getData() != null) {
                                Observable.just(0)
                                        .observeOn(Schedulers.io())
                                        .subscribe(new Consumer<Integer>() {
                                            @Override
                                            public void accept(@NonNull Integer integer) throws Exception {
                                                FoodModifierDaoUtils foodModifierDao = new FoodModifierDaoUtils(IActivity);
                                                foodModifierDao.deleteAll();
                                                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 = RestaurantInfoManager.newInstance().getRestaurantId();
        mModel.downDiscount(restaurantId)
                .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.getData() != null) {
                                Observable.just(0)
                                        .observeOn(Schedulers.io())
                                        .subscribe(new Consumer<Integer>() {
                                            @Override
                                            public void accept(@NonNull Integer integer) throws Exception {
                                                DiscountDaoUtils discountDaoUtils = new DiscountDaoUtils(IActivity);
                                                discountDaoUtils.deleteAll();
                                                List<Discount> discountList = JsonUtils.parseArray(result.getData(), Discount.class);
                                                if (discountList != null) {
                                                    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("部分下載失敗，點擊刷新按鈕重新下載");
                    }
                });
    }

    public void downExpandInfo(int downTag) {
        int restaurantId = RestaurantInfoManager.newInstance().getRestaurantId();
        mModel.downExpandInfo(restaurantId)
                .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.getData() != null) {
                                Observable.just(0)
                                        .observeOn(Schedulers.io())
                                        .subscribe(new Consumer<Integer>() {
                                            @Override
                                            public void accept(@NonNull Integer integer) throws Exception {
                                                ExpandInfoDaoUtils expandInfoDaoUtils = new ExpandInfoDaoUtils(IActivity);
                                                expandInfoDaoUtils.deleteAll();
                                                List<ExpandInfo> expandInfoList = JsonUtils.parseArray(result.getData(), ExpandInfo.class);
                                                if (expandInfoList != null) {
                                                    expandInfoDaoUtils.insertMultExpandInfo(expandInfoList);
                                                    RestaurantExpandInfoUtils.setCommonExpandInfo(expandInfoList);
                                                }
                                            }
                                        });
                            }
                            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 downPrinterList(int downTag) {
        int restaurantId = RestaurantInfoManager.newInstance().getRestaurantId();
        mModel.downPrinterList(restaurantId)
                .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.getData() != null) {
                                Observable.just(0)
                                        .observeOn(Schedulers.io())
                                        .subscribe(new Consumer<Integer>() {
                                            @Override
                                            public void accept(@NonNull Integer integer) throws Exception {
                                                PrinterDeviceDaoUtils printerDeviceDaoUtils = new PrinterDeviceDaoUtils(IActivity);
                                                printerDeviceDaoUtils.deleteAll();
                                                PrinterListBean printerListBean = JsonUtils.parseObject(result.getData(), PrinterListBean.class);
                                                if (printerListBean != null && printerListBean.getList() != null) {
                                                    printerDeviceDaoUtils.insertMultPrinterDeviceBean(printerListBean.getList());
                                                }
                                            }
                                        });
                            }
                            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 downColorList(int downTag) {
        mModel.downColorList()
                .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.getData() != null) {
                                Observable.just(0)
                                        .observeOn(Schedulers.io())
                                        .subscribe(new Consumer<Integer>() {
                                            @Override
                                            public void accept(@NonNull Integer integer) throws Exception {
                                                ColorDaoUtils colorDaoUtils = new ColorDaoUtils(IActivity);
                                                colorDaoUtils.deleteAll();
                                                List<ColorBean> colorBeanList = JsonUtils.parseArray(result.getData(), ColorBean.class);
                                                if (colorBeanList != null) {
                                                    colorDaoUtils.insertMultColorBean(colorBeanList);
                                                }
                                            }
                                        });
                            }
                            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) {
        String[] urls = new String[urlList.length];
        for (int i = 0; i < urlList.length; i++) {
            if (i != 0) {
                urls[i] = urlList[i] += "?restaurantId=" + restaurantId;
            }
        }
        return urls;
    }

    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(ComponentName.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]);
        }
    }

}
