package com.yzx.escreen.fragment

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.graphics.Color
import android.text.Editable
import android.text.TextWatcher
import android.view.KeyEvent
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.*
import com.qmuiteam.qmui.widget.roundwidget.QMUIRoundButton
import com.yzx.escreen.R
import com.yzx.escreen.adapter.ChangeListAdapter
import com.yzx.escreen.fragment.base.BaseFragment
import com.yzx.escreen.model.*
import com.yzx.escreen.presenter.ChangePresenter
import com.yzx.escreen.presenter.ChangeView
import com.yzx.escreen.utils.FileUploadCallBack
import com.yzx.escreen.widget.BaseDialog
import kotlinx.android.synthetic.main.fragment_change.*
import kotlinx.android.synthetic.main.layout_loading.view.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.jetbrains.anko.support.v4.ctx
import org.jetbrains.anko.support.v4.toast
import org.jetbrains.anko.textColor


class ChangeFragment : BaseFragment<ChangePresenter>(), ChangeView,
    NetworkUtils.OnNetworkStatusChangedListener, FileUploadCallBack {

    companion object {

        val CAMER_REQUEST_CODE = 0x01

        @JvmStatic
        fun getNewInstance() =
            ChangeFragment()
    }

    private val mAdapter: ChangeListAdapter by lazy {
        val list = mutableListOf<StuChange>()
        ChangeListAdapter(list)
    }

    private var mPager = Pager()
    var list = mutableListOf<StuChange>()
    private val statusBtnList = mutableListOf<QMUIRoundButton>()
    var keyword: String = ""
    var status: String = ""
    private var isLoading = false
    private val mShowList = mutableListOf<StuChange>()
    private val mShowDialogList = mutableListOf<BaseDialog>()
    private var isRefresh = false

    private val refreshRun = Runnable {
        refreshData()
    }

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

    override fun initView() {
        NetworkUtils.registerNetworkStatusChangedListener(this)
        recyclerView.layoutManager =
            LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
        recyclerView.adapter = mAdapter

        preTxtBtn.setOnClickListener { pre() }
        nextTxtBtn.setOnClickListener { next() }
        allBtn.setOnClickListener { changeStatus(0) }
        status1Btn.setOnClickListener { changeStatus(1) }
        status2Btn.setOnClickListener { changeStatus(2) }
        status3Btn.setOnClickListener { changeStatus(3) }
        statusBtnList.add(allBtn)
        statusBtnList.add(status1Btn)
        statusBtnList.add(status2Btn)
        statusBtnList.add(status3Btn)
        keywordInput.setOnKeyListener { _, keyCode, _ ->
            if (!isLoading) {
                if (keyCode == KeyEvent.KEYCODE_ENTER) {
                    keyword = keywordInput.text.toString()
                    initData()
                    KeyboardUtils.hideSoftInput(keywordInput)
                }
            }
            false
        }
        clearBtn.setOnClickListener {
            keyword = ""
            keywordInput.setText("")
            KeyboardUtils.hideSoftInput(keywordInput)
            initData()
        }
        var lastClickTime = TimeUtils.getNowMills()
        mAdapter.setOnItemClickListener { adapter, view, position ->
            val curr = TimeUtils.getNowMills()
            if(curr - lastClickTime > 500){
                lastClickTime = curr
                mPresenter?.getDetail(mAdapter.getItem(position).id)
            }
        }

        mAdapter.setOnItemChildClickListener { adapter, view, position ->
            LogUtils.d("setOnItemChildClickListener", position)
            val curr = TimeUtils.getNowMills()
            if(curr - lastClickTime > 500){
                lastClickTime = curr
                when (view.id) {
                    R.id.cancelBtn -> {

                    }
                    R.id.faceEmpty -> {
                        mPresenter?.getDetail(mAdapter.getItem(position).id)
                    }
                }
            }

        }


        switchBtn.setOnCheckedChangeListener { buttonView, isChecked ->
            SPUtils.getInstance().put("auto_show_change", isChecked)
            changeSwitchBtnTxt(isChecked)
            EventBus.getDefault().post(AutoSwitchChange(2))
        }
        val isAutoShowLeave = SPUtils.getInstance().getBoolean("auto_show_change", true)
        switchBtn.isChecked = isAutoShowLeave
        changeSwitchBtnTxt(isAutoShowLeave)

        switchBtnTxt.setOnClickListener {
            switchBtn.isChecked = !switchBtn.isChecked
        }
        keywordInput.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                if (s != null && s.isNotEmpty()) {
                    clearBtn.visibility = View.VISIBLE
                } else {
                    clearBtn.visibility = View.INVISIBLE
                }
            }

            override fun afterTextChanged(s: Editable?) {

            }

        })
        filterLayout.setOnClickListener {
            KeyboardUtils.hideSoftInput(keywordInput)
        }
        btnRefresh.setOnClickListener {
            isRefresh = true
            showLayoutLoading()
            initData()
        }
        changeStatusBtn(0)
        loadingLayout.setOnClickListener {
            //do nothing
        }
        goPageOne.setOnClickListener {
            showLayoutLoading()
            initData()
        }
    }

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

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


    private fun changeSwitchBtnTxt(isChecked: Boolean) {
        if (isChecked) {
            switchBtnTxt.setTextColor(ctx.resources.getColor(R.color.green2))
        } else {
            switchBtnTxt.setTextColor(ctx.resources.getColor(R.color.black_3))
        }
    }

    @SuppressLint("SetTextI18n")
    private fun showLeaveDialog(detail: StuChange) {
        EventBus.getDefault().post(detail)
    }

    private fun changeStatusBtn(idx: Int) {
        statusBtnList.forEachIndexed { index, button ->
            button.isSelected = index == idx
        }
    }

    private fun changeStatus(status: Int) {
        KeyboardUtils.hideSoftInput(keywordInput)
        if (isLoading) {
            return
        }
        changeStatusBtn(status)
        this.status = if (status == 0) {
            ""
        } else {
            "${status}"
        }
        showLayoutLoading()
        initData()
    }

    override fun initData() {

        mPager.page_no = 1
        if (NetworkUtils.isConnected()) {
            showEmpty(1)
            isLoading = true
            mPresenter?.getList(mPager.page_no, keyword, status)
        } else {
            showEmpty(2)
        }

    }

    /**
     * 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)
            }
        }

    }

    private fun refreshData() {
        if (isLoading) {
            return
        }
        isLoading = true
        mPresenter?.getList(mPager.page_no, keyword, status)
    }

    private fun pre() {
        KeyboardUtils.hideSoftInput(keywordInput)
        if (isLoading) {
            return
        }
        if (mPager.page_no <= 1) {
        } else {
            isLoading = true
            showLayoutLoading()
            mPresenter?.getList(mPager.page_no - 1, keyword, status)
        }
    }

    private fun next() {
        KeyboardUtils.hideSoftInput(keywordInput)
        if (isLoading) {
            return
        }
        if (mPager.page_no >= mPager.total_pages) {
        } else {
            isLoading = true
            showLayoutLoading()
            mPresenter?.getList(mPager.page_no + 1, keyword, status)
        }
    }

    override fun initPresenter(): ChangePresenter = ChangePresenter(this)

    @SuppressLint("SetTextI18n")
    override fun onListSuccess(list: MutableList<StuChange>, 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()
            pageTv.postDelayed({
                refreshData()
            }, 30 * 1000)
        }
    }

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


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

    override fun onListError(error: String) {
        isLoading = false
        if(isRefresh){
            toast("刷新失败，请重试！")
            isRefresh = false
        }
        hideLayoutLoading()
        showEmpty(3)
    }

    override fun onDetailSuccess(detail: StuChange) {
        pageTv?.apply {
            val item = mShowList.find { it.id == detail.id }
            if (item != null) {
                //替换新的数据
                val index = mShowList.indexOf(item)
                mShowList[index] = detail

                //移除原本的dialog
                val dialogIndex = mShowDialogList.indexOfFirst { it.getLeaveId() == item.id }
                if (dialogIndex > -1) {
                    mShowDialogList[dialogIndex].hide()
                    mShowDialogList.removeAt(dialogIndex)
                }

            } else {
                mShowList.add(detail)
            }
            showLeaveDialog(detail)
        }
    }

    override fun onDetailError(error: String) {

    }

    override fun onDisconnected() {

    }

    override fun onConnected(networkType: NetworkUtils.NetworkType?) {
        refreshData()
    }

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


        }
        super.onActivityResult(requestCode, resultCode, data)
    }

    override fun onSuccess(identity: String, key: String) {
        LogUtils.d(identity, key)

    }

    override fun onError(msg: String) {
        LogUtils.d(msg)


    }

    //接收消息
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: MessageEventAuto) {
        val list = event.list.filter { it.type == 1 }.toMutableList()
        if (list.isNotEmpty() && switchBtn.isChecked) {
            list.forEachIndexed { index, leaveID ->
                pageTv.postDelayed({
                    mPresenter?.getDetail(leaveID.id)
                }, 500L * index)
            }
        }
    }

    //接收消息
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageRefreshEvent(event: RefreshTokenEvent) {
        refreshData()
    }

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

