package xn.xxp.main.person

import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import core.ui.fragment.RcBaseFragment
import core.ui.widget.decoration.NoLastLineItemDecoration
import http.client.ApiRepository
import http.vo.response.LabPersonVo
import xn.xxp.R
import xn.xxp.databinding.FragmentLabPersonDutyBinding
import xn.xxp.databinding.ViewPersonListEmptyBinding
import java.text.SimpleDateFormat
import java.util.*

/**
 * 人员信息-值班人员 type=1
 * 人员信息-巡查人员 type=2
 *
 * @author ReiChin_
 */
class LabDutyPersonFragment :
    RcBaseFragment<FragmentLabPersonDutyBinding>() {

    private var mType: Int = TYPE_DUTY // 1-值班人员 2-巡查人员
    private lateinit var mLabId: String

    private lateinit var mMonday: Calendar

    private val mWeekday1Adapter by lazy { LabDutyPersonAdapter(mType) }
    private val mWeekday2Adapter by lazy { LabDutyPersonAdapter(mType) }
    private val mWeekday3Adapter by lazy { LabDutyPersonAdapter(mType) }
    private val mWeekday4Adapter by lazy { LabDutyPersonAdapter(mType) }
    private val mWeekday5Adapter by lazy { LabDutyPersonAdapter(mType) }
    private val mWeekday6Adapter by lazy { LabDutyPersonAdapter(mType) }
    private val mWeekday7Adapter by lazy { LabDutyPersonAdapter(mType) }

    companion object {
        const val TYPE_DUTY = 1 // 值班人员
        const val TYPE_PATROL = 2 // 巡查人员

        fun newInstance(type: Int, labId: String): LabDutyPersonFragment {
            val args = Bundle()
            args.putInt("type", type)
            args.putString("labId", labId)
            val fragment = LabDutyPersonFragment()
            fragment.arguments = args
            return fragment
        }
    }

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

    override fun initViews(savedInstanceState: Bundle?) {
        mType = requireArguments().getInt("type")
        mLabId = requireArguments().getString("labId")!!
        mMonday = Calendar.getInstance().apply {
            firstDayOfWeek = Calendar.MONDAY
            time = Date()
            set(Calendar.DAY_OF_WEEK, Calendar.MONDAY)
        }
        updateDateViews()
        initRecyclerView()
        // 上一周
        viewBinding.prev.setOnClickListener {
            // 1、日期前移7天
            mMonday.add(Calendar.DATE, -7)
            // 2、更新日历
            updateDateViews()
            // 3、查询值班人员
            queryDutyPerson()
        }
        // 下一周
        viewBinding.next.setOnClickListener {
            // 1、日期后移7天
            mMonday.add(Calendar.DATE, 7)
            // 2、更新日历
            updateDateViews()
            // 3、查询值班人员
            queryDutyPerson()
        }
        queryDutyPerson()
    }

    private fun updateDateViews() {
        val calendar = Calendar.getInstance().apply {
            time = mMonday.time
        }
        // 周一
        updateDateViews(calendar, viewBinding.weekday1Text, viewBinding.currentWeekday1, false)
        // 周二
        updateDateViews(calendar, viewBinding.weekday2Text, viewBinding.currentWeekday2)
        // 周三
        updateDateViews(calendar, viewBinding.weekday3Text, viewBinding.currentWeekday3)
        // 周四
        updateDateViews(calendar, viewBinding.weekday4Text, viewBinding.currentWeekday4)
        // 周五
        updateDateViews(calendar, viewBinding.weekday5Text, viewBinding.currentWeekday5)
        // 周六
        updateDateViews(calendar, viewBinding.weekday6Text, viewBinding.currentWeekday6)
        // 周日
        updateDateViews(calendar, viewBinding.weekday7Text, viewBinding.currentWeekday7)
    }

    private fun updateDateViews(
        calendar: Calendar,
        weekday: TextView,
        current: TextView,
        addDay: Boolean = true
    ) {
        if (addDay) calendar.add(Calendar.DAY_OF_MONTH, 1)
        weekday.text = "${calendar.get(Calendar.DAY_OF_MONTH)}"
        current.visibility =
            if (isSameDay(calendar, Calendar.getInstance())) View.VISIBLE else View.INVISIBLE
    }

    private fun initRecyclerView() {
        // 周一
        initRecyclerView(viewBinding.dutyWeekday1, mWeekday1Adapter)
        // 周二
        initRecyclerView(viewBinding.dutyWeekday2, mWeekday2Adapter)
        // 周三
        initRecyclerView(viewBinding.dutyWeekday3, mWeekday3Adapter)
        // 周四
        initRecyclerView(viewBinding.dutyWeekday4, mWeekday4Adapter)
        // 周五
        initRecyclerView(viewBinding.dutyWeekday5, mWeekday5Adapter)
        // 周六
        initRecyclerView(viewBinding.dutyWeekday6, mWeekday6Adapter)
        // 周日
        initRecyclerView(viewBinding.dutyWeekday7, mWeekday7Adapter)
    }

    private fun initRecyclerView(recyclerView: RecyclerView, adapter: LabDutyPersonAdapter) {
        recyclerView.layoutManager = LinearLayoutManager(requireActivity())
        val itemDecoration = NoLastLineItemDecoration(requireActivity(), DividerItemDecoration.VERTICAL).apply {
            setDrawable(ContextCompat.getDrawable(requireActivity(), R.drawable.divider_vertical_transparent_10)!!)
        }
        recyclerView.addItemDecoration(itemDecoration)
        recyclerView.adapter = adapter
    }

    private fun queryDutyPerson() {
        showLoading("查询中...")
        val monday = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(mMonday.time)
        val disposable = ApiRepository.queryDutyPerson(mType, mLabId, monday)
            .subscribe({ data ->
                dismissLoading()
                dispatchDutyPerson(data.weekday1, mWeekday1Adapter)
                dispatchDutyPerson(data.weekday2, mWeekday2Adapter)
                dispatchDutyPerson(data.weekday3, mWeekday3Adapter)
                dispatchDutyPerson(data.weekday4, mWeekday4Adapter)
                dispatchDutyPerson(data.weekday5, mWeekday5Adapter)
                dispatchDutyPerson(data.weekday6, mWeekday6Adapter)
                dispatchDutyPerson(data.weekday7, mWeekday7Adapter)
            }, { throwable ->
                dismissLoading()
                showNetError(throwable)
                throwable.printStackTrace()
            })
        addDisposable(disposable)
    }

    private fun dispatchDutyPerson(dutyPersons: MutableList<LabPersonVo>?,
                                   adapter: LabDutyPersonAdapter
    ) {
        if (dutyPersons.isNullOrEmpty()) {
            val emptyViewBinding = ViewPersonListEmptyBinding.inflate(layoutInflater)
            emptyViewBinding.emptyImage.setImageResource(R.mipmap.img_kzt)
            emptyViewBinding.emptyText.setTextColor(Color.WHITE)
            emptyViewBinding.emptyText.text = if (TYPE_DUTY == mType) "暂无值班人员" else "暂无巡查人员"
            adapter.setEmptyView(emptyViewBinding.root)
        }
        adapter.setNewInstance(dutyPersons)
    }

    private fun isSameDay(c1: Calendar, c2: Calendar): Boolean {
        return c1.get(Calendar.YEAR) == c2.get(Calendar.YEAR)
                && c1.get(Calendar.MONTH) == c2.get(Calendar.MONTH)
                && c1.get(Calendar.DAY_OF_MONTH) == c2.get(Calendar.DAY_OF_MONTH)
    }

}

// type 1-值班人员 2-巡查人员
private class LabDutyPersonAdapter(private val type: Int) :
    BaseQuickAdapter<LabPersonVo, BaseViewHolder>(R.layout.item_lab_person_duty) {

    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)
            .into(holder.getView(R.id.pPhoto))

        holder.setText(R.id.pName, item.userName)
            .setText(R.id.pPhone, item.userPhone)
        if (1 == type) {
            holder.setGone(R.id.patrolCnt, true)
                .setGone(R.id.patrolTime, true)
        } else {
            holder.setGone(R.id.patrolCnt, false)
                .setGone(R.id.patrolTime, false)
                .setText(R.id.patrolCnt, "签到次数：${item.signNumber ?: ""}(次)")
                .setText(R.id.patrolTime, "最后巡查：${formatPatrolTime(item.signOut)}")
        }
    }

    private fun formatPatrolTime(time: String?): CharSequence {
        // 2023-03-30 15:54:00 => 15:54
        return if (time.isNullOrEmpty()) "" else time.subSequence(11, 16)
    }

}