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.bean.BaseResult;
import com.gingersoft.gsa.cloud.common.constans.HttpsConstans;
import com.gingersoft.gsa.cloud.common.core.restaurant.RestaurantInfoManager;
import com.gingersoft.gsa.cloud.common.utils.gson.GsonUtils;
import com.gingersoft.gsa.cloud.common.utils.time.TimeUtils;
import com.gingersoft.gsa.cloud.common.webview.WebviewHelper;
import com.gingersoft.gsa.cloud.component.ComponentName;
import com.gingersoft.gsa.cloud.main.mvp.contract.HomeContract;
import com.gingersoft.gsa.cloud.main.mvp.model.bean.CheckVersionRequest;
import com.gingersoft.gsa.cloud.main.mvp.model.bean.MainBusinessBean;
import com.gingersoft.gsa.cloud.main.mvp.ui.activity.MainActivity;
import com.gingersoft.gsa.cloud.main.mvp.ui.fragment.HomeFragment;
import com.gingersoft.gsa.cloud.pay.pos.OnPosActionListener;
import com.gingersoft.gsa.cloud.pay.pos.PosPay;
import com.gingersoft.gsa.cloud.pay.pos.hyweb.bean.response.pos.HywebPosResponse;
import com.jess.arms.di.scope.FragmentScope;
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.retrofiturlmanager.RetrofitUrlManager;
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 01/10/2020 15:02
 * <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>
 * ================================================
 */
@FragmentScope
public class HomePresenter extends BasePresenter<HomeContract.Model, HomeContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    private MainActivity IActivity;

    @Inject
    public HomePresenter(HomeContract.Model model, HomeContract.View rootView) {
        super(model, rootView);
        HomeFragment homeFragment = (HomeFragment) rootView;;
        this.IActivity = (MainActivity) homeFragment.getActivity();
    }

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

    public void getRestaurantReport(String restaurantId) {
        RequestBody requestBody = new FormBody.Builder()
                .add("restaurantId", restaurantId)
                .add("startTime", TimeUtils.getYesterdayTime(TimeUtils.DATE_FORMAT_DATE))
                .add("endTime", TimeUtils.getCurrentTimeInString(TimeUtils.DATE_FORMAT_DATE))
                .build();

        mModel.getRestaurantReport(requestBody)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading(""))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<MainBusinessBean>(mErrorHandler) {

                    @Override
                    public void onNext(@NonNull MainBusinessBean info) {
                        if (info != null && info.isSuccess()) {
                            if (info.getData() != null) {
//                                mRootView.loadBusinessInfo(info.getData());
                            }
                        } else {
                            mRootView.showMessage("營業報表獲取失敗");
                        }
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        RetrofitUrlManager.getInstance().putDomain("common", HttpsConstans.ROOT_SERVER_ADDRESS_FORMAL);
                    }

                    @Override
                    public void onError(Throwable t) {
                        super.onError(t);
                        RetrofitUrlManager.getInstance().putDomain("common", HttpsConstans.ROOT_SERVER_ADDRESS_FORMAL);
                    }
                });
    }

    /**
     * 獲取餐廳功能列表
     */
    public void getRestaurantFunList(String restaurantId) {
        mModel.getRestaurantFunList(restaurantId)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> mRootView.showLoading(""))
                .subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doAfterTerminate(() -> mRootView.hideLoading())
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<String>(mErrorHandler) {
                    @Override
                    public void onNext(@NonNull String info) {
                    }
                });
    }

    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() {
//        RequestBody requestBody = new FormBody.Builder()
//                .add("version", )
//                .add("type", "2")
//                .build();
        mModel.checkAppVersion(DeviceUtils.getVersionName(mApplication) + "|" + DeviceUtils.getVersionCode(mApplication))
                .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();
    }

}
