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

import android.app.Application;
import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;

import com.billy.cc.core.component.CC;
import com.gingersoft.gsa.cloud.common.core.restaurant.RestaurantInfoManager;
import com.gingersoft.gsa.cloud.common.bean.BaseResult;
import com.gingersoft.gsa.cloud.common.webview.WebviewHelper;
import com.gingersoft.gsa.cloud.component.ComponentName;
import com.gingersoft.gsa.cloud.main.mvp.contract.NewMainContract;
import com.gingersoft.gsa.cloud.main.mvp.model.bean.CheckVersionRequest;
import com.gingersoft.gsa.cloud.main.mvp.ui.activity.NewMainActivity;
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 javax.inject.Inject;

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

import static com.jess.arms.utils.ArmsUtils.startActivity;


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 02/18/2020 17:14
 * <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 NewMainPresenter extends BasePresenter<NewMainContract.Model, NewMainContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    private NewMainActivity IActivity;

    @Inject
    public NewMainPresenter(NewMainContract.Model model, NewMainContract.View rootView) {
        super(model, rootView);
        this.IActivity = (NewMainActivity) rootView;
    }

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

    public void syncRestaurantExtendedConfiguration() {
        mModel.syncRestaurantExtendedConfiguration(RestaurantInfoManager.newInstance().getRestaurantId())
                .subscribeOn(Schedulers.io())
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<BaseResult>(mErrorHandler) {

                    @Override
                    public void onNext(@NonNull BaseResult result) {
                        if (result != null) {

                        } else {
                        }
                    }
                });
    }

    public void checkAppVersion() {
        mModel.checkAppVersion(DeviceUtils.getVersionName(mApplication) + "|" + DeviceUtils.getVersionCode(mApplication),
                2,
                2,
                RestaurantInfoManager.newInstance().getBrandId(),
                RestaurantInfoManager.newInstance().getRestaurantId())
                .subscribeOn(Schedulers.io())
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<CheckVersionRequest>(mErrorHandler) {

                    @Override
                    public void onNext(@NonNull CheckVersionRequest info) {
                        if (info != null) {
                            /**
                             * 操作类型：
                             * 1、不提示更新
                             * 2、提示更新可选择更新
                             * 3、强行更新
                             * 4、跳转goole play下载app 没安装goole play就用webview打开goole网页下载
                             * 5、跳转goole play下载app 没安装goole play就用浏览器打开goole网页下载
                             */
                            int operate = info.getOperate();
                            if (operate == 2 || operate == 3 || operate == 4 || operate == 5) {
                                String updatePath = info.getUpdatePath();
                                if (!TextUtils.isEmpty(updatePath) && !updatePath.equals("null")) {
                                    updateAPK(operate, updatePath);
                                } else {
                                    if (operate == 3) {
                                        mAppManager.appExit();
                                    }
                                }
                            }
                        } else {
                        }
                    }
                });
    }

    public void loginOut() {
        RequestBody requestBody = new FormBody.Builder()
                .add("type", "2")
                .build();
        clearHeartbeat();
        mModel.loginOut(requestBody)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading(null))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<Object>(mErrorHandler) {

                    @Override
                    public void onNext(@NonNull Object info) {
                        mRootView.loginOut();
                    }

                    @Override
                    public void onError(Throwable t) {
                        super.onError(t);
                        mRootView.loginOut();
                    }
                });
    }

    public void addSettlementOperation(int restaurantId) {
        RequestBody requestBody = new FormBody.Builder()
                .add("restaurantId", String.valueOf(restaurantId))
                .build();
        mModel.addSettlementOperation()
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading("調起POS清機中..."))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<BaseResult>(mErrorHandler) {

                    @Override
                    public void onNext(@NonNull BaseResult info) {
                        if (info != null && info.isSuccess()) {
                            if (info.getData() != null) {
//                                PosPay.settlement(IActivity, IActivity, new OnPosActionListener() {
//                                    @Override
//                                    public void onPosSuccess(HywebPosResponse response) {
//                                        mRootView.showMessage("清機成功!");
//                                        updateSettlementOperation(restaurantId, GsonUtils.GsonString(response), 1);
//                                    }
//
//                                    @Override
//                                    public void onPosException(HywebPosResponse response,Exception e) {
//                                        mRootView.showMessage("清機Exception :" + e.getMessage());
//                                        updateSettlementOperation(restaurantId, e.getMessage(), 0);
//                                    }
//
//                                    @Override
//                                    public void onPosInvalid(String e) {
//                                        mRootView.showMessage(e);
//                                        updateSettlementOperation(restaurantId, e, 2);
//                                    }
//
//                                    @Override
//                                    public void onUpdateStatusSuccess(HywebPosResponse response) {
//                                    }
//
//                                    @Override
//                                    public void onUpdateStatusError(Throwable e) {
//                                    }
//                                });
                            }
                        } else {
                            mRootView.showMessage("調起POS清機失敗");
                        }
                    }

                    @Override
                    public void onError(Throwable t) {
                        super.onError(t);
                        mRootView.showMessage("調起POS清機失敗: " + t.getMessage());
                    }
                });
    }

    public void updateSettlementOperation(int restaurantId, String content, int status) {
        RequestBody requestBody = new FormBody.Builder()
                .add("restaurantId", String.valueOf(restaurantId))
                .add("content", content)
                .add("status", String.valueOf(status))
                .build();
        mModel.updateSettlementOperation(requestBody)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading(null))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<BaseResult>(mErrorHandler) {

                    @Override
                    public void onNext(@NonNull BaseResult info) {
                        if (info != null && info.isSuccess()) {
                            mRootView.showMessage("更新清機狀態成功");
                        } else {
                            mRootView.showMessage("更新清機狀態無效");
                        }
                    }

                    @Override
                    public void onError(Throwable t) {
                        super.onError(t);
                        mRootView.showMessage("更新清機狀態失敗: " + t.getMessage());
                    }
                });
    }

    public void clearHeartbeat() {
        RequestBody requestBody = new FormBody.Builder()
                .add("restaurantId", RestaurantInfoManager.newInstance().getRestaurantId() + "")
                .build();

        //關閉心跳
        CC.obtainBuilder(ComponentName.COMPONENT_DELIVERYPICK)
                .setActionName("closeHeart")
                .build()
                .call();

        mModel.clearHeartbeat(requestBody)
                .subscribeOn(Schedulers.io())
                .subscribe(new ErrorHandleSubscriber<Object>(mErrorHandler) {
                    @Override
                    public void onNext(@NonNull Object info) {
                    }
                });
    }

    public void updateAPK(int type, String downApkURL) {
        if (type == 4 || type == 5) {
            if (type == 4) {
                try {
                    DeviceUtils.launchAppDetail(IActivity, mApplication.getPackageName(), "com.android.vending");
                } catch (Exception e) {
                    //跳转goole play下载app
                    CC.obtainBuilder(ComponentName.COMPONENT_WEBVIEW)
                            .setActionName("openWebActivity")
                            .addParam(WebviewHelper.TYPE_KEY, downApkURL)
                            .addParam(WebviewHelper.URL_KEY, WebviewHelper.RIGHT_TYPE_REFRESH)
                            .addParam(WebviewHelper.RIGHT_IMG_TYPE, WebviewHelper.RIGHT_TYPE_REFRESH)
                            .build()
                            .callAsyncCallbackOnMainThread((cc, result) -> {

                            });
                }
            } else {
                try {
                    DeviceUtils.launchAppDetail(IActivity, mApplication.getPackageName(), "com.android.vending");
                } catch (Exception e) {
                    Intent intent = new Intent();
                    intent.setAction("android.intent.action.VIEW");
                    Uri content_url = Uri.parse(downApkURL);
                    intent.setData(content_url);
                    startActivity(intent);
                }
            }
            return;
        }
        boolean isForce = false;
        if (type == 3 || type == 5) {
            isForce = true;
        }
        UpdateAppUtils.from(IActivity)
                .checkBy(UpdateAppUtils.DOWNLOAD_BY_APP) //更新检测方式，默认为VersionCode
//                .serverVersionCode(DeviceUtils.getVersionCode(mApplication))
//                .serverVersionName(DeviceUtils.getVersionName(mApplication))
                .apkPath(downApkURL)
                .showNotification(false) //是否显示下载进度到通知栏，默认为true
//                .updateInfo("發現新版本,點擊下載更新")  //更新日志信息 String
                .downloadBy(UpdateAppUtils.DOWNLOAD_BY_APP) //下载方式：app下载、手机浏览器下载（DOWNLOAD_BY_BROWSER）。默认app下载
                .isForce(isForce) //是否强制更新，默认false 强制更新情况下用户不同意更新则不能使用app
                .update();
    }

    /**
     * 进入应用强制用户开启 存储的权限(保存error log来文件必须拥有读写权限)
     */
//    public void requestExternalStoragePermission() {
//        PermissionUtil.externalStorage(new PermissionUtil.RequestPermission() {
//            @Override
//            public void onRequestPermissionSuccess() {
//            }
//
//            @Override
//            public void onRequestPermissionFailure(List<String> permissions) {
//                mRootView.showMessage(LanguageUtils.get_language_system( "external.storage.permission.hint", ArmsUtils.getString(mApplication, R.string.queue_write_external_storage_permission_hint)));
//                mRootView.killMyself();
//            }
//
//            @Override
//            public void onRequestPermissionFailureWithAskNeverAgain(List<String> permissions) {
//            }
//        }, mRootView.getRxPermissions(), mErrorHandler);
//    }


}
