package xn.hxp.ui.uses


import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.LayoutInflater
import android.view.View
import android.widget.AdapterView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.viewbinding.ViewBinding
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.request.RequestOptions
import com.codbking.widget.DatePickDialog
import com.codbking.widget.bean.DateType
import xn.hxp.app.ChemicalApp
import xn.hxp.R
import xn.hxp.databinding.ActivityWarningEventsBinding
import xn.hxp.ui.adapter.WarningEventsAdapter
import xn.hxp.utils.TimeUpdater
import xn.hxp.utils.UiManager
import com.blankj.utilcode.util.LogUtils
import com.rc.core.ui.activity.BaseActivity
import com.rc.httpcore.HttpClient
import com.rc.httpcore.HttpConfig
import com.rc.httpcore.client.ApiRepository
import com.rc.httpcore.client.HttpTool
import java.util.*

//预警事件
class WarningEventsActivity : BaseActivity() {
    private lateinit var timeUpdater: TimeUpdater
    private val mAdapter by lazy { WarningEventsAdapter(this) }
    private var mNoticeStatus: String? = null   //1是已处理，0和2是未处理
    private var mWarnTime: String? = null       //具体时间
    private var mTimeType: String? = null       //1是近一个月，2是近三个月
    private var mPages = 1  //总页码
    private var mDataPage = -1  //返回得总条数
    private var page = 1
    private var pageSize = 10

    lateinit var viewBinding: ActivityWarningEventsBinding
    override fun setViewBinding(): ViewBinding {
        viewBinding = ActivityWarningEventsBinding.inflate(layoutInflater)
        return viewBinding
    }

    override fun onInit() {
        warningNoticeCount()
        viewBinding.tvReturn.text = "返回${ChemicalApp.confs!!.backTime}s"
        viewBinding.rvView?.layoutManager = LinearLayoutManager(this)
        viewBinding.rvView?.adapter = mAdapter
        viewBinding.tvReturn.setOnClickListener {
            finish()
        }
        viewBinding.tvOutLogin.setOnClickListener {
            HttpTool.logout()
        }
        mAdapter.setOnItemChildClickListener { adapter, view, position ->
            if (view.id == R.id.operate) {
                val map = mutableMapOf<String, Any>()
                map["noticeId"] = mAdapter.data[position].noticeId
                if (mAdapter.data[position].solve) {
                    //需要处理
                    UiManager.switcher(this, map, ProcessedActivity::class.java)
                } else {
                    //详情只查看 不需要处理
                    UiManager.switcher(this, map, ProcessedActivity::class.java)
                }
            }
        }



        viewBinding.tvReturn.setOnClickListener {
            finish()
        }

        viewBinding.re1.setOnClickListener {
            viewBinding.whole.isChecked = true
            page = 1
            mTimeType = null
            getTimeView()  //选择时间
        }

        viewBinding.whole.setOnClickListener {
            page = 1
            viewBinding.oneMonth.isChecked = false
            viewBinding.threeMonths.isChecked = false
            mTimeType = null
            getLists()
        }

        viewBinding.oneMonth.setOnClickListener {
            page = 1
            viewBinding.whole.isChecked = false
            viewBinding.threeMonths.isChecked = false
            mTimeType = "1"
            getLists()
        }

        viewBinding.threeMonths.setOnClickListener {
            page = 1
            viewBinding.whole.isChecked = false
            viewBinding.oneMonth.isChecked = false
            mTimeType = "2"
            getLists()
        }

        viewBinding.spLev.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(
                parent: AdapterView<*>?,
                view: View?,
                position: Int,
                id: Long
            ) {
                page = 1
                //1是已处理，0和2是未处理
                when (position) {
                    0 -> {//全部
                        LogUtils.i("===测hi是===$position")
                        mNoticeStatus = null
                        getLists()
                    }

                    1 -> {//待处理
                        LogUtils.i("===测hi是===$position")
                        mNoticeStatus = "0"
                        getLists()
                    }

                    2 -> {//已处理
                        LogUtils.i("===测hi是===$position")
                        mNoticeStatus = "1"
                        getLists()
                    }
                }
            }

            override fun onNothingSelected(parent: AdapterView<*>?) {
                // 当没有选项被选择时调用
            }
        }


        val handler = Handler(Looper.getMainLooper())
        timeUpdater = TimeUpdater(handler) { currentTime ->
            viewBinding.nowTime.text = "$currentTime"
        }
        //启动定时更新
        timeUpdater.startUpdating()

        viewBinding.tvName.text = ChemicalApp.userData!!.userName
        val imageView = viewBinding.imageName
        // 使用 Glide 加载网络图片
        Glide.with(this)
            .load("${HttpConfig.API_BASE_IMG_URL}${ChemicalApp.userData!!.avatar}")
            .apply(RequestOptions.diskCacheStrategyOf(DiskCacheStrategy.AUTOMATIC))
            .into(imageView)

        // 使用 Glide 加载网络图片
        viewBinding.deptName.text = "${ChemicalApp.confs!!.deptName}-${ChemicalApp.confs!!.roomNum}"
        Glide.with(this)
            .load("${HttpConfig.API_BASE_IMG_URL}${ChemicalApp.confs!!.circularLogo}")
            .apply(RequestOptions.diskCacheStrategyOf(DiskCacheStrategy.AUTOMATIC))
            .into(viewBinding.image)

        getLists()

        viewBinding.butUpper.setOnClickListener {
            //上一页
            if (mDataPage != 0) {
                if (page != 1) {
                    page--
                    getLists()
                }
            }
        }

        viewBinding.butNext.setOnClickListener {
            //下一页
            if (mDataPage != 0) {
                if (mDataPage != page) {
                    page++
                    getLists()
                }
            }
        }
    }


    override fun onDestroy() {
        super.onDestroy()
        try {
            timeUpdater.stopUpdating()
        } catch (e: Exception) {
        }
    }

    override fun cdFinish() {
        finish()
    }

    override fun cdTime(cd: Int) {
        viewBinding.tvReturn.text = "返回${cd}s"
    }

    private fun getLists() {
        val mutableMap = mutableMapOf<String, String>()
        mutableMap["subId"] = "${ChemicalApp.subjectId}"
        if (mNoticeStatus != null) {
            mutableMap["noticeStatus"] = "$mNoticeStatus"
        }
        if (mTimeType != null) {
            mutableMap["timeType"] = "$mTimeType"
        }
        if (mWarnTime != null) {
            mutableMap["warnTime"] = "$mWarnTime"
        }
        mutableMap["page"] = "$page"
        mutableMap["pageSize"] = "$pageSize"
        showLoading("加载中...")
        val disposable = ApiRepository.warningNoticeList(mutableMap)
            .subscribe({ data ->
                dismissLoading()
                mDataPage = data.pages  //总页
                if (mAdapter.data != null) {
                    mAdapter.data.clear()
                    mAdapter.notifyDataSetChanged()
                    initPagesView(data.pages)
                }
                if (data.pages != 0) {
                    if (data.pages > 1 && data.current > 1) {
                        LogUtils.i("================1")
                        //当前需要更新页码
                        upPagesView(data.pages, data.current)
                        mAdapter.setList(data.records.toMutableList())
                    } else {
                        LogUtils.i("================2")
                        mAdapter.setNewInstance(data.records.toMutableList())
                        initPagesView(data.pages)
                    }
                }
            }, { throwable ->
                dismissLoading()
                showNetError(throwable)

            })
        addDisposable(disposable)
    }


    /**
     * 总页码 当前页  初始化
     */
    private fun initPagesView(pages: Int) {
        mPages = pages
        viewBinding.one.setBackgroundResource(R.drawable.bg_sou_suo_page)
        viewBinding.two.setBackgroundResource(R.drawable.bg_sou_suo_two_page)
        viewBinding.three.setBackgroundResource(R.drawable.bg_sou_suo_two_page)
        viewBinding.one.setTextColor(ContextCompat.getColor(this, R.color.white))
        viewBinding.two.setTextColor(ContextCompat.getColor(this, R.color.black))

        when (pages) {
            1 -> {
                viewBinding.one.visibility = View.VISIBLE
            }

            2 -> {
                viewBinding.two.visibility = View.VISIBLE
            }

            3 -> {
                viewBinding.two.visibility = View.VISIBLE
                viewBinding.three.visibility = View.VISIBLE
            }

            else -> {
                viewBinding.two.visibility = View.VISIBLE
                viewBinding.three.visibility = View.VISIBLE
                viewBinding.drop.visibility = View.VISIBLE
                viewBinding.many.visibility = View.VISIBLE
                viewBinding.many.text = "$pages"
            }
        }
        if (pages == 1 || pages == 0) {
            viewBinding.two.visibility = View.GONE
            viewBinding.three.visibility = View.GONE
            viewBinding.many.visibility = View.GONE
            viewBinding.drop.visibility = View.GONE
        }
        if (pages < 4) {
            when (pages) {
                1 -> {
                    viewBinding.two.visibility = View.GONE
                    viewBinding.three.visibility = View.GONE
                    viewBinding.many.visibility = View.GONE
                    viewBinding.drop.visibility = View.GONE
                }

                2 -> {
                    viewBinding.three.visibility = View.GONE
                    viewBinding.many.visibility = View.GONE
                    viewBinding.drop.visibility = View.GONE
                }

                3 -> {
                    viewBinding.many.visibility = View.GONE
                    viewBinding.drop.visibility = View.GONE
                }
            }
        }
    }

    //更新页码
    private fun upPagesView(pages: Int, current: Int) {
        LogUtils.i("======2")
        if (pages < 4) {
//            viewBinding.one.visibility = View.VISIBLE
            when (pages) {
                1 -> {
                    viewBinding.two.visibility = View.GONE
                    viewBinding.three.visibility = View.GONE
                    viewBinding.many.visibility = View.GONE
                    viewBinding.drop.visibility = View.GONE
                }

                2 -> {
                    viewBinding.three.visibility = View.GONE
                    viewBinding.many.visibility = View.GONE
                    viewBinding.drop.visibility = View.GONE
                }

                3 -> {
                    viewBinding.many.visibility = View.GONE
                    viewBinding.drop.visibility = View.GONE
                }
            }
            when (current) {
                1 -> {
                    viewBinding.one.setTextColor(
                        ContextCompat.getColor(
                            this,
                            R.color.white
                        )
                    )
                    viewBinding.two.setTextColor(
                        ContextCompat.getColor(
                            this,
                            R.color.black
                        )
                    )
                    viewBinding.three.setTextColor(
                        ContextCompat.getColor(
                            this,
                            R.color.black
                        )
                    )
                    viewBinding.one.setBackgroundResource(R.drawable.bg_sou_suo_page)
                    viewBinding.two.setBackgroundResource(R.drawable.bg_sou_suo_two_page)
                    viewBinding.three.setBackgroundResource(R.drawable.bg_sou_suo_two_page)
                }

                2 -> {
//                    viewBinding.two.visibility = View.VISIBLE
                    viewBinding.one.setTextColor(
                        ContextCompat.getColor(
                            this,
                            R.color.black
                        )
                    )
                    viewBinding.two.setTextColor(
                        ContextCompat.getColor(
                            this,
                            R.color.white
                        )
                    )
                    viewBinding.three.setTextColor(
                        ContextCompat.getColor(
                            this,
                            R.color.black
                        )
                    )
                    viewBinding.one.setBackgroundResource(R.drawable.bg_sou_suo_two_page)
                    viewBinding.two.setBackgroundResource(R.drawable.bg_sou_suo_page)
                    viewBinding.three.setBackgroundResource(R.drawable.bg_sou_suo_two_page)
                }

                3 -> {
//                    viewBinding.three.visibility = View.VISIBLE
                    viewBinding.one.setTextColor(
                        ContextCompat.getColor(
                            this,
                            R.color.black
                        )
                    )
                    viewBinding.two.setTextColor(
                        ContextCompat.getColor(
                            this,
                            R.color.black
                        )
                    )
                    viewBinding.three.setTextColor(
                        ContextCompat.getColor(
                            this,
                            R.color.white
                        )
                    )
                    viewBinding.one.setBackgroundResource(R.drawable.bg_sou_suo_two_page)
                    viewBinding.two.setBackgroundResource(R.drawable.bg_sou_suo_two_page)
                    viewBinding.three.setBackgroundResource(R.drawable.bg_sou_suo_page)
                }
            }
        } else {
//            viewBinding.many.visibility = View.VISIBLE
            viewBinding.three.text = "3"
            when (current) {
                1 -> {
                    viewBinding.one.setTextColor(
                        ContextCompat.getColor(
                            this,
                            R.color.white
                        )
                    )
                    viewBinding.two.setTextColor(
                        ContextCompat.getColor(
                            this,
                            R.color.black
                        )
                    )
                    viewBinding.three.setTextColor(
                        ContextCompat.getColor(
                            this,
                            R.color.black
                        )
                    )
                    viewBinding.one.setBackgroundResource(R.drawable.bg_sou_suo_page)
                    viewBinding.two.setBackgroundResource(R.drawable.bg_sou_suo_two_page)
                    viewBinding.three.setBackgroundResource(R.drawable.bg_sou_suo_two_page)
                }

                2 -> {
                    viewBinding.one.setTextColor(
                        ContextCompat.getColor(
                            this,
                            R.color.black
                        )
                    )
                    viewBinding.two.setTextColor(
                        ContextCompat.getColor(
                            this,
                            R.color.white
                        )
                    )
                    viewBinding.three.setTextColor(
                        ContextCompat.getColor(
                            this,
                            R.color.black
                        )
                    )
                    viewBinding.one.setBackgroundResource(R.drawable.bg_sou_suo_two_page)
                    viewBinding.two.setBackgroundResource(R.drawable.bg_sou_suo_page)
                    viewBinding.three.setBackgroundResource(R.drawable.bg_sou_suo_two_page)
                }

                3 -> {
                    viewBinding.one.setTextColor(
                        ContextCompat.getColor(
                            this,
                            R.color.black
                        )
                    )
                    viewBinding.two.setTextColor(
                        ContextCompat.getColor(
                            this,
                            R.color.black
                        )
                    )
                    viewBinding.three.setTextColor(
                        ContextCompat.getColor(
                            this,
                            R.color.white
                        )
                    )
                    viewBinding.one.setBackgroundResource(R.drawable.bg_sou_suo_two_page)
                    viewBinding.two.setBackgroundResource(R.drawable.bg_sou_suo_two_page)
                    viewBinding.three.setBackgroundResource(R.drawable.bg_sou_suo_page)
                }

                else -> {
                    viewBinding.three.text = "$current"
                    if (pages == current) {
                        viewBinding.three.text = "${current - 1}"

                        viewBinding.one.setTextColor(
                            ContextCompat.getColor(
                                this,
                                R.color.black
                            )
                        )
                        viewBinding.two.setTextColor(
                            ContextCompat.getColor(
                                this,
                                R.color.black
                            )
                        )
                        viewBinding.three.setTextColor(
                            ContextCompat.getColor(
                                this,
                                R.color.black
                            )
                        )
                        viewBinding.many.setTextColor(
                            ContextCompat.getColor(
                                this,
                                R.color.white
                            )
                        )
                        viewBinding.one.setBackgroundResource(R.drawable.bg_sou_suo_two_page)
                        viewBinding.two.setBackgroundResource(R.drawable.bg_sou_suo_two_page)
                        viewBinding.three.setBackgroundResource(R.drawable.bg_sou_suo_two_page)
                        viewBinding.many.setBackgroundResource(R.drawable.bg_sou_suo_page)

                    } else {
                        viewBinding.one.setTextColor(
                            ContextCompat.getColor(
                                this,
                                R.color.black
                            )
                        )
                        viewBinding.two.setTextColor(
                            ContextCompat.getColor(
                                this,
                                R.color.black
                            )
                        )
                        viewBinding.three.setTextColor(
                            ContextCompat.getColor(
                                this,
                                R.color.white
                            )
                        )
                        viewBinding.many.setTextColor(
                            ContextCompat.getColor(
                                this,
                                R.color.black
                            )
                        )

                        viewBinding.one.setBackgroundResource(R.drawable.bg_sou_suo_two_page)
                        viewBinding.two.setBackgroundResource(R.drawable.bg_sou_suo_two_page)
                        viewBinding.three.setBackgroundResource(R.drawable.bg_sou_suo_page)
                        viewBinding.many.setBackgroundResource(R.drawable.bg_sou_suo_two_page)
                    }
                }
            }
        }
    }

    //待处理数量
    private fun warningNoticeCount() {
        showLoading("加载中...")
        val disposable = ApiRepository.warningNoticeCount(ChemicalApp.subjectId!!)
            .subscribe({ data ->
                dismissLoading()
                viewBinding.countSi.text = "待处理:$data"
            }, { throwable ->
                dismissLoading()
                showNetError(throwable)
            })
        addDisposable(disposable)
    }

    private fun getTimeView() {
        val dialog = DatePickDialog(this)

        //设置上下年分限制
        with(dialog) {

            //设置上下年分限制
            setYearLimt(5)

            //设置标题
            setTitle("选择时间")

            //设置类型
            setType(DateType.TYPE_YMD)

            //设置消息体的显示格式，日期格式
            setMessageFormat(DateType.TYPE_YMD.toString())

//            //设置选择回调
//            setOnChangeLisener{
//                val time = it.time
//                LogUtils.i("=============$time")
//            }

            //设置点击确定按钮回调
            setOnSureLisener {
                val date = Date(it.time)
                // 使用 Date 对象获取年、月、日
                val year: Int = getYearFromDate(date)
                val month: Int = getMonthFromDate(date)
                val day: Int = getDayFromDate(date)
                val formattedMonth = if (month < 10) {
                    "0$month"
                } else {
                    month.toString()
                }
                val formattedday = if (day < 10) {
                    "0$day"
                } else {
                    day.toString()
                }
                viewBinding.whole.isChecked = true
                viewBinding.oneMonth.isChecked = false
                viewBinding.threeMonths.isChecked = false
                // $year-$formattedMonth-$formattedday
                viewBinding.dateTime.text = "$year-$formattedMonth-$formattedday"
                mWarnTime = "$year-$formattedMonth-$formattedday"
                getLists()
            }
            show()
        }
    }

    // 获取年份
    private fun getYearFromDate(date: Date?): Int {
        val calendar = Calendar.getInstance()
        calendar.time = date
        return calendar[Calendar.YEAR]
    }

    // 获取月份（注意：返回的月份范围是 0-11，所以需要加1）
    private fun getMonthFromDate(date: Date?): Int {
        val calendar = Calendar.getInstance()
        calendar.time = date
        return calendar[Calendar.MONTH] + 1
    }

    // 获取天数
    private fun getDayFromDate(date: Date?): Int {
        val calendar = Calendar.getInstance()
        calendar.time = date
        return calendar[Calendar.DAY_OF_MONTH]
    }

}