package com.lukouguoji.mit.activity

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.widget.*
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.alibaba.fastjson.JSONArray
import com.alibaba.fastjson.JSONObject
import com.lukouguoji.mit.R
import com.lukouguoji.mit.adapt.AccidentVisaAdapter
import com.lukouguoji.mit.model.AccidentVisaModel
import com.lukouguoji.mit.viewModel.AccidentVisaViewModel
import com.lukouguoji.module_base.ActivityCollector
import com.lukouguoji.module_base.BaseActivity
import com.lukouguoji.module_base.common.Constant
import com.lukouguoji.module_base.router.ARouterConstants
import com.lukouguoji.module_base.util.Common
import com.lukouguoji.module_base.util.SwipeDeleteRecyclerView
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.scwang.smart.refresh.header.ClassicsHeader
import com.scwang.smart.refresh.layout.api.RefreshLayout
import java.text.SimpleDateFormat
import java.util.*

@Route(path = ARouterConstants.ACTIVITY_URL_MONITOR_ACCIDENT_VISA)
class AccidentVisaActivity : BaseActivity(), View.OnClickListener {
    private val currentTitleName = "事故签证"

    private lateinit var viewModel: AccidentVisaViewModel
    private lateinit var adapter: AccidentVisaAdapter
    private val collectList = ArrayList<AccidentVisaModel>()
    private lateinit var refreshLayout: RefreshLayout
    private var currentPage = 1
    private var pageSize = 10
    private var totalPage = 0
    private var totalCount = 0  //总条数
    private val calendar = Calendar.getInstance()
    private val ymdSdf = SimpleDateFormat("yyyy-MM-dd")//年月日
    private val ymdHmsSdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")//年月日 时分秒

    //标题
    private lateinit var toolBack: LinearLayout
    private lateinit var titleName: TextView

    //筛选页
    private lateinit var searchListFragment: LinearLayout
    private lateinit var filtrateFragment: LinearLayout
    private lateinit var filtrateLayout: LinearLayout
    private lateinit var submit: TextView
    private lateinit var reset: TextView


    //搜索
    private lateinit var beginDate: TextView
    private lateinit var endDate: TextView
    private lateinit var areaType: TextView
    private var areaTypeStatus = ""
    private val areaTypeArr = JSONArray()
    private lateinit var ieFlag: TextView
    private var ieFlagStatus = ""
    private val ieFlagArr = JSONArray()
    private lateinit var wbNo: EditText
    private lateinit var opId: EditText
    private lateinit var searchLayout: LinearLayout
    private lateinit var addIcon: ImageView
    private lateinit var quickSearch: EditText

    //列表
    private lateinit var listLayout: LinearLayout


    private fun initView() {
        viewModel = ViewModelProvider(this).get(AccidentVisaViewModel::class.java)

        val layoutManager = LinearLayoutManager(this)
        adapter = AccidentVisaAdapter(this, viewModel, collectList)
        var recyclerView: SwipeDeleteRecyclerView = findViewById(R.id.collectList)
        recyclerView.layoutManager = layoutManager
        recyclerView.adapter = adapter

        refreshLayout = findViewById(R.id.refreshLayout)

        //标题
        toolBack = findViewById(R.id.tool_back)
        titleName = findViewById(R.id.title_name)
        //筛选页
        searchListFragment = findViewById(R.id.searchListFragment)
        filtrateFragment = findViewById(R.id.filtrateFragment)
        filtrateLayout = findViewById(R.id.filtrateLayout)
        submit = findViewById(R.id.submit)
        reset = findViewById(R.id.reset)

        beginDate = findViewById(R.id.beginDate)
        endDate = findViewById(R.id.endDate)
        areaType = findViewById(R.id.areaType)
        ieFlag = findViewById(R.id.ieFlag)
        wbNo = findViewById(R.id.wbNo)
        opId = findViewById(R.id.opId)
        searchLayout = findViewById(R.id.searchLayout)
        addIcon = findViewById(R.id.addIcon)
        quickSearch = findViewById(R.id.quickSearch)
        //列表
        listLayout = findViewById(R.id.listLayout)


        toolBack.setOnClickListener(this)
        beginDate.setOnClickListener(this)
        endDate.setOnClickListener(this)
        areaType.setOnClickListener(this)
        ieFlag.setOnClickListener(this)
        searchLayout.setOnClickListener(this)
        filtrateLayout.setOnClickListener(this)
        addIcon.setOnClickListener(this)
        submit.setOnClickListener(this)
        reset.setOnClickListener(this)

        quickSearch.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                if (s != null && s.toString() != "") {
                    val filterCollectionList = collectList.filter { c -> c.wbNo.contains(s.toString()) }
                    recyclerView.adapter = AccidentVisaAdapter(
                        ActivityCollector.getLastActivity()!!,
                        viewModel,
                        filterCollectionList as MutableList<AccidentVisaModel>
                    )
                } else {
                    recyclerView.adapter = AccidentVisaAdapter(
                        ActivityCollector.getLastActivity()!!,
                        viewModel,
                        collectList
                    )
                }
                adapter.notifyDataSetChanged()
            }

            override fun afterTextChanged(s: Editable?) {

            }
        })

        wbNo.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                if (s != null && s.toString().length > 11) {
                    var wbNoStr = s.toString()
                    Common.showToast(ActivityCollector.getLastActivity() as Activity, "请输入正确的运单号格式！")
                    wbNoStr = wbNoStr.substring(0, 11)
                    wbNo.setText(wbNoStr)
                }
            }

            override fun afterTextChanged(s: Editable?) {

            }
        })


        var format = ymdSdf.format(Date())
        beginDate.text = "$format 00:00:00"
        endDate.text = "$format 23:59:59"

        val noneArea = JSONObject()
        noneArea["name"] = "请选择"
        noneArea["code"] = ""
        val guonei = JSONObject()
        guonei["name"] = "国内"
        guonei["code"] = "0"
        val guoji = JSONObject()
        guoji["name"] = "国际"
        guoji["code"] = "1"
        areaTypeArr.add(noneArea)
        areaTypeArr.add(guonei)
        areaTypeArr.add(guoji)

        val noneIeFlag = JSONObject()
        noneIeFlag["name"] = "请选择"
        noneIeFlag["code"] = ""
        val chu = JSONObject()
        chu["name"] = "出港"
        chu["code"] = "E"
        val jin = JSONObject()
        jin["name"] = "进港"
        jin["code"] = "I"
        ieFlagArr.add(noneIeFlag)
        ieFlagArr.add(chu)
        ieFlagArr.add(jin)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_accident_visa)
        initView()

        //查询返回结果
        viewModel.searchParamLive.observe(this) {
            loadingCancel()
            //1.获取数据
            var listArr: JSONArray = it["list"] as JSONArray
            totalCount = it.getIntValue("total")
            totalPage = it["pages"] as Int
//            var listArr :JSONArray =it["list"] as JSONArray
            if (listArr.size > 0) {
                listLayout.visibility = View.VISIBLE

                //2.循环遍历塞入collectList
                listArr.forEach {
                    val itemObj = it as JSONObject

                    val id = itemObj.getIntValue("id")
                    val wbNo = itemObj.getString("wbNo") ?: ""
                    val areaFlag = itemObj.getString("areaFlag") ?: ""
                    val ieFlag = itemObj.getString("ieFlag") ?: ""
                    val dpc = itemObj.getString("dpc") ?: ""//不正常件数
                    val opId = itemObj.getString("opId") ?: ""//操作人
                    val opDate = itemObj.getString("opDate") ?: ""//操作时间

                    //列表赋值
                    collectList.add(
                        AccidentVisaModel(
                            id,
                            wbNo,
                            areaFlag,
                            ieFlag,
                            dpc,
                            opId,
                            opDate
                        )
                    )
                }
                //3.调adpter展示
                if (currentPage == 1) {
                    val layoutManager = LinearLayoutManager(this)
                    adapter = AccidentVisaAdapter(this, viewModel, collectList)
                    var recyclerView: SwipeDeleteRecyclerView = findViewById(R.id.collectList)
                    recyclerView.layoutManager = layoutManager
                    recyclerView.adapter = adapter
                } else {
                    adapter.notifyItemRangeInserted((currentPage - 1) * 10, collectList.size)
                }
                refreshLayout.finishRefresh()
                refreshLayout.finishLoadMore()

            }

        }

        resetSearch()

        //删除行 返回结果
        viewModel.deleteLineObserver.observe(this) {
            loadingCancel()
            val positionDel = it.getInteger("positionDel")
            val status = it.getString("status")
            val msg = it.getString("msg")
            if (Constant.Result.succ == status) {
                collectList.removeAt(positionDel)
                adapter.notifyItemRemoved(positionDel)
                val dataStatus = it.getString("data")
                if (Constant.Result.succ == dataStatus) {
                    Common.showToast(this, "删除成功！")

                } else {
                    Common.showToast(this, "删除失败！")
                }
            } else {
                Common.showToast(this, "删除失败！")
            }
        }

        ///////////////////////////////   加载刷新的布局
        refreshLayout.setRefreshHeader(ClassicsHeader(this))
        refreshLayout.setRefreshFooter(ClassicsFooter(this))
        /////////////////////////////// 下拉刷新
        refreshLayout.setOnRefreshListener {
            resetSearch()
        }
        /////////////////////////////// 上拉加载
        refreshLayout.setOnLoadMoreListener {
            if (currentPage < totalPage) {
                currentPage++
                //初始化查询
                searchFun()
            } else {
                refreshLayout.finishLoadMoreWithNoMoreData()
            }
        }
    }

    override fun onClick(v: View?) {
        v?.let {
            when (it.id) {
                R.id.tool_back -> {
                    if (searchListFragment.visibility == View.GONE && filtrateFragment.visibility == View.VISIBLE) {
                        searchListFragment.visibility = View.VISIBLE
                        filtrateFragment.visibility = View.GONE
                        titleName.text = currentTitleName
                    } else {
                        finish()
                    }
                }
                R.id.beginDate -> {
                    Common.onYearMonthDayTime(this, beginDate.text.toString()) { year, month, day, hour, minute, second ->
                        calendar.set(year, month - 1, day, hour, minute, second)
                        beginDate.text = ymdHmsSdf.format(calendar.time)
                    }
                }
                R.id.endDate -> {
                    Common.onYearMonthDayTime(this, endDate.text.toString()) { year, month, day, hour, minute, second ->
                        calendar.set(year, month - 1, day, hour, minute, second)
                        endDate.text = ymdHmsSdf.format(calendar.time)
                    }
                }
                R.id.areaType -> {
                    Common.singleSelect(this, "地区类型", areaTypeArr, areaTypeStatus) { _, item ->
                        val jsonObject = item as JSONObject
                        val name = jsonObject.getString("name")
                        val code = jsonObject.getString("code")
                        areaType.text = name
                        areaTypeStatus = code
                    }
                }
                R.id.ieFlag -> {
                    Common.singleSelect(this, "进出港", ieFlagArr, ieFlagStatus) { _, item ->
                        val jsonObject = item as JSONObject
                        val name = jsonObject.getString("name")
                        val code = jsonObject.getString("code")
                        ieFlag.text = name
                        ieFlagStatus = code
                    }
                }
                R.id.searchLayout -> {
                    resetSearch()
                }
                R.id.filtrateLayout -> {
                    if (searchListFragment.visibility == View.VISIBLE && filtrateFragment.visibility == View.GONE) {
                        searchListFragment.visibility = View.GONE
                        filtrateFragment.visibility = View.VISIBLE
                        titleName.text = "搜索"
                    } else {
                        searchListFragment.visibility = View.VISIBLE
                        filtrateFragment.visibility = View.GONE
                        titleName.text = currentTitleName
                    }
//                    Common.showToast(this,"筛选")
                }
                R.id.addIcon -> {
                    ARouter.getInstance().build(ARouterConstants.ACTIVITY_URL_MONITOR_ACCIDENT_VISA_INFO)
                        .navigation(this, Constant.RequestCode.accident_visa_list_query_result)
                }
                R.id.submit -> {
                    //筛选页隐藏
                    searchListFragment.visibility = View.VISIBLE
                    filtrateFragment.visibility = View.GONE
                    titleName.text = currentTitleName
                    //搜索
                    resetSearch()
                }
                R.id.reset -> {
                    resetFun()
                }
                else -> {
                    Toast.makeText(this, "未找到对应操作", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    /**
     * onActivityResult 回调
     */
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == Constant.RequestCode.accident_visa_list_query_result && resultCode == RESULT_OK) {
            resetSearch()
        }
    }


    /**
     * 搜索
     */
    private fun searchFun() {

        loading()
        viewModel.search(
            pageSize,
            currentPage,
            beginDate.text.toString(),
            endDate.text.toString(),
            areaTypeStatus,
            ieFlagStatus,
            wbNo.text.toString(),
            opId.text.toString()
        )
    }

    /**
     * 重置数据，搜索
     */
    private fun resetSearch() {
        //recyclerView 清除所有数据数据
        refreshLayout.setNoMoreData(false)
        adapter.notifyItemRangeRemoved(0, collectList.size)
        collectList.clear()
        currentPage = 1
        searchFun()
    }

    /**
     * 重置筛选条件
     */
    private fun resetFun() {
        currentPage = 1

        wbNo.setText("")

        beginDate.text = ""
        endDate.text = ""
        areaType.text = ""
        areaTypeStatus = ""
        ieFlag.text = ""
        ieFlagStatus = ""

        wbNo.setText("")
        opId.setText("")
    }
}