package com.bjzc.bhzhgd.activity.zhgd

import android.Manifest
import android.content.ContentValues
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Color
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.widget.AdapterView
import android.widget.TextView
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.bjzc.bhzhgd.DBModel.XSJJHDataBean
import com.bjzc.bhzhgd.DBModel.XSJJHXZDataBean
import com.bjzc.bhzhgd.R
import com.bjzc.bhzhgd.adapter.CommonAdapter
import com.bjzc.bhzhgd.adapter.DeviceTwoLevelAdapter
import com.bjzc.bhzhgd.base.MipcaActivityCapture
import com.bjzc.bhzhgd.bean.XsRequestInfo
import com.bjzc.bhzhgd.contans.Contans
import com.bjzc.bhzhgd.databinding.ActivityDeviceListBinding
import com.bjzc.bhzhgd.utils.GsonUtils
import com.bjzc.bhzhgd.utils.OAToolbar
import com.bjzc.bhzhgd.utils.SPUtils
import com.bjzc.bhzhgd.weight.BaCheckDialog
import com.rehome.scbaxj.base.BaseActivityOaToolbarViewBinding
import com.yolanda.nohttp.NoHttp
import com.yolanda.nohttp.RequestMethod
import com.yolanda.nohttp.rest.Response
import org.litepal.crud.DataSupport
import java.text.SimpleDateFormat
import java.util.ArrayList
import java.util.Date
import com.bjzc.bhzhgd.adapter.ViewHolder
import com.bjzc.bhzhgd.bean.DeviceRequestInfo
import com.bjzc.bhzhgd.bean.DeviceZhgdBean
import com.bjzc.bhzhgd.utils.HttpListener
import com.bjzc.bhzhgd.utils.NoProgresshttpUtils


class DeviceListActivity : BaseActivityOaToolbarViewBinding<ActivityDeviceListBinding>() {

    //private lateinit var headView: View
    //private lateinit var tv_djrw: TextView
    private val CAMERA_REQUEST_CODE = 3 //请求码
    var nfcValue: String? = null
    private lateinit var type: String
    private lateinit var username: String
    private lateinit var launcherResult: ActivityResultLauncher<Intent?>

    private lateinit var adapter: DeviceTwoLevelAdapter
    private var datas: MutableList<DeviceZhgdBean.DeviceBean> = mutableListOf()


//    DeviceTwoLevelAdapter
//    DeviceThreeLevelAdapter



    //adapter_device_two_level
    //adapter_device_three_level


    override fun getViewBinding() = ActivityDeviceListBinding.inflate(layoutInflater)

    override fun getToolbar() = binding.toolbarView.toolbar

    override fun initView() {
        initToolbar("二级电箱", "扫码") {
            //动态权限申请
            //动态权限申请
            if (ContextCompat.checkSelfPermission(
                    this,
                    Manifest.permission.CAMERA
                ) != PackageManager.PERMISSION_GRANTED
            ) {
                ActivityCompat.requestPermissions(
                    this,
                    arrayOf(Manifest.permission.CAMERA),
                    CAMERA_REQUEST_CODE
                )
            } else {
                //扫码
                goScan()
            }
        }

//        binding.toolbarView.toolbar.ivLeft.visibility=View.GONE

        launcherResult =
            registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
                if (it.resultCode == RESULT_OK) {
                    val bundle: Bundle? = it.data?.extras
                    val ewm = bundle?.getString("result")
                    if (ewm != null) {
                        handleTwoCodeCheck(ewm)
                    }
                }
            }


        username = SPUtils.get(context, Contans.USERID, "") as String
        binding.lv.emptyView = binding.tvNodata

        adapter = DeviceTwoLevelAdapter(context, datas)
        binding.lv.adapter = adapter

        binding.tvNodata.visibility= View.VISIBLE
        binding.lv.visibility=View.GONE

        binding.lv.onItemClickListener =
            AdapterView.OnItemClickListener { _, _, position, _ ->
                val item = datas[position]
                val data = item.data
                if(data!=null&&data.size>0){
                    val intent = Intent(context, DeviceThreeLevelActivity::class.java)
                    //intent.putExtra("data", GsonUtils.GsonString(data))
                    intent.putParcelableArrayListExtra("data", ArrayList(data))
                    startActivity(intent)
                }
            }

    }

    override fun initData() {

    }


    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String?>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (CAMERA_REQUEST_CODE == requestCode) {
            if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //扫码
                goScan()
            } else {
                //权限拒绝
                Toast.makeText(this, "你拒绝了权限申请，无法打开相机扫码哟！", Toast.LENGTH_SHORT).show()
            }
        }
    }

    private fun goScan() {
        val intent = Intent(this, MipcaActivityCapture::class.java)
        launcherResult.launch(intent)
    }

    private fun removeDuplicate(list: MutableList<XSJJHXZDataBean>): MutableList<XSJJHXZDataBean> {
        for (i in 0 until list.size - 1) {
            for (j in list.size - 1 downTo i + 1) {
                if (list[j].qybh == list[i].qybh) {
                    list.removeAt(j)
                }
            }
        }
        return list
    }


    //处理二维码的数据
    private fun handleTwoCodeCheck(result: String?) {
        if(TextUtils.isEmpty(result)){
            showToast("二维码无法识别")
        }else{
            uploadLocationByNFC(result!!)
        }
    }

    private fun uploadLocationByNFC(ewm: String) {
        val requestxs = NoHttp.createStringRequest(
            Contans.IP + Contans.ZHGD_GET_DEVICE_LIST,
            RequestMethod.POST
        )
        requestxs.setDefineRequestBodyForJson(createJsonByEwm(ewm))
        NoProgresshttpUtils.getInstance().add(this, 1, requestxs, object : HttpListener<String?> {
            override fun onSucceed(what: Int, response: Response<String?>?) {
                val result = response?.get()
                showLog("----------------->>>")
                showLog(result)
                val bean = GsonUtils.GsonToBean(
                    result,
                    DeviceZhgdBean::class.java
                )
                if (bean.state == 1) {
                    //showToast("获取数据成功")
                    if (bean.data != null && bean.data.size>0) {
                        datas.clear()
                        datas.addAll(bean.data)
                        adapter.notifyDataSetChanged()
                        binding.tvNodata.visibility= View.GONE
                        binding.lv.visibility=View.VISIBLE
                    }else {
                        showToast("获取数据失败")
                        datas.clear()
                        adapter.notifyDataSetChanged()
                        binding.tvNodata.visibility= View.VISIBLE
                        binding.lv.visibility=View.GONE
                    }
                }
            }

            override fun onFailed(what: Int, response: Response<String?>?) {

            }
        })
    }

    private fun createJsonByEwm(ewm: String): String {
        val info = DeviceRequestInfo()
        info.action = "SGSB_CX"
        info.ewm = ewm
        val json = GsonUtils.GsonString(info)
        showLog(json)
        return json
    }

    override fun onRestart() {
        super.onRestart()
    }

    override fun onResume() {
        super.onResume()
    }
}