package com.qimai.log.ui

import android.annotation.SuppressLint
import android.graphics.Color
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.*
import com.qimai.log.QLog
import com.qimai.log.databinding.ActivityLogUpBinding
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class LogUpActivity : AppCompatActivity() {

    private lateinit var bind: ActivityLogUpBinding

    private val mAdapter by lazy { LogUpAdapter() }

    override fun onCreate(savedInstanceState: Bundle?) {
        BarUtils.setStatusBarColor(this, Color.WHITE)
        BarUtils.setStatusBarLightMode(this, true)
        super.onCreate(savedInstanceState)
        bind = ActivityLogUpBinding.inflate(layoutInflater)
        setContentView(bind.root)
        init()
    }

    @SuppressLint("SetTextI18n")
    private fun init() {
        val startDate = TimeUtils.getNowString(TimeUtils.getSafeDateFormat("yyyy-MM-dd 00:00:00"))
        val endDate = TimeUtils.getNowString(TimeUtils.getSafeDateFormat("yyyy-MM-dd HH:mm:ss"))
        bind.etDate.setText("$startDate -- $endDate")
        bind.rv.layoutManager = LinearLayoutManager(this)
        bind.rv.adapter = mAdapter
        bind.btnSearch.setOnClickListener { getLogData() }
        getLogData()
    }

    private fun getLogData() {
        lifecycleScope.launch(Dispatchers.IO) {
            val timeStr = bind.etDate.text.toString()
            val timeSplit = timeStr.split(" -- ")
            val startTime = timeSplit[0]
            val endTime = timeSplit[1]
            QLog.f()
            val list = QLog.getLogListByPeriod(startTime, endTime)
            withContext(Dispatchers.Main) {
                if (list.isNullOrEmpty()) {
                    ToastUtils.showShort("未查询到日志")
                    return@withContext
                }
                KeyboardUtils.hideSoftInput(bind.btnSearch)
                bind.etDate.clearFocus()
                mAdapter.setNewData(list)
            }
        }
    }
}