package xn.xxp.home.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.bumptech.glide.Glide
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.module.LoadMoreModule
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import core.ui.fragment.RcRefreshFragment
import core.ui.widget.decoration.GridSpacingItemDecoration
import core.util.ifNullOrEmpty
import http.client.ApiRepository
import http.vo.response.LabPersonVo
import io.reactivex.rxjava3.disposables.Disposable
import xn.xxp.R
import xn.xxp.databinding.FragmentAccessPersonBinding
import xn.xxp.home.HomeFragmentCallback
import xn.xxp.utils.Tool

/**
 * 主页-实验人员 type=1
 * 主页-准入人员 type=2
 *
 * @author ReiChin_
 */
class AccessPersonFragment :
    RcRefreshFragment<LabPersonVo, FragmentAccessPersonBinding>() {

    override val mSrlRefresh: SwipeRefreshLayout by lazy { viewBinding.swipeRefreshLayout }
    override val mRvContent: RecyclerView by lazy { viewBinding.recyclerView }
    override val mAdapter: BaseQuickAdapter<LabPersonVo, BaseViewHolder>
            by lazy { AccessPersonAdapter(mType) }

    private var mType: Int = TYPE_EXPERIMENT // 1-实验人员 2-准入人员
    private lateinit var mLabId: String

    companion object {
        const val TAG_EXPERIMENT = "AccessPersonFragment_1"
        const val TAG_ACCESS = "AccessPersonFragment_2"

        const val TYPE_EXPERIMENT = 1 // 实验人员
        const val TYPE_ACCESS = 2 // 准入人员
    }

    override fun createViewBinding(
        inflater: LayoutInflater,
        container: ViewGroup?
    ): FragmentAccessPersonBinding {
        return FragmentAccessPersonBinding.inflate(inflater, container, false)
    }

    override fun initViews(savedInstanceState: Bundle?) {
        mType = requireArguments().getInt("type")
        mLabId = requireArguments().getString("labId")!!
        super.initViews(savedInstanceState)

        viewBinding.personExpand.setOnClickListener {
            requireFragmentManager().popBackStack()
            val activity = requireActivity()
            if (activity is HomeFragmentCallback) {
                activity.closePersonPanel()
            }
        }
    }

    override fun createLayoutManager(): RecyclerView.LayoutManager {
        return GridLayoutManager(requireActivity(), 4)
    }

    override fun createItemDecoration(): RecyclerView.ItemDecoration {
        return GridSpacingItemDecoration(
            4,
            Tool.INSTANCE.dip2px(7f),
            Tool.INSTANCE.dip2px(15f), true
        )
    }

    override fun queryData(): Disposable {
        return ApiRepository.queryAccessPerson(mType, mLabId, mCurrentPage, PAGE_SIZE)
            .subscribe({ data ->
                dispatchLoadDataSuccess(data)
            }, { throwable ->
                dispatchLoadDataFailure(throwable)
            })
    }

}

// type 1-实验人员 2-准入人员
private class AccessPersonAdapter(private val type: Int) :
    BaseQuickAdapter<LabPersonVo, BaseViewHolder>(R.layout.item_access_person),
    LoadMoreModule {

    override fun convert(holder: BaseViewHolder, item: LabPersonVo) {
        // 头像
        Glide.with(context)
            .load(item.avatar)
            .placeholder(R.mipmap.icon_sign_in_avatar)
            .error(R.mipmap.icon_sign_in_avatar)
//            .transform(RoundedCorners(DeviceUtils.dip2px(context, 6f)))
            .into(holder.getView(R.id.pPhoto))

        holder.setText(R.id.pName, "姓名：${item.userName.ifNullOrEmpty()}")
            .setText(R.id.pCardNumber, "学号(工号): ${item.jobNumber.ifNullOrEmpty()}")
        if (1 == type) {
            // 1-实验人员  签到时间：01-05 14:56
            holder.setText(R.id.pTime, "签到时间: ${formatSignTime(item.signTime)}")
        } else {
            // 2-准入人员  准入期限：24-10-10
            holder.setText(R.id.pTime, "准入期限: ${formatValidTime(item.validEndTime)}")
        }
    }

    private fun formatValidTime(input: String?): String {
        // 2024-10-10 => 24-10-10
        return if (input.isNullOrEmpty()) "" else input.substring(2, input.length)
    }

    private fun formatSignTime(time: String?): CharSequence {
        // 2023-03-30 15:45:25 => 03-30 15:45
        return if (time.isNullOrEmpty()) "" else time.substring(5, 16)
    }

}