package com.dahe.pass.ui.gone

import android.content.Intent
import android.graphics.Color
import android.os.Bundle
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.callback.RefreshCallBack
import com.dahe.mylibrary.net.CommonResponseBean
import com.dahe.mylibrary.net.PagerBean
import com.dahe.mylibrary.utils.ActivityUtils
import com.dahe.mylibrary.utils.PickUtils
import com.dahe.mylibrary.utils.TimeUtil
import com.dahe.pass.R
import com.dahe.pass.adapter.GoneAdapter
import com.dahe.pass.base.AppConfig
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.gone.activity.AddGoActivity
import com.dahe.pass.ui.gone.activity.EditGoActivity
import com.lxj.xpopup.XPopup
import kotlinx.android.synthetic.main.fragment_gone.*
import java.text.SimpleDateFormat
import java.util.*


class GoneFragment : BaseFragment(), RefreshCallBack, View.OnClickListener {

    lateinit var applyAdapter: GoneAdapter

    override fun getContentViewLayoutID() = R.layout.fragment_gone

    override fun onFragmentVisibleChange(isVisible: Boolean) {
        if (isVisible) {
            initData()
//            DataManager.getInstance().passList()
//                .compose(DataManager.setThread())
//                .subscribe(BaseObserver(mContext, object : RxHttpCallBack<PagerBean<PassBean>>() {
//                    override fun onSuccess(t: CommonResponseBean<PagerBean<PassBean>>) {
//                        super.onSuccess(t)
//                        val data = t.data
//                        val total = data.total
//                    }
//                }))

        } else {
        }
    }


    override fun onFragmentFirstVisible() {
        setTitleBar("已使用", true) {
//            var intent = Intent(Intent.ACTION_GET_CONTENT);
//            intent.setType("*/*");//设置类型，我这里是任意类型，可以过滤文件类型
//            intent.addCategory(Intent.CATEGORY_OPENABLE);
//            startActivityForResult(intent, 10005)

            ActivityUtils.startActivityForResult(requireActivity(), AddGoActivity::class.java, 1)
        }

        initRec()
        initData()

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

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode==10005){
            val data1 = data?.data
            //文件名
            val path = PickUtils.getPath(getContext(), data1)
            //文件名
            val mFileName = PickUtils.getFileName(requireContext(), data1)
        }
    }

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

    override fun getRefreshDate(stat: Int, page: Int, count: Int) {
    }

    fun initData() {
        DataManager.getInstance().passCount(tvSearch.text.toString())
            .compose(DataManager.setThread())
            .subscribe(BaseObserver(mContext, object : RxHttpCallBack<PassBean>() {
                override fun onSuccess(t: CommonResponseBean<PassBean>) {
                    super.onSuccess(t)
                    tvYf.text = t?.data?.numberOfPasses.toString()
                    tvYsy.text = t?.data?.passNoNumber.toString()
                    tvYsp.text = t.data.notUsedNum

                    tvMf1.text = t?.data?.numberOfPassesMF
                    tvMf2.text = t?.data?.passNoNumberMF
                    tvMf3.text = t?.data?.notUsedNumMF
                    tvSf1.text = t?.data?.numberOfPassesSF
                    tvSf2.text = t?.data?.passNoNumberSF
                    tvSf3.text = t?.data?.notUsedNumSF
                }
            }))

        DataManager.getInstance().passList(tvSearch.text.toString())
            .compose(DataManager.setThread())
            .subscribe(BaseObserver(mContext, object : RxHttpCallBack<PagerBean<PassBean>>() {
                override fun onSuccess(t: CommonResponseBean<PagerBean<PassBean>>?) {
                    super.onSuccess(t)
                    applyAdapter.setList(t?.data?.rows)
                }
            }))
//        Observable.zip(DataManager.getInstance().passCount(),
//            DataManager.getInstance().passList(tvSearch.text.toString()),
//            { item1, item2 ->
//                val objectCommonResponseBean: CommonResponseBean<PagerBean<PassBean>> =
//                    CommonResponseBean<PagerBean<PassBean>>()
//                val pagerBean = PagerBean<PassBean>()
//                pagerBean.total = item2.data.total
//                pagerBean.count = item1.data.passNoNumber
//                pagerBean.rows = item2.data.rows
//
//                objectCommonResponseBean.setCode(item1.getCode())
//                objectCommonResponseBean.setData(pagerBean)
//                objectCommonResponseBean
//            }).compose(DataManager.setThread())
//            .subscribe(BaseObserver(mContext, object : RxHttpCallBack<PagerBean<PassBean>>() {
//                override fun onSuccess(t: CommonResponseBean<PagerBean<PassBean>>) {
//                    super.onSuccess(t)
//                    val data = t.data
//                    tvYsy.text = data.count.toString()
//                    tvYf.text = data.total.toString()
//                    tvYsp.text = (data.total - data.count).toString()
//                    applyAdapter.setList(data.rows)
//                }
//            }))
    }

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

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

        applyAdapter.addChildClickViewIds(R.id.tvEdit)
        applyAdapter.setOnItemChildClickListener { adapter, view, position ->
            val bundle = Bundle()
            bundle.putSerializable(AppConfig.BEAN, applyAdapter.data[position])
            ActivityUtils.startActivity(requireActivity(), EditGoActivity::class.java, bundle)
        }

    }

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

}