package com.yidianling.user.modular_service

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import androidx.fragment.app.Fragment
import android.text.TextUtils
import com.alibaba.android.arouter.facade.annotation.Route
import com.ydl.ydlcommon.base.BaseApp
import com.ydl.ydlcommon.bean.VersionData
import com.ydl.ydlcommon.data.http.RxUtils
import com.ydl.ydlcommon.data.http.ThrowableConsumer
import com.ydl.ydlcommon.utils.ActivityManager
import com.ydl.ydlcommon.utils.ApkUpdateDialog
import com.yidianling.common.tools.RxAppTool
import com.yidianling.user.LoginHelper
import com.yidianling.user.LoginUtils
import com.yidianling.user.UserConstants
import com.yidianling.user.UserHelper
import com.yidianling.user.api.bean.UserResponseBean
import com.yidianling.user.api.bean.UserSettingBean
import com.yidianling.user.api.listener.LoginCallBackListener
import com.yidianling.user.api.listener.SecretDataListener
import com.yidianling.user.api.listener.UserInfoFromApiListener
import com.yidianling.user.api.listener.VersionUpdateStatusListener
import com.yidianling.user.api.service.IUserService
import com.yidianling.user.http.UserHttpImpl
import com.yidianling.user.mine.MineFragment
import com.yidianling.user.mine.data.AppDataManager
import com.yidianling.user.mine.utils.UpdateUtil
import com.yidianling.user.route.UserIn
import com.yidianling.user.safePrivate.FingerPrintCheckActivity
import com.yidianling.user.safePrivate.FingerPrintUtil
import com.yidianling.user.safePrivate.HandUnlockCheckActivity
import com.yidianling.user.safePrivate.PrivacyActivity
import com.yidianling.user.ui.InputPhoneActivity
import com.yidianling.user.ui.LoginActivity
import com.yidianling.user.ui.login.OneKeyLoginHelp
import com.yidianling.user.ui.login.RegisterAndLoginActivity
import com.yidianling.user.ui.login.SecretActivity
import com.yidianling.user.widget.utils.PrivacyDialogUtils
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.functions.Consumer
import io.reactivex.schedulers.Schedulers

/**
 * author : Zhangwenchao
 * e-mail : zhangwch@yidianling.com
 * time   : 2018/04/13
 */
@Route(path = "/user/UserService")
public class UserServiceImp : IUserService {

    constructor()

    override fun init(context: Context?) {

    }

    override fun getUserSetting(): UserSettingBean? {
        return UserHelper.getUsetSetting()
    }

    override fun updateUserInfoSp(userInfo: UserResponseBean.UserInfo?) {
        UserHelper.updateUserinfo(userInfo)
    }

    override fun updateUserSetingSp(userSetting: UserSettingBean?) {
        UserHelper.updateUserSetting(userSetting)
    }

    override fun setChatTeamHisShowed(showed: Boolean) {
        UserHelper.getUsetSetting()?.chatTeamHisShowed = showed
    }

    override fun setUserResponse(userInfo: UserResponseBean?) {
        UserHelper.setUserinfo(userInfo)
    }

    override fun getUserResponse(): UserResponseBean? {
        return UserHelper.getUserInfo()
    }

    override fun isLogin(): Boolean {
        return UserHelper.isLogin()
    }

    override fun isFirstLogin(): Boolean {
        return UserHelper.getUserInfo()?.firstLogin==1
    }

    override fun setFirstLogin(first: Boolean) {
        var value : Int = if (first) 1 else 2 //1是2否
        UserHelper.getUserInfo()?.firstLogin = value
    }

    override fun isSafePrivacyClicked(): Boolean {
        return UserHelper.getUsetSetting()?.meSafePrivateIsClick?:true
    }

    override fun putSafePrivacyClicked(clicked: Boolean) {
        UserHelper.getUsetSetting()?.meSafePrivateIsClick = clicked
    }

    override fun getUserInfo(): UserResponseBean.UserInfo? {
        return UserHelper.getUserInfo()?.userInfo
    }

    @SuppressLint("CheckResult")
    override fun getUserInfoFromApi(listener: UserInfoFromApiListener) {
        AppDataManager.getHttp().getUserInfo()
            .compose(RxUtils.resultJavaData())
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(Consumer {
                try {
                    listener.apiResponse(it)
                }catch (e: Exception) {
                    listener.onFailure(e.toString())
                }
            }, object : ThrowableConsumer() {
                override fun accept(msg: String) {
                    listener.onFailure(msg)
                }
            })
    }

    override fun setUserInfo(userInfo: UserResponseBean.UserInfo?) {
        UserHelper.getUserInfo()?.userInfo = userInfo
    }

    override fun isBindPhone(): Boolean {
        return !TextUtils.isEmpty(UserHelper.getUserInfo()?.userInfo?.phone)
    }

    override fun putUnlockCheckSuccessTime(time: Long) {
        UserHelper.getUsetSetting()?.unLockCheckSuccessTime = time
    }

    override fun getChatTeamHisShow(): Boolean {
        return UserHelper.getUsetSetting()?.chatTeamHisShowed?:true
    }

    override fun privacyIntent(activity: Activity): Intent {
        return Intent(activity, PrivacyActivity::class.java)
    }

    override fun loginWayIntent(context: Context): Intent {
        return RegisterAndLoginActivity.getIntent(context)
    }

    override fun inputPhoneIntent(activity: Activity, smsAction: String): Intent {
        return InputPhoneActivity.newIntent(activity, smsAction)
    }

    override fun safeTipViewGone(): Boolean {
        //如果是非登录状态 或者 app指纹开启 或者 手势密码不为空 或者 已提示过安全解锁 -> 隐藏 设置密码提示
        return !UserHelper.isLogin() || FingerPrintUtil.instance().fingerPrintIsOpen()
                || !TextUtils.isEmpty(FingerPrintUtil.instance().getHandPass())
                || FingerPrintUtil.instance().getTrendsSafeTip()
    }

    override fun setTrendsSafeTip(status: Boolean) {
        FingerPrintUtil.instance().setTrendsSafeTip(status)
    }

    override fun errorAgainTime(): Long {
        return FingerPrintUtil.errorAgainTime
    }

    override fun isFirstStart(): Boolean {
        val lastVersionCode : Int = UserHelper.getUsetSetting()?.lastVersionCode?:0
        val currentVersionCode : Int = RxAppTool.getAppVersionCode(BaseApp.getApp())
        if (lastVersionCode < currentVersionCode) {
            UserHelper.getUsetSetting()?.lastVersionCode = currentVersionCode
            return true
        }
        return false
    }

    override fun clearUserInfo() {
        UserHelper.setUserinfo(null)
        UserIn.clearImData()
    }

    override fun getMineFragment(): Fragment {
        return MineFragment()
    }

    override fun updateUI(fragment: Fragment) {
        if (fragment is MineFragment) {
            fragment.updateUI()
        }
    }

    override fun checkUpVersion(activity: Activity, listener: VersionUpdateStatusListener) {
        UpdateUtil.getInstance().setUpdateListener(activity,
            object : UpdateUtil.VersionUpdateListener {
                override fun setUpdateData(version1: VersionData) {
                    //根据获取的version判断是否需要更新
                    var isUpdate = UpdateUtil.getInstance().needUpdate(activity, version1.ver)
                    if (activity != null && isUpdate) {
                        listener.shouldUpdate()
                        AppDataManager.getLocal().putUpdate(true)
                        ApkUpdateDialog(activity).setData(version1).setCancle(false).show()

                    } else {
                        listener.notUpdate()
                        AppDataManager.getLocal().putUpdate(false)
                    }
                }

                override fun onFailed() {

                }
            })
    }

    override fun getRedPocketTime(): Long {
        return AppDataManager.getLocal().getRedPocketTime()
    }

    override fun putRedPocketTime(time: Long) {
        AppDataManager.getLocal().putRedPocketTime(time)
    }

    override fun hasUpdate(): Boolean {
        return AppDataManager.getLocal().hasUpdate()
    }

    override fun hasPrivacyDialog(): Boolean {
        return PrivacyDialogUtils.INSTANCE.privacyDialog != null
    }

    override fun initPrivacyDialog(activity: Activity, content: String, time: String) {
        PrivacyDialogUtils.INSTANCE.initPrivacy(activity, content, time)
    }

    override fun privacyDialogIsShow(): Boolean {
        return PrivacyDialogUtils.INSTANCE.privacyDialog?.isShowing?:true
    }

    override fun showPrivacyDialog() {
        PrivacyDialogUtils.INSTANCE.privacyDialog?.show()
    }

    override fun loginUtilsLogout() {
        LoginUtils.logout()
    }

    override fun setChannelId() {
        LoginHelper.setChannelId()
    }

    override fun logoutlearLocal() {
        LoginUtils.logoutClearLocal()
    }

    override fun shouldShowFingerPage(activity: Activity) {
        if(!(activity is HandUnlockCheckActivity
                || activity is FingerPrintCheckActivity
                || activity is LoginActivity)
                && FingerPrintUtil.instance().isShowActivity()) {
            //跳转解锁页面
            val intent = Intent(
                ActivityManager.getInstance().getTopTaskActivity(),
                HandUnlockCheckActivity::class.java
            )
            intent.putExtra("isFromBackground", true)
            ActivityManager.getInstance().getTopTaskActivity().startActivity(intent)
        }
    }

    override fun shouldShowFingerPageFromKill(activity: Activity, isSplashActivity: Boolean) {
        if (FingerPrintUtil.instance().appIsSetUnLockPass() && isSplashActivity) {
            //跳转解锁页面
            val intent = Intent(activity, HandUnlockCheckActivity::class.java)
            intent.putExtra("isFromBackground", true)
            activity.startActivity(intent)
        }
    }

    override fun wxBindToInputhonePage(activity: Activity) {
        InputPhoneActivity.start(activity, UserConstants.BIND_PHONE_ACTION, null, false)
    }

    override fun getSecretPageRequestOkCode(): Int {
        return SecretActivity.SECRET_PAGE_REQUEST_OK_CODE
    }

    @SuppressLint("CheckResult")
    override fun getSecretDataApi(activity: Activity, listener: SecretDataListener) {
        UserHttpImpl.Companion.getInstance().getSecretJavaData()
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(Consumer {
                if (it.code == 200) {
                    SecretActivity.startProtocol(activity, it.data)
                } else {
                    listener.onOtherAction()
                }
            }, object : ThrowableConsumer() {
                override fun accept(msg: String) {
                    listener.onOtherAction()
                }
            })
    }

    override fun startFromGuide(context: Context, isBindPhone: Boolean, isFromGudile: Boolean) {
        RegisterAndLoginActivity.startFromGuide(context, isBindPhone, isFromGudile)
    }
    /**
     * 调用优先使用一键登录，并返回调用时的登录状态，
     * @param isOpenDialog true:一键登录使用弹窗展示 false:一键登录使用全屏模式
     * @return true：已登录，不触发登录跳转，false：未登录，优先一键登录
     * */
    override fun loginByOneKeyLogin(context: Context, isOpenDialog: Boolean):Boolean {
        return OneKeyLoginHelp.startLoginByStatus(context,isOpenDialog)
    }

    override fun loginByOneKeyLoginCallBack(
        context: Context,
        isOpenDialog: Boolean,
        listener: LoginCallBackListener
    ) {
        OneKeyLoginHelp.startLoginByStatusLoginCallBack(context,isOpenDialog,listener)
    }
}