package com.yzx.escreen.fragment

import android.Manifest
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 android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.*
import com.huantansheng.easyphotos.EasyPhotos
import com.huantansheng.easyphotos.models.album.entity.Photo
import com.qmuiteam.qmui.widget.dialog.QMUIDialog
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog
import com.qmuiteam.qmui.widget.roundwidget.QMUIRoundButton
import com.yzx.escreen.R
import com.yzx.escreen.adapter.HomeGridAdapter
import com.yzx.escreen.adapter.HomeListAdapter
import com.yzx.escreen.fragment.base.BaseFragment
import com.yzx.escreen.model.*
import com.yzx.escreen.presenter.HomePresenter
import com.yzx.escreen.presenter.HomeView
import com.yzx.escreen.utils.*
import com.yzx.escreen.widget.BaseDialog
import kotlinx.android.synthetic.main.fragment_home.*
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.find
import org.jetbrains.anko.support.v4.act
import org.jetbrains.anko.support.v4.ctx
import org.jetbrains.anko.support.v4.toast
import org.jetbrains.anko.textColor


class HomeFragment : BaseFragment<HomePresenter>(), HomeView,
    NetworkUtils.OnNetworkStatusChangedListener, FileUploadCallBack {

    companion object {

        val CAMER_REQUEST_CODE = 0x01

        @JvmStatic
        fun getNewInstance() =
            HomeFragment()
    }

    private val mAdapter: HomeListAdapter by lazy {
        val list = mutableListOf<StuLeave>()
        HomeListAdapter(list)
    }

    private val mGridAdapter: HomeGridAdapter by lazy {
        val list = mutableListOf<StuLeave>()
        HomeGridAdapter(list)
    }

    private var mPager = Pager()
    var list = mutableListOf<StuLeave>()
    private val statusBtnList = mutableListOf<QMUIRoundButton>()
    var keyword: String = ""
    var status: String = ""
    var add_time: String = "today"
    private var isLoading = false
    private val mShowList = mutableListOf<StuLeave>()
    private val mShowDialogList = mutableListOf<BaseDialog>()
    private var mCancelItem: StuLeave? = null
    private var mCancelFaceImg: ImageView? = null
    private var mDialogVacation: BaseDialog? = null
    private val mVacation = Vacation()
    private val mVacationAttachment = Attachment("", "", "")
    private var isRefresh = false
    private var listType = 2 //1 列表模式  2 grid模式
    private var is_hide = 0  //1 离校     0  未离校

    private val refreshRun = Runnable {
        refreshData()
    }

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

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

        recyclerView2.layoutManager =
            GridLayoutManager(context, 5, GridLayoutManager.VERTICAL, false)
        recyclerView2.adapter = mGridAdapter

        preTxtBtn.setOnClickListener { pre() }
        nextTxtBtn.setOnClickListener { next() }
        preTxtBtn2.setOnClickListener { pre() }
        nextTxtBtn2.setOnClickListener { next() }
        allBtn.setOnClickListener { changeStatus(0) }
        yesterday.setOnClickListener { changeStatus(2) }
        last7Days.setOnClickListener { changeStatus(3) }
        today.setOnClickListener { changeStatus(1) }
        statusBtnList.add(allBtn)
        statusBtnList.add(today)
        statusBtnList.add(yesterday)
        statusBtnList.add(last7Days)
        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
                LogUtils.d("获取详情开始", TimeUtils.getNowMills(), mAdapter.getItem(position).id)
                showLayoutLoading()
                mPresenter?.getDetail(mAdapter.getItem(position).id)
            }
        }

        mGridAdapter.setOnItemClickListener { adapter, view, position ->
            val curr = TimeUtils.getNowMills()
            if (curr - lastClickTime > 500) {
                lastClickTime = curr
                LogUtils.d("获取详情开始", TimeUtils.getNowMills(), mAdapter.getItem(position).id)
                showLayoutLoading()
                mPresenter?.getDetail(mGridAdapter.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 -> {
                        mCancelItem = mAdapter.getItem(position)
                        showCancelDialog()
                    }

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

        mGridAdapter.setOnItemChildClickListener { adapter, view, position ->
            LogUtils.d("setOnItemChildClickListener", position)
            val curr = TimeUtils.getNowMills()
            if (curr - lastClickTime > 500) {
                lastClickTime = curr
                when (view.id) {
                    R.id.sureBtn,
                    R.id.faceEmpty -> {
                        showLayoutLoading()
                        mPresenter?.getDetail(mGridAdapter.getItem(position).id)
                    }
                }
            }
        }


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

        switchBtnTxt.setOnClickListener {
            switchBtn.isChecked = !switchBtn.isChecked

            EventBus.getDefault().post(AutoSwitchChange(1))
        }

        hideType0.setOnClickListener {

            is_hide = if(is_hide==0){
                -1
            }else{
                0
            }
            changeSwitch2BtnTxt()
            initData()
        }
        hideType1.setOnClickListener {
            is_hide = if(is_hide==1){
                -1
            }else{
                1
            }
            changeSwitch2BtnTxt()
            initData()
        }
        changeSwitch2BtnTxt()

        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(1)
        loadingLayout.setOnClickListener {
            //do nothing
        }
        goPageOne.setOnClickListener {
            showLayoutLoading()
            initData()
        }
        goPageOne2.setOnClickListener {
            showLayoutLoading()
            initData()
        }
        filterBtn.setOnClickListener {
            showFilterDialog(this.status)
        }

        listType1Btn.setOnClickListener {
            listType1Btn.visibility = View.GONE
            listType2Btn.visibility = View.VISIBLE
            listType = 1
            initData()
        }
        listType2Btn.setOnClickListener {
            listType2Btn.visibility = View.GONE
            listType1Btn.visibility = View.VISIBLE
            listType = 2
            initData()
        }
    }

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

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

    @SuppressLint("SetTextI18n")
    private fun showFilterDialog(status: String) {
        var idx = if (status == "") {
            0
        } else {
            status.toInt()
        }
        val dialogVacation = BaseDialog(act, R.style.BaseDialog, R.layout.dialog_time_filter)
        val btns = mutableListOf<TextView>()
        btns.add(dialogVacation.find(R.id.allBtn))
        btns.add(dialogVacation.find(R.id.status1Btn))
        btns.add(dialogVacation.find(R.id.status2Btn))
        btns.add(dialogVacation.find(R.id.status3Btn))
        btns.add(dialogVacation.find(R.id.status4Btn))
        btns.add(dialogVacation.find(R.id.status5Btn))
        btns.forEachIndexed { index, button ->
            button.setOnClickListener {
                btns.forEachIndexed { childIdx, btn ->
                    btn.isSelected = childIdx == index
                }
                idx = index
            }
            button.isSelected = index == idx
        }
        dialogVacation.find<TextView>(R.id.submitBtn).setOnClickListener {
            this.status = if (idx == 0) {
                ""
            } else {
                "${idx}"
            }
            dialogVacation.hide()
            showLayoutLoading()
            initData()
        }
        dialogVacation.find<TextView>(R.id.closeBtn).setOnClickListener {
            dialogVacation.hide()
        }
        //处理弹窗显示
        dialogVacation.show()
        dialogVacation.hideNavigationBar()
    }

    @SuppressLint("SetTextI18n")
    private fun showCancelDialog() {
        val dialogVacation = BaseDialog(act, R.style.BaseDialog, R.layout.dialog_vacation)
        mCancelItem?.apply {
            mVacation.id = id
            mVacation.vacation_type = 2
            mVacation.vacation_attachment = ""
            mVacation.vacation_remark = "电子屏人工销假"
            mVacationAttachment.clear()
            dialogVacation.find<TextView>(R.id.leave_student_name).text = leave_student_name
            dialogVacation.find<TextView>(R.id.class_name).text = "${grade_name}${class_name}"
            dialogVacation.find<TextView>(R.id.add_time).text =
                "${start_time.toTime()} - ${end_time.toTime()}"
            val nowTime = (TimeUtils.getNowMills() / 1000).toInt()
            dialogVacation.find<TextView>(R.id.vacation_time).text = nowTime.toTime()
            mVacation.vacation_time = nowTime.toLong()
            dialogVacation.find<EditText>(R.id.vacation_remark).setText(mVacation.vacation_remark)
            dialogVacation.find<View>(R.id.cameraBtn).setOnClickListener { onCameraBtnClick() }
            mCancelFaceImg = dialogVacation.find<ImageView>(R.id.face_img)
            dialogVacation.find<View>(R.id.submitBtn).setOnClickListener {
                postVacation()
            }
            dialogVacation.find<View>(R.id.closeBtn).setOnClickListener {
                dialogVacation.dismiss()
            }
        }
        //处理弹窗显示
        dialogVacation.show()
        dialogVacation.hideNavigationBar()
        mDialogVacation = dialogVacation
    }

    private fun postVacation() {
        if (mVacationAttachment.id.isNotEmpty()) {
            mVacation.vacation_attachment = GsonUtils.toJson(mutableListOf(mVacationAttachment))
        }
        showLoading("销假中")
        mPresenter?.postVacation(mVacation)
    }

    private fun onCameraBtnClick() {
        val isGranted = PermissionUtils.isGranted(Manifest.permission.CAMERA)
        if (!isGranted) {
            PermissionUtils.permission(Manifest.permission.CAMERA)
                .callback { isAllGranted, granted, deniedForever, denied ->
                    if (!isAllGranted) {
                        val tipDialog = QMUIDialog.MessageDialogBuilder(activity)
                            .setTitle("温馨提示")
                            .setMessage("拍照权限被拒绝，请开启权限后重试")
                            .addAction("取消") { dialog, index ->
                                dialog.dismiss()
                            }
                            .addAction("确定") { dialog, index ->
                                dialog.dismiss()
                                PermissionUtils.launchAppDetailsSettings()
                            }
                            .create()
                        tipDialog.show()
                        tipDialog.hideNavigationBar()
                    }
                }
                .request()
        } else {
            openCamera()
        }
    }

    private fun openCamera() {
        EasyPhotos.createCamera(this, true)
            .setFileProviderAuthority("${activity?.packageName}.fileProvider")
            .start(CAMER_REQUEST_CODE)//也可以选择链式调用写法
    }


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

    private fun changeSwitch2BtnTxt() {
        if (is_hide == 0) {
            hideType0.isSelected = true
            hideType1.isSelected = false
        } else if (is_hide == 1) {
            hideType0.isSelected = false
            hideType1.isSelected = true
        } else {
            hideType0.isSelected = false
            hideType1.isSelected = false
        }
    }

    @SuppressLint("SetTextI18n")
    private fun showLeaveDialog(detail: StuLeave) {
        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.add_time = when (status) {
            0 -> {
                ""
            }

            1 -> {
                "today"
            }

            2 -> {
                "yesterday"
            }

            3 -> {
                "last7Days"
            }

            else -> {
                ""
            }
        }
        showLayoutLoading()
        initData()
    }

    override fun initData() {

        mPager.page_no = 1
        if (NetworkUtils.isConnected()) {
            showEmpty(1)
            isLoading = true
            mPresenter?.getLeaveList(mPager.page_no, keyword, status, add_time, listType, is_hide)
        } 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("数据加载中")
                }

                mGridAdapter.setEmptyView(R.layout.layout_loading)
                mGridAdapter.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()
                    }
                }

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

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

    }

    private fun refreshData() {
        if (isLoading) {
            return
        }
        isLoading = true
        if (NetworkUtils.isConnected()) {
            mPresenter?.getLeaveList(mPager.page_no, keyword, status, add_time, listType, is_hide)
        }
    }

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

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

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

    @SuppressLint("SetTextI18n")
    override fun onLeaveListSuccess(list: MutableList<StuLeave>, pager: Pager) {
        pageTv?.apply {
            if (isRefresh) {
                toast("刷新成功！")
                isRefresh = false
            }
            mAdapter.setList(list)
            mGridAdapter.setList(list)

            mPager = pager
            pageTv.text = "${pager.page_no} / ${pager.total_pages}"
            totalTv.text = "共${pager.total_count}条"

            pageTv2.text = "${pager.page_no} / ${pager.total_pages}"
            totalTv2.text = "共${pager.total_count}条"

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

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

            isLoading = false
            showEmpty(3)
            hideLayoutLoading()
            if (listType == 1) {
                listTypeLayout2.visibility = View.GONE
                listTypeLayout1.visibility = View.VISIBLE
            } else {
                listTypeLayout1.visibility = View.GONE
                listTypeLayout2.visibility = View.VISIBLE
            }
            pageTv.postDelayed({
                refreshData()
            }, 30 * 1000)
        }
    }

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

    //接收异动消息
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(detail: SureOutSchool) {
        showLoading("处理中...")
        mPresenter?.outSchool(detail.item)
    }

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

    override fun onLeaveDetailSuccess(detail: StuLeave) {
        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)
            }
            LogUtils.d("获取详情结束", TimeUtils.getNowMills(), detail.id)
            hideLayoutLoading()
            showLeaveDialog(detail)
        }
    }

    override fun onLeaveDetailError(error: String) {
        hideLayoutLoading()
    }

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

    //接收消息
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: MessageEventAuto) {
        val list = event.list.filter { it.type == 0 }.toMutableList()
        LogUtils.d("WebSocketClient-onMessageEvent", event)
        if (list.isNotEmpty() && switchBtn.isChecked) {
            onLeaveIDsSuccess(list)
        }
    }

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

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

    override fun onLeaveIDsSuccess(list: MutableList<LeaveID>) {

        list.forEachIndexed { index, leaveID ->
            pageTv.postDelayed({
                if (leaveID.id > 0) {
                    mPresenter?.getDetail(leaveID.id)
                }
            }, 500L * index)
        }
    }

    override fun postVacationSuccess(msg: String) {
        showDialogToast(msg, 2000L)
        hideLoading()
        mDialogVacation?.apply {
            dismiss()
            refreshData()
        }
    }

    override fun postVacationError(msg: String) {
        hideLoading()
        showDialogToast(msg, 2000L, QMUITipDialog.Builder.ICON_TYPE_FAIL)
    }

    override fun onDisconnected() {

    }

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

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == CAMER_REQUEST_CODE) {
                val photos = data?.getParcelableArrayListExtra<Photo>(EasyPhotos.RESULT_PHOTOS)
                LogUtils.d("photos", photos)
                photos?.apply {
                    if (this.size > 0) {
                        mVacationAttachment.name = this[0].name
                        FileUpload.upload(this[0].path, this@HomeFragment)
                    }
                }

            }

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

    override fun onSuccess(identity: String, key: String) {
        LogUtils.d(identity, key)
        mCancelFaceImg?.setSrc(identity, key)
        mVacationAttachment.identity = identity
        mVacationAttachment.id = key
    }

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

    override fun postHideSuccess(msg: String) {
        showDialogToast(msg, 2000L)
        hideLoading()
        initData()
    }

    override fun postHideError(msg: String) {
        showDialogToast(msg, 2000L)
        hideLoading()
    }
}

