package com.bc_chat.mine.setting

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.view.View
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bc_chat.bc_base.BuildConfig
import com.bc_chat.bc_base.ImService.ImRongService
import com.bc_chat.bc_base.WebViewActivity
import com.bc_chat.bc_base.config.RouteConfig
import com.bc_chat.bc_base.entity.ApkVersion
import com.bc_chat.bc_base.utils.Const
import com.bc_chat.mine.R
import com.bc_chat.mine.contract.SettingContract
import com.bc_chat.mine.databinding.ActivitySettingBinding
import com.bc_chat.mine.presenter.SettingPresenter
import com.bc_chat.mine.window.HourMinuteDialogFragment
import com.sinata.download.service.DownloadService
import com.sinata.download.utils.VersionPreferences
import com.zhaohaoting.framework.abs.BaseActivity
import com.zhaohaoting.framework.ui.dialog.CustomDialog
import com.zhaohaoting.framework.utils.*
import com.zhaohaoting.framework.view.picker.base.util.DateUtils
import io.reactivex.Observable
import io.rong.imkit.notification.MessageNotificationManager
import io.rong.imlib.RongIMClient
import java.text.SimpleDateFormat
import java.util.*

/**
 * author：Created by zhaohaoting on 2019/2/25
 * email：526309416@qq.com
 * desc：设置 351
 */
@Route(path = RouteConfig.SETTING_ACTIVITY)
class SettingActivity : BaseActivity<SettingPresenter>(), View.OnClickListener, SettingContract.View {

    companion object {
        const val REQUESTCODE_MODIFY_PWD = 351
    }

    private val binding by lazy {
        rootDataBinding as ActivitySettingBinding
    }

    override fun getLayoutResId(): Int = R.layout.activity_setting

    override fun initPresenter(): SettingPresenter? = SettingPresenter(this)

    override fun initialize() {
        binding.onClickEvent = this
        val dataFormat = SimpleDateFormat("HH:mm:ss", Locale.CHINA)
        val dataFormat1 = SimpleDateFormat("HH:mm", Locale.CHINA)
        binding.tvVersion.text = "V" + BuildConfig.VERSION_NAME
        val versionCode = VersionPreferences.getString(VersionPreferences.VERSION_CODE, "0")
        if (versionCode.compareTo(BuildConfig.VERSION_NAME) > 0) {
            binding.newVersion.visibility = View.VISIBLE
        } else {
            binding.newVersion.visibility = View.GONE
        }
        try {
            binding.tvCache.text = DataCache.calculateCacheSize(this)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        binding.checkNotice.setOnClickListener {
            val isChecked = binding.checkNotice.isChecked
            binding.disturbTime.visibility = if (isChecked) View.VISIBLE else View.GONE
            if (isChecked) {
                val disturbTime = Preferences.getString(Const.DISTURB_TIME, "")
                if (Check.isEmpty(disturbTime)) {
                    setNotificationQuietHours("23", "31")
                } else {
                    val split = disturbTime.split("-")
                    setNotificationQuietHours(split[0], split[1])
                }
            } else {
                RongIMClient.getInstance().removeNotificationQuietHours(object : RongIMClient.OperationCallback() {
                    override fun onSuccess() {
                        MessageNotificationManager.getInstance().clearNotificationQuietHours()
                    }

                    override fun onError(p0: RongIMClient.ErrorCode?) {
                    }
                })
            }
        }
        RongIMClient.getInstance().getNotificationQuietHours(object : RongIMClient.GetNotificationQuietHoursCallback() {
            override fun onError(p0: RongIMClient.ErrorCode?) {
            }

            override fun onSuccess(p0: String?, p1: Int) {
                if (Check.isEmpty(p0)) {
                    binding.checkNotice.isChecked = false
                } else {
                    binding.checkNotice.isChecked = true
                    val time = dataFormat.parse(p0).time
                    val endTime = (p1 + 1) * 60 * 1000 + time
                    binding.disturbTime.text = dataFormat1.format(time) + "-" + dataFormat1.format(endTime)
                }
                binding.disturbTime.visibility = if (binding.checkNotice.isChecked) View.VISIBLE else View.GONE
            }
        })
    }

    @SuppressLint("SetTextI18n")
    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.tv_modify_pwd -> {
                ARouter.getInstance().build(RouteConfig.MODIFY_PASSWORD_ACTIVITY)
                        .navigation(this, REQUESTCODE_MODIFY_PWD)
            }
            R.id.ll_clear_cache -> {
                CustomDialog.Builder(this).setTitle("清除缓存").setMessage("您确定要清除缓存吗？")
                        .setPositiveButton("确定") { dialog, _ ->
                            dialog.dismiss()
                            clearCache()
                        }.setNegativeButton("取消") { dialog, _ ->
                            dialog.dismiss()
                        }.create().show()
            }
            R.id.tv_above -> {
                presenter.loadWebPage(Const.WebPageType.AOUT_PROTOCOL)
            }
            R.id.tv_login_out -> {
                CustomDialog.Builder(this)
                        .setTitle("退出登录")
                        .setMessage("确定要退出登录?")
                        .setNegativeButton("取消") { dialog, _ -> dialog?.dismiss() }
                        .setPositiveButton("确定") { dialog, _ ->
                            ARouter.getInstance().navigation(ImRongService::class.java)?.loginOut(this)
                        }.create().show()
            }
            R.id.disturb_time -> {
                val hourMinuteDialogFragment = HourMinuteDialogFragment()
                hourMinuteDialogFragment.show(fragmentManager)
                hourMinuteDialogFragment.setSelectDateListener { startHour, endHour ->
                    setNotificationQuietHours(startHour, endHour)
                }
            }
            R.id.version_layout -> {
                presenter.getUpdateVerson(true)
            }
            R.id.tv_modify_pay_pwd -> {
                ARouter.getInstance().build(RouteConfig.MODIFY_PAY_PASSWORD_ACTIVITY).navigation();
            }
        }
    }

    private fun setNotificationQuietHours(startHour: String, endHour: String) {
        RongIMClient.getInstance().setNotificationQuietHours(
                "$startHour:00:00",
                (DateUtils.trimZero(endHour) - DateUtils.trimZero(startHour) - 1) * 60 + 59,
                object : RongIMClient.OperationCallback() {
                    override fun onError(p0: RongIMClient.ErrorCode?) {
                        ToastUtils.show(p0?.message)
                    }

                    override fun onSuccess() {
                        Preferences.saveString(Const.DISTURB_TIME, "$startHour-$endHour")
                        binding.disturbTime.text = "$startHour:00-${getStringHour(endHour)}:00"
                        MessageNotificationManager.getInstance().setNotificationQuietHours(
                                "$startHour:00:00",
                                (DateUtils.trimZero(endHour) - DateUtils.trimZero(startHour) - 1) * 60 + 59
                        )
                    }
                })
    }

    private fun getStringHour(hour: String): String {
        val hourInt = DateUtils.trimZero(hour)
        val stringBuilder = StringBuilder()
        if (hourInt >= 24) {
            val endHour = hourInt - 24
            if (endHour >= 10) {
                stringBuilder.append(endHour)
            } else {
                stringBuilder.append(0).append(endHour)
            }
        } else {
            if (hourInt >= 10) {
                stringBuilder.append(hourInt)
            } else {
                stringBuilder.append(0).append(hourInt)
            }
        }
        return stringBuilder.toString();
    }

    override fun getUpdateVersonSuccess(verson: ApkVersion) {
        verson?.let {
            VersionPreferences.saveString(VersionPreferences.VERSION_CODE, it.version)
            if (verson.version.compareTo(BuildConfig.VERSION_NAME) > 0) {
                CustomDialog.Builder(this)
                        .setTitle(getString(R.string._has_new_version, verson.version))
                        .setMessage(
                                getString(
                                        R.string.version_content_tip1_,
                                        if (verson.content == null) "" else verson.content
                                )
                        )
                        .setNegativeButton(R.string.talk_later, null)
                        .setPositiveButton(R.string.immediately_update) { dialog, which ->
                            downLoadApk(verson.url)
                            ToastUtils.show(R.string.add_download_queue)
                        }
                        .create().show()
            } else {
                ToastUtils.show(R.string.not_new_version)
            }
        }
    }

    private fun downLoadApk(url: String?) {
        val service = Intent(this, DownloadService::class.java)
        service.putExtra("url", url)
        service.putExtra("type", DownloadService.TYPE_APK)
        startService(service)
    }

    override fun getUpdateVersonFailure(e: Exception) {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }

    override fun loadWebPageSuccess(content: String) {
        WebViewActivity.startActivity(this, content, "关于我们", 1)
    }

    private fun clearCache() {
        loadingDialog.show()
        val subscribe = Observable.fromCallable {
            DataCache.clearCacheData(this)
            DataCache.calculateCacheSize(this)
        }.compose(RxSchedulers.applyObservableAsync()).subscribe({ s ->
            binding.tvCache.text = s
            loadingDialog.dismiss()
        }, { loadingDialog.dismiss() })
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode != Activity.RESULT_OK) return

    }
}