package com.dahe.pass.ui.home

import android.graphics.Color
import android.text.TextUtils
import android.view.View
import android.widget.TextView
import androidx.core.widget.addTextChangedListener
import androidx.recyclerview.widget.LinearLayoutManager
import com.bigkoo.pickerview.builder.TimePickerBuilder
import com.dahe.dispatch.cuspop.SelectTimePopup
import com.dahe.mylibrary.base.BaseFragment
import com.dahe.mylibrary.net.CommonResponseBean
import com.dahe.mylibrary.net.PagerBean
import com.dahe.mylibrary.utils.ActivityUtils
import com.dahe.mylibrary.utils.TimeUtil
import com.dahe.pass.R
import com.dahe.pass.adapter.ApplyAdapter
import com.dahe.pass.bean.ApplyBean
import com.dahe.pass.bean.HomeTimeBean
import com.dahe.pass.bean.PassBean
import com.dahe.pass.net.BaseObserver
import com.dahe.pass.net.DataManager
import com.dahe.pass.net.RxHttpCallBack
import com.dahe.pass.ui.home.activity.ApplyActivity
import com.dahe.pass.ui.home.activity.ApplyDetailActivity
import com.lxj.xpopup.XPopup
import kotlinx.android.synthetic.main.fragment_home.*
import java.text.SimpleDateFormat
import java.util.*

class HomeFragment : BaseFragment(), View.OnClickListener {
    lateinit var applyAdapter: ApplyAdapter
    var startTime: String = ""
    var endTime: String = ""


    override fun getContentViewLayoutID() = R.layout.fragment_home

    override fun onFragmentVisibleChange(isVisible: Boolean) {
        if (isVisible) {
            initData()
        } else {
        }
    }


    override fun onFragmentFirstVisible() {
        setTitleBar("申请记录", true) {
            ActivityUtils.startActivityForResult(requireActivity(), ApplyActivity::class.java, 1)
        }


        initRec()
        tvSearch.setOnClickListener(this)
        initData()

        tvSearch.setOnClickListener(this)
        llClear.setOnClickListener(this)
        tvSearch.addTextChangedListener {
            if (it.toString().length>0){
                llClear.visibility = View.VISIBLE
            }else{
                llClear.visibility = View.GONE
            }
        }

    }

    fun initData() {
        val homeTimeBean = HomeTimeBean()
        val parmDao = HomeTimeBean.ParmDao()
        parmDao.createDate = tvSearch.text.toString()
        homeTimeBean.params = parmDao
        DataManager.getInstance().applyList(startTime,endTime)
            .compose(DataManager.setThread())
            .subscribe(BaseObserver(mContext, object : RxHttpCallBack<PagerBean<ApplyBean>>() {
                override fun onSuccess(t: CommonResponseBean<PagerBean<ApplyBean>>) {
                    super.onSuccess(t)
                    applyAdapter.setList(t.data.rows)
                }
            }))
        getCount()
    }

    fun getCount() {
        DataManager.getInstance().applyCount(startTime,endTime)
            .compose(DataManager.setThread())
            .subscribe(BaseObserver(mContext, object : RxHttpCallBack<PassBean>() {
                override fun onSuccess(t: CommonResponseBean<PassBean>?) {
                    val data = t?.data
                    tvYsq.text = data?.numberOfPassesRequired.toString()
                    tvYsp.text = data?.numberOfPasses.toString()
                    tvMf1.text = data?.requiredNumMF
                    tvSf1.text = data?.requiredNumSF
                    tvMf2.text = data?.passesNumMF
                    TvSf2.text = data?.passesNumSF
                }
            }))
    }

    override fun onClick(v: View) {
        when (v.id) {
            R.id.tvSearch -> search()
//            R.id.tvSearch -> setBir(tvSearch)
            R.id.llClear -> {
                tvSearch.text = ""
                startTime = ""
                endTime = ""
                initData()
            }
        }
    }

    fun setBir(view: TextView) {
        val startDate = Calendar.getInstance()
        val endtDate = Calendar.getInstance()
        val currDate = Calendar.getInstance()
        startDate[1990, 0] = 1
        endtDate[2100, 0] = 1


        if (!TextUtils.isEmpty(view.getText())) {
            val date = TimeUtil.string2Date(view.getText().toString(),
                SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()))
            if (date != null) currDate.time = date
        }


        val pvTime = TimePickerBuilder(
            context
        ) { date, v -> //选中事件回调
//            TimeUtil.date2String(date,SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()))
            val data =
                TimeUtil.date2String(date, SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()))
            view.text = data
            initData()
        }.setSubmitColor(Color.parseColor("#F1474B")) //确定按钮文字颜色
            .setCancelColor(Color.parseColor("#F1474B")) //取消按钮文字颜色
            .setTitleBgColor(Color.parseColor("#FFFFFF"))
            .setType(booleanArrayOf(true, true, true, false, false, false))
            .setTitleText("选择时间")
            .setDate(currDate)
            .setRangDate(startDate, endtDate)
            .setBgColor(Color.parseColor("#F5F5F5"))
            .build()
        //                 pvTime.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
        pvTime.show()
    }

    fun search() {
        XPopup.Builder(mContext)
            .enableDrag(true)
            .hasShadowBg(true)
            .isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
            .asCustom(SelectTimePopup(mContext).setOnMyItemClickListener(object :
                SelectTimePopup.OnMyItemClickListener {
                override fun onItemClick(startTime: String, endTime: String) {
                    if (startTime.isNullOrEmpty()||endTime.isNullOrEmpty()){
                        showToast("请完善时间")
                        return
                    }

                    tvSearch.text = """${startTime}至${endTime}"""
                    this@HomeFragment.startTime = startTime
                    this@HomeFragment.endTime = endTime
                    initData()
                }
            }))
            .show()
    }


    fun initRec() {
        recyclerView.layoutManager =
            LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false)
        recyclerView.setHasFixedSize(true)
        applyAdapter = ApplyAdapter(-1)
        recyclerView.adapter = applyAdapter


//        val mutableListOf = mutableListOf<ApplyBean>()
//        mutableListOf.add(ApplyBean())
//        mutableListOf.add(ApplyBean())
//        mutableListOf.add(ApplyBean())
//        applyAdapter.setList(mutableListOf)

//        applyAdapter.setOnItemClickListener { adapter, view, position ->
//            ActivityUtils.startActivity(mContext, ApplyDetailActivity::class.java)
//        }
    }


}