package com.yzx.ebrand.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.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.ebrand.R
import com.yzx.ebrand.adapter.HomeListAdapter
import com.yzx.ebrand.fragment.base.BaseFragment
import com.yzx.ebrand.model.*
import com.yzx.ebrand.presenter.HomePresenter
import com.yzx.ebrand.presenter.HomeView
import com.yzx.ebrand.utils.*
import com.yzx.ebrand.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 var mPager = Pager()
    var list = mutableListOf<StuLeave>()
    private val statusBtnList = mutableListOf<QMUIRoundButton>()
    var keyword: String = ""
    var status: String = ""
    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 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

        preTxtBtn.setOnClickListener { pre() }
        nextTxtBtn.setOnClickListener { next() }
        allBtn.setOnClickListener { changeStatus(0) }
        status1Btn.setOnClickListener { changeStatus(1) }
        status2Btn.setOnClickListener { changeStatus(2) }
        status3Btn.setOnClickListener { changeStatus(3) }
        status4Btn.setOnClickListener { changeStatus(4) }
        status5Btn.setOnClickListener { changeStatus(5) }
        statusBtnList.add(allBtn)
        statusBtnList.add(status1Btn)
        statusBtnList.add(status2Btn)
        statusBtnList.add(status3Btn)
        statusBtnList.add(status4Btn)
        statusBtnList.add(status5Btn)
        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)
            }
        }

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


        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", false)
        switchBtn.isChecked = isAutoShowLeave
        changeSwitchBtnTxt(isAutoShowLeave)

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

            EventBus.getDefault().post(AutoSwitchChange(1))
        }
        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
    }

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

    @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.status = if (status == 0) {
            ""
        } else {
            "${status}"
        }
        showLayoutLoading()
        initData()
    }

    override fun initData() {

        mPager.page_no = 1
        if (NetworkUtils.isConnected()) {
            showEmpty(1)
            isLoading = true
            mPresenter?.getLeaveList(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?.getLeaveList(mPager.page_no, keyword, status)
    }

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

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

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

