package com.yzx.escreen.fragment

import android.graphics.Color
import android.text.InputType
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.KeyboardUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.NetworkUtils
import com.qmuiteam.qmui.widget.dialog.QMUIDialog
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog.Builder.ICON_TYPE_FAIL
import com.yzx.escreen.R
import com.yzx.escreen.activity.LoginActivity
import com.yzx.escreen.adapter.DeviceListAdapter
import com.yzx.escreen.fragment.base.BaseFragment
import com.yzx.escreen.model.Device
import com.yzx.escreen.model.Pager
import com.yzx.escreen.model.TeacherInfo
import com.yzx.escreen.model.TimeShow
import com.yzx.escreen.model.User
import com.yzx.escreen.model.UserVersionCheck
import com.yzx.escreen.presenter.SettingPresenter
import com.yzx.escreen.presenter.SettingView
import com.yzx.escreen.utils.hideNavigationBar
import kotlinx.android.synthetic.main.fragment_setting.btnNormal
import kotlinx.android.synthetic.main.fragment_setting.btnOpen
import kotlinx.android.synthetic.main.fragment_setting.btnRefresh
import kotlinx.android.synthetic.main.fragment_setting.checkAll
import kotlinx.android.synthetic.main.fragment_setting.checkVersion
import kotlinx.android.synthetic.main.fragment_setting.goPageOne
import kotlinx.android.synthetic.main.fragment_setting.loadingLayout
import kotlinx.android.synthetic.main.fragment_setting.nextTxtBtn
import kotlinx.android.synthetic.main.fragment_setting.pageTv
import kotlinx.android.synthetic.main.fragment_setting.preTxtBtn
import kotlinx.android.synthetic.main.fragment_setting.recyclerView
import kotlinx.android.synthetic.main.fragment_setting.sysExitBtn
import kotlinx.android.synthetic.main.fragment_setting.totalTv
import kotlinx.android.synthetic.main.fragment_setting.userNameBox
import kotlinx.android.synthetic.main.fragment_setting.userNameTv
import kotlinx.android.synthetic.main.layout_loading.view.QMUIEmptyView
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.jetbrains.anko.support.v4.toast
import org.jetbrains.anko.textColor
import kotlin.system.exitProcess

class SettingFragment : BaseFragment<SettingPresenter>(), SettingView {

    companion object {

        @JvmStatic
        fun getNewInstance() =
            SettingFragment()
    }

    private var count = 0
    private val run = Runnable {
        count = 0
    }
    private var isLoading = false
    private var mPager = Pager()
    var list = mutableListOf<Device>()
    private var isRefresh = false

    private val mAdapter: DeviceListAdapter by lazy {
        val list = mutableListOf<Device>()
        DeviceListAdapter(list)
    }

    override val inflateId: Int
        get() = R.layout.fragment_setting

    override fun initView() {
        sysExitBtn.setOnClickListener {
            count++
            sysExitBtn.removeCallbacks(run)
            sysExitBtn.postDelayed(run, 1000)
            if (count >= 5) {
                showExitDialog()
            }
        }

        recyclerView.layoutManager =
            LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
        recyclerView.adapter = mAdapter

        mAdapter.setOnItemChildClickListener { adapter, view, position ->
            val item = mAdapter.getItem(position)
            val idList = mutableListOf<Int>()
            idList.add(item.id)
            LogUtils.d("deviceids",idList.joinToString(",") )
            when (view.id) {
                R.id.actionNormal -> {
                    showActionDialog(idList, 0)
                }

                R.id.actionOpen -> {
                    showActionDialog(idList, 1)
                }
            }
        }



        preTxtBtn.setOnClickListener { pre() }
        nextTxtBtn.setOnClickListener { next() }
        btnRefresh.setOnClickListener {
            isRefresh = true
            showLayoutLoading()
            initData()
        }

        btnOpen.setOnClickListener {
            val newList = mAdapter.data.filter { it.isChecked }
            if(newList.isEmpty()){
                showDialogToast("请先选择设备", icon = ICON_TYPE_FAIL)
                return@setOnClickListener
            }

            val idList = newList.map { it.id }
            showActionDialog(idList.toMutableList(),1)
        }
        btnNormal.setOnClickListener {
            val newList = mAdapter.data.filter { it.isChecked }
            if(newList.isEmpty()){
                showDialogToast("请先选择设备", icon = ICON_TYPE_FAIL)
                return@setOnClickListener
            }

            val idList = newList.map { it.id }
            showActionDialog(idList.toMutableList(),0)
        }
        checkAll.setOnCheckedChangeListener { _, isChecked ->
            if(isChecked){
                mAdapter.data.forEach { it.isChecked = true }
                mAdapter.notifyDataSetChanged()
            }else{
                mAdapter.data.forEach { it.isChecked = false }
                mAdapter.notifyDataSetChanged()
            }
        }

        userNameBox.setOnClickListener {
            logoutDialog()
        }

        checkVersion.setOnClickListener {
            EventBus.getDefault().post(UserVersionCheck())
        }

    }

    private  fun logoutDialog(){
        val tipDialog = QMUIDialog.MessageDialogBuilder(activity)
            .setTitle("温馨提示")
            .setMessage("是否确定退出登录？")
            .addAction("取消") { dialog, index ->
                dialog.dismiss()
            }
            .addAction("确定") { dialog, index ->
                dialog.dismiss()
                activity?.apply {
                    User.clearUserInfo()
                    LoginActivity.active(this)
                    finish()
                }
            }
            .create()
        tipDialog.show()
    }

    private fun showActionDialog(idList: MutableList<Int>, mode: Int) {
        val tipDialog = QMUIDialog.MessageDialogBuilder(activity)
            .setTitle("温馨提示")
            .setMessage(
                if (mode == 1) {
                    "是否确定将设备设置为常开？"
                } else {
                    "是否确定将设备设置为标准状态？"
                }
            )
            .addAction("取消") { dialog, index ->
                dialog.dismiss()
            }
            .addAction("确定") { dialog, index ->
                dialog.dismiss()
                showLoading("操作中...")
                mPresenter?.setDoorRelayMode(idList,mode)
            }
            .create()
        tipDialog.show()
    }

    private fun showLayoutLoading() {
        loadingLayout.visibility = View.VISIBLE
    }

    private fun hideLayoutLoading() {
        loadingLayout.visibility = View.GONE
    }

    private fun refreshData() {
        if (isLoading) {
            return
        }
        isLoading = true
        mPresenter?.getDeviceList(mPager.page_no)
    }

    private fun pre() {
        if (isLoading) {
            return
        }
        if (mPager.page_no <= 1) {
        } else {
            isLoading = true
            showLayoutLoading()
            mPresenter?.getDeviceList(mPager.page_no - 1)
        }
    }

    private fun next() {
        if (isLoading) {
            return
        }
        if (mPager.page_no >= mPager.total_pages) {
        } else {
            isLoading = true
            showLayoutLoading()
            mPresenter?.getDeviceList(mPager.page_no + 1)
        }
    }

    private fun showExitDialog() {
        val builder = QMUIDialog.EditTextDialogBuilder(activity)

        builder.setPlaceholder("输入密码")
            .setTitle("请输入密码")
            .setInputType(InputType.TYPE_NUMBER_VARIATION_PASSWORD or InputType.TYPE_CLASS_NUMBER)
            .addAction(
                "取消"
            ) { dialog, index ->
                KeyboardUtils.hideSoftInput(builder.editText)
                dialog?.dismiss()
            }
            .addAction(
                "确定"
            ) { dialog, index ->
                val text = builder.editText.text
                LogUtils.d(text)
                LogUtils.d("112233".equals(text))
                if ("112233" == text.toString()) {
                    activity?.finish()
                    exitProcess(0)
                } else {
//                    ToastUtils.showShort("密码不正确")
                    showPwdErrorTip()
                }
            }
            .setCancelable(false)
            .setCanceledOnTouchOutside(false)
        val dialog = builder.show()

        dialog.hideNavigationBar()
    }

    private fun showPwdErrorTip() {
        val tipDialog = QMUITipDialog.Builder(activity)
            .setIconType(QMUITipDialog.Builder.ICON_TYPE_FAIL)
            .setTipWord("密码错误")
            .create()
        tipDialog.show()
        tipDialog.hideNavigationBar()
        sysExitBtn.postDelayed({
            tipDialog.dismiss()
        }, 1500)
    }

    override fun initData() {
        mPresenter?.getDeviceList(1)

        mPager.page_no = 1
        if (NetworkUtils.isConnected()) {
            showEmpty(1)
            isLoading = true
            mPresenter?.getDeviceList(mPager.page_no)
        } else {
            showEmpty(2)
        }


    }

    override fun onResume() {
        super.onResume()
        mPresenter?.getTeacherInfo(User.getUser().user_id)
    }

    override fun initPresenter(): SettingPresenter = SettingPresenter(this)
    override fun onSetSuccess() {
        hideLoading()
        showDialogToast("设置成功！")
    }

    override fun onSetError(error: String) {
        hideLoading()
        showDialogToast(error,icon = QMUITipDialog.Builder.ICON_TYPE_FAIL)
    }


    override fun onStop() {
        super.onStop()
        EventBus.getDefault().unregister(this)
    }


    override fun onStart() {
        super.onStart()
        EventBus.getDefault().register(this)
    }

    //接收消息
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: TimeShow) {
//        timeView.setTime(event)
    }

    override fun onDeviceListSuccess(list: MutableList<Device>, pager: Pager) {
        pageTv?.apply {
            if (isRefresh) {
                toast("刷新成功！")
                isRefresh = false
            }
            mAdapter.setList(list)
            mPager = pager
            pageTv.text = "${pager.page_no} / ${pager.total_pages}"
            totalTv.text = "共${pager.total_count}条"

            val disabledColor = Color.parseColor("#666666")
            val color = Color.parseColor("#3ca0e9")
            if (pager.page_no <= 1) {
                preTxtBtn.textColor = disabledColor
                goPageOne.visibility = View.GONE
            } else {
                preTxtBtn.textColor = resources.getColor(R.color.s_app_color_blue)
                goPageOne.visibility = View.VISIBLE
            }

            if (pager.page_no >= pager.total_pages) {
                nextTxtBtn.textColor = disabledColor
            } else {
                nextTxtBtn.textColor = resources.getColor(R.color.s_app_color_blue)
            }

            isLoading = false
            showEmpty(3)
            hideLayoutLoading()
        }
    }

    override fun onDeviceListError(error: String) {

    }

    /**
     * type 1 loading 2 neterror 3 empty
     */
    private fun showEmpty(type: Int) {
        when (type) {
            1 -> {
                mAdapter.setEmptyView(R.layout.layout_loading)
                mAdapter.emptyLayout?.apply {
                    this.QMUIEmptyView.setLoadingShowing(true)
                    this.QMUIEmptyView.setTitleText("数据加载中")
                }
            }

            2 -> {
                mAdapter.setEmptyView(R.layout.layout_loading)
                mAdapter.emptyLayout?.apply {
                    this.QMUIEmptyView.show(false, null, "网络连接异常，请检查", "去设置") {
                        NetworkUtils.openWirelessSettings()
                    }
                }
            }

            3 -> {
                mAdapter.setEmptyView(R.layout.layout_empty)
            }
        }

    }

    override fun onUserInfoError(error: String) {

    }

    override fun onUserInfoSuccess(info: TeacherInfo) {
        userNameTv.text = info.teacher_name
    }
}