package com.rehome.sgbaxj.activity.sbxj

import android.text.TextUtils
import android.util.Log
import android.view.View
import android.widget.CheckBox
import android.widget.TextView
import com.rehome.sgbaxj.R
import com.rehome.sgbaxj.adapter.BamjAdapter
import com.rehome.sgbaxj.base.BaseActivityOaToolbarViewBinding
import com.rehome.sgbaxj.bean.MjList
import com.rehome.sgbaxj.bean.MjRequestInfo
import com.rehome.sgbaxj.bean.XsRequestInfo
import com.rehome.sgbaxj.contans.Contans
import com.rehome.sgbaxj.databinding.ActivityBamjBinding
import com.rehome.sgbaxj.utils.GsonUtils
import com.rehome.sgbaxj.utils.HttpListener
import com.rehome.sgbaxj.utils.NetworkUtil
import com.rehome.sgbaxj.utils.NoProgresshttpUtils
import com.rehome.sgbaxj.utils.SPUtils
import com.rehome.sgbaxj.weight.MjEditDialog
import com.rehome.sgbaxj.weight.WaitDialog
import com.yolanda.nohttp.NoHttp
import com.yolanda.nohttp.RequestMethod
import com.yolanda.nohttp.rest.Request
import com.yolanda.nohttp.rest.RequestQueue
import com.yolanda.nohttp.rest.Response

class BamjActivity : BaseActivityOaToolbarViewBinding<ActivityBamjBinding>() {

    private val mjList: MutableList<MjList.DataBean> = mutableListOf()
    private lateinit var adapter: BamjAdapter
    private lateinit var headView: View
    private lateinit var head: View
    private lateinit var tv_yjzj: TextView
    private lateinit var xj_cb: CheckBox
    private lateinit var dialog: WaitDialog
    private lateinit var queue: RequestQueue
    private lateinit var username: String

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

    override fun getToolbar() = binding.toolbarView.toolbar

    override fun initView() {
        initToolbar("保安免检管理", "提交", { finish() }, {
            if (NetworkUtil.hasNetWorkStatus(context, true)) {
                showLog("有wifi网络")
                if (mjList.size > 0) {
                    var isChecked = false
                    val mjCheckList: MutableList<MjList.DataBean> = mutableListOf()
                    for (i in mjList.indices) {
                        if (mjList[i].isChecked) {
                            isChecked = true
                            mjCheckList.add(mjList[i])
                        }
                    }
                    if (isChecked) {
                        val dialog = MjEditDialog(this, object : MjEditDialog.DialogListener {
                            override fun onYesClick(noCheckReason: String) {
                                if(!TextUtils.isEmpty(noCheckReason)){
                                    upLoadBaMj(noCheckReason,mjCheckList)
                                }else{
                                    showToast("免检原因必填")
                                }
                            }

                            override fun onNoClick() {

                            }

                        })
                        dialog.show()
                    } else {
                        showToast("请选择要免检的计划")
                    }
                }
            } else {
                showLog("无网络")
                showToast("无wifi网络连接，请先连接到wifi网络")
            }
        })
        queue = NoHttp.newRequestQueue(1)
        username = SPUtils.get(context, Contans.USERID, "") as String
        binding.lv.emptyView = binding.tvNodata
        dialog = WaitDialog(context, "上传数据中...请稍等...")
        dialog.setCancelable(false)
        headView = View.inflate(context, R.layout.scxscb_item, null)
        head = headView.findViewById(R.id.head)
        tv_yjzj = headView.findViewById(R.id.tv_yjzj)
        tv_yjzj.text = "总点数"
        xj_cb = headView.findViewById(R.id.xj_cb)
        binding.lv.addHeaderView(headView, null, false)
        xj_cb.setOnClickListener {
            if (xj_cb.isChecked) {
                for (i in mjList.indices) {
                    mjList[i].isChecked = true
                    adapter.notifyDataSetChanged()
                }
            } else {
                for (i in mjList.indices) {
                    mjList[i].isChecked = false
                    adapter.notifyDataSetChanged()
                }
            }
        }

        adapter = BamjAdapter(this, mjList) { view: View ->
            val checkBox = view as CheckBox
            val index = checkBox.tag as Int
            mjList[index].isChecked = checkBox.isChecked
            var count = 0
            for (a in mjList.indices) {
                if (mjList[a].isChecked) {
                    count++
                }
            }
            xj_cb.isChecked = count == mjList.size
            adapter.notifyDataSetChanged()
        }
        binding.lv.adapter = adapter
    }

    override fun initData() {
        if (NetworkUtil.hasNetWorkStatus(context, true)) {
            showLog("有wifi网络")
            requestData()
        } else {
            showLog("无网络")
        }
    }

    private fun requestData() {    //下载巡检数据
        val request: Request<String> =
            NoHttp.createStringRequest(Contans.IP + Contans.BA_Download_MJ_URL, RequestMethod.POST)
        request.setDefineRequestBodyForJson(createJsonBaMjDown())
        NoProgresshttpUtils.getInstance().add(this, 0, request, object : HttpListener<String?> {

            override fun onSucceed(what: Int, response: Response<String?>?) {
                showLog("----------------")
                val result = response?.get()
                showLog(result ?: "")
                val bean = GsonUtils.GsonToBean(result, MjList::class.java)
                if (bean.state == "1") {
                    if (bean.data != null && bean.data.size > 0) {
                        mjList.clear()
                        val list = bean.data //服务器数据
                        mjList.addAll(list)
                        adapter.notifyDataSetChanged()
                    }else{
                        mjList.clear()
                        adapter.notifyDataSetChanged()
                    }
                }else{
                    mjList.clear()
                    adapter.notifyDataSetChanged()
                }
            }

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

            }
        })
    }

    private fun upLoadBaMj(noCheckReason: String?,mjCheckList: MutableList<MjList.DataBean>) {
        val request: Request<String> =
            NoHttp.createStringRequest(Contans.IP + Contans.BA_UPLOAD_MJ_URL, RequestMethod.POST)
        request.setDefineRequestBodyForJson(createJsonBaMjUp(noCheckReason,mjCheckList))
        NoProgresshttpUtils.getInstance().add(this, 0, request, object : HttpListener<String?> {

            override fun onSucceed(what: Int, response: Response<String?>?) {
                showLog("----------------")
                val result = response?.get()
                showLog(result ?: "")
                val bean = GsonUtils.GsonToBean(result, MjList::class.java)
                if (bean.state == "1") {
                    showToast("操作成功")
                    initData()
                }
            }

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

            }
        })
    }

    private fun createJsonBaMjDown(): String {
        val info = XsRequestInfo()
        info.action = "BA_XJGL_BAKH_GET"
        val json = GsonUtils.GsonString(info)
        showLog(json)
        return json
    }

    private fun createJsonBaMjUp(noCheckReason: String?,mjCheckList: MutableList<MjList.DataBean>): String {
        val info = MjRequestInfo()
        info.action = "BA_XJGL_BAKHSC_SET"
        if (noCheckReason != null) {
            info.bz = noCheckReason
        } else {
            info.bz = ""
        }
        info.scr = username
        info.data = mjCheckList
        val json = GsonUtils.GsonString(info)
        showLog(json)
        return json
    }
}