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.base.application.GsaCloudApplication;
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.gingersoft.gsa.cloud.ui.activity.WebActivity;
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 checkAppVersion() {
        RequestBody requestBody = new FormBody.Builder()
                .add("version", DeviceUtils.getVersionName(mApplication) + "|" + DeviceUtils.getVersionCode(mApplication))
                .add("type", "2")
                .build();
        mModel.checkAppVersion(requestBody)
                .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("restaurantId", GsaCloudApplication.getRestaurantId(mApplication) + "")
                .build();

        CC.obtainBuilder("Component.OtherOrder")
                .setActionName("closeHeart")
                .build()
                .call();

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

        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();
                        //清空用戶信息
                        GsaCloudApplication.clearMemberInfo();

                    }
                });
    }

    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
                    WebActivity.startWebActivity_url(IActivity, downApkURL, WebActivity.RIGHT_TYPE_REFRESH);
                }
            }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.CHECK_BY_VERSION_CODE) //更新检测方式，默认为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(mApplication, "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);
//    }


}
