package com.lukouguoji.mit.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.MitInPackListAdapter
import com.lukouguoji.mit.model.MitInPackListModel
import com.lukouguoji.mit.viewModel.MitInPackListViewModel
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_IN_PACK)
class MitInPackActivity : BaseActivity(), View.OnClickListener {
    private lateinit var viewModel: MitInPackListViewModel
    private lateinit var adapter: MitInPackListAdapter
    private val collectList = ArrayList<MitInPackListModel>()
    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 fdate: TextView
    private lateinit var startDateIcon: ImageView
    private lateinit var fno: EditText
    private lateinit var origin: EditText
    private lateinit var dest: 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(MitInPackListViewModel::class.java)

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

        refreshLayout = findViewById(R.id.refreshLayout)

        fdate = findViewById(R.id.fdate)
        startDateIcon = findViewById(R.id.startDateIcon)
        fno = findViewById(R.id.fno)
        origin = findViewById(R.id.origin)
        dest = findViewById(R.id.dest)
        searchLayout = findViewById(R.id.searchLayout)
        addIcon = findViewById(R.id.addIcon)
        quickSearch = findViewById(R.id.quickSearch)
        //列表
        listLayout = findViewById(R.id.listLayout)


        fdate.setOnClickListener(this)
        startDateIcon.setOnClickListener(this)
        searchLayout.setOnClickListener(this)
        addIcon.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.carId.contains(s.toString()) }
                    recyclerView.adapter = MitInPackListAdapter(
                        ActivityCollector.getLastActivity()!!,
                        viewModel,
                        filterCollectionList as MutableList<MitInPackListModel>
                    )
                } else {
                    recyclerView.adapter = MitInPackListAdapter(
                        ActivityCollector.getLastActivity()!!,
                        viewModel,
                        collectList
                    )
                }
                adapter.notifyDataSetChanged()
            }

            override fun afterTextChanged(s: Editable?) {

            }
        })

        fno.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) {

            }

            override fun afterTextChanged(editable: Editable?) {
                val originText = editable.toString()
                if (originText != null && originText != "") {
                    val regularExpression = "(^([A-Z0-9]+)$)"
                    val matches = originText.matches(regularExpression.toRegex())
                    if(!matches){
                        val regularExpression2 = "([^A-Za-z0-9]+)"
                        val replaceStr = originText.replace(regularExpression2.toRegex(),"")
                        val replaceStrToUpper = replaceStr.uppercase(Locale.ROOT)//小写转大写
                        fno.setText(replaceStrToUpper)
                        fno.setSelection(replaceStrToUpper.length)
                    }
                }
            }
        })

        fdate.text = ymdSdf.format(Date())//tw2022年6月13日15:57:10 要求航班日期默认当天
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_mit_in_pack)
        setBackArrow("进港卸机")
        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 fId = itemObj.getIntValue("fid")
                    val carId = itemObj.getString("carId") ?: ""//板车号
                    val flight = itemObj.getString("flight") ?: ""//航班
                    val countryType = itemObj.getString("countryType") ?: ""//地区类型
                    val opDate = itemObj.getString("opDate") ?: ""//装板时间
                    val opId = itemObj.getString("opId") ?: ""//确认人

                    //列表赋值
                    collectList.add(
                        MitInPackListModel(
                            fId,
                            carId,
                            flight,
                            countryType,
                            opDate,
                            opId
                        )
                    )
                }
                //3.调adpter展示
                if (currentPage == 1) {
                    val layoutManager = LinearLayoutManager(this)
                    adapter = MitInPackListAdapter(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()

            }

        }

        //航班返回结果
        viewModel.queryFlightObserver.observe(this) {
            loadingCancel()
            val status = it.getString("status")
            if (Constant.Result.succ == status) {
                var jsonObject = it.getJSONObject("data")
                viewModel.fid = jsonObject.getInteger("fid")
                viewModel.fdate = jsonObject.getString("fdate")
                viewModel.fno = jsonObject.getString("fno")
                viewModel.countryName = jsonObject.getString("countryName")
                viewModel.fdep = jsonObject.getString("fdep")
                viewModel.fdest = jsonObject.getString("fdest")

                origin.setText(viewModel.fdep)
                dest.setText(viewModel.fdest)

                if (viewModel.fid != null) {
                    listLayout.visibility = View.VISIBLE
                    loading()
                    resetSearch()
                }

            } else {
                //无数据
            }
        }

        //删除行 返回结果
        viewModel.deleteObserver.observe(this) {
            loadingCancel()
            val status = it.getString("status")
            val msg = it.getString("msg")
            if (Constant.Result.succ == status) {
                val dataStatus = it.getString("data")
                if (Constant.Result.succ == dataStatus) {
                    Common.showToast(this, "删除成功！")
                    resetSearch()
                } 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.fdate -> {
                    Common.onYearMonthDay(this, fdate.text.toString()) { year, month, day ->
                        calendar.set(year, month - 1, day)
                        fdate.text = ymdSdf.format(calendar.time)
                    }
                }
                R.id.startDateIcon -> {
                    fdate.text = ""
                }
                R.id.searchLayout -> {
                    origin.setText("")
                    dest.setText("")

                    viewModel.fid = null
                    viewModel.fdate = ""
                    viewModel.fno = ""
                    viewModel.countryName = ""
                    viewModel.fdep = ""
                    viewModel.fdest = ""

                    doFlight()
                }
                R.id.addIcon -> {
                    ARouter.getInstance().build(ARouterConstants.ACTIVITY_URL_MONITOR_IN_PACK_INFO).withInt("fid", viewModel.fid ?: -9999)
                        .withString("fdate", viewModel.fdate)
                        .withString("fno", viewModel.fno)
                        .withString("countryName", viewModel.countryName)
                        .withString("fdep", viewModel.fdep)
                        .withString("fdest", viewModel.fdest)
                        .navigation(this, Constant.RequestCode.gjj_cang_dan_list)
                }
                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.gjj_cang_dan_list && resultCode == RESULT_OK) {
            resetSearch()
        }
    }


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

        loading()
        viewModel.search(
            pageSize,
            currentPage,
            "",
            "",
            "",
            fdate.text.toString(),
            fno.text.toString(),
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            ""
        )
    }

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

    /**
     * 查询航班是否存在
     */
    private fun doFlight() {
        if (fdate.text.toString() == "" || fno.text.toString() == "") {
            Common.showToast(this, "航班日期和航班号不可为空！")
            return
        }
        loading()
        listLayout.visibility = View.GONE
        viewModel.queryFlight(fdate.text.toString(), fno.text.toString())
    }

}