package com.lukouguoji.hangban.activity

import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.fastjson.JSONArray
import com.alibaba.fastjson.JSONObject
import com.lukouguoji.hangban.R
import com.lukouguoji.hangban.adapt.HangBanListAdapter
import com.lukouguoji.hangban.model.HangBanListModel
import com.lukouguoji.hangban.viewModel.HangBanListViewModel
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.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.*


@Deprecated("旧版航班查询，使用 HbQueryListActivity 替代")
// @Route(path = ARouterConstants.ACTIVITY_URL_HANG_BAN_QUERY) // 已废弃，使用 HbQueryListActivity
class HangBanQueryActivity : BaseActivity(), View.OnClickListener {
    private val currentTitleName = "航班查询"

    private lateinit var viewModel: HangBanListViewModel
    private lateinit var adapter: HangBanListAdapter
    private val collectList = ArrayList<HangBanListModel>()
    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 startDate: TextView
    private lateinit var endDate: TextView
    private lateinit var fno: EditText
    private lateinit var flightType: TextView
    private var flightTypeValue = ""
    private lateinit var filtrateLayout: LinearLayout
    private lateinit var searchLayout: LinearLayout

    //筛选
    private lateinit var filtrateFragment: LinearLayout

    //    private lateinit var flight: EditText
    private lateinit var inOrOut: TextView
    private var inOrOutValue = ""
    private lateinit var countryType: TextView
    private var countryTypeValue = ""
    private lateinit var range1: EditText
    private lateinit var range2: EditText
    private lateinit var submit: TextView
    private lateinit var reset: TextView

    //列表
    private lateinit var listLayout: LinearLayout

    private fun initView() {
        viewModel = ViewModelProvider(this).get(HangBanListViewModel::class.java)
        val layoutManager = LinearLayoutManager(this)
        adapter = HangBanListAdapter(this, viewModel, collectList)
        var recyclerView: RecyclerView = 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)
        startDate = findViewById(R.id.startDate)
        startDate = findViewById(R.id.startDate)
        endDate = findViewById(R.id.startDate)
        fno = findViewById(R.id.fno)
        flightType = findViewById(R.id.flightType)
        filtrateLayout = findViewById(R.id.filtrateLayout)
        searchLayout = findViewById(R.id.searchLayout)

        //筛选
        filtrateFragment = findViewById(R.id.filtrateFragment)
//        flight = findViewById(R.id.flight)
        inOrOut = findViewById(R.id.inOrOut)
        countryType = findViewById(R.id.countryType)
        range1 = findViewById(R.id.range1)
        range2 = findViewById(R.id.range2)
        submit = findViewById(R.id.submit)
        reset = findViewById(R.id.reset)
        //列表
        listLayout = findViewById(R.id.listLayout)

        toolBack.setOnClickListener(this)
        startDate.setOnClickListener(this)
        endDate.setOnClickListener(this)
        flightType.setOnClickListener(this)

        filtrateLayout.setOnClickListener(this)
        searchLayout.setOnClickListener(this)

        inOrOut.setOnClickListener(this)
        countryType.setOnClickListener(this)
        submit.setOnClickListener(this)
        reset.setOnClickListener(this)

        startDate.text = ymdSdf.format(Date())
        endDate.text = ymdSdf.format(calendar.time)

        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)
                    }
                }
            }
        })

        range1.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-Z]+)$)"
                    val matches = originText.matches(regularExpression.toRegex())
                    if(!matches){
                        val regularExpression2 = "([^A-Za-z]+)"
                        val replaceStr = originText.replace(regularExpression2.toRegex(),"")
                        val replaceStrToUpper = replaceStr.uppercase(Locale.ROOT)//小写转大写
                        range1.setText(replaceStrToUpper)
                        range1.setSelection(replaceStrToUpper.length)
                    }
                }
            }
        })

        range2.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-Z]+)$)"
                    val matches = originText.matches(regularExpression.toRegex())
                    if(!matches){
                        val regularExpression2 = "([^A-Za-z]+)"
                        val replaceStr = originText.replace(regularExpression2.toRegex(),"")
                        val replaceStrToUpper = replaceStr.uppercase(Locale.ROOT)//小写转大写
                        range2.setText(replaceStrToUpper)
                        range2.setSelection(replaceStrToUpper.length)
                    }
                }
            }
        })
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_hangban_query)
        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("fid")
                    val fdate = itemObj.getString("fdate") ?: ""
                    val fno = itemObj.getString("fno") ?: ""
                    val range = itemObj.getString("range") ?: ""
                    val jtz = itemObj.getString("jtz") ?: ""
                    val scheduledArrival = itemObj.getString("scheduledArrival") ?: ""
                    val estimatedArrival = itemObj.getString("estimatedArrival") ?: ""
                    val actualArrival = itemObj.getString("actualArrival") ?: ""
                    val scheduledTackOff = itemObj.getString("scheduledTackOff") ?: ""
                    val estimatedTakeOff = itemObj.getString("estimatedTakeOff") ?: ""
                    val actualTakeOff = itemObj.getString("actualTakeOff") ?: ""
                    val countryType = itemObj.getString("countryType") ?: ""
                    val serviceType = itemObj.getString("serviceType") ?: ""
                    val flightStatus = itemObj.getString("flightStatus") ?: ""
                    val delayFreeText = itemObj.getString("delayFreeText") ?: ""
                    val aircraftCode = itemObj.getString("aircraftCode") ?: ""
                    val standId = itemObj.getString("standId") ?: ""
                    val registration = itemObj.getString("registration") ?: "" //机号
                    val status = itemObj.getString("status") ?: "0"

                    //列表赋值
                    collectList.add(
                        HangBanListModel(
                            id,
                            fdate,
                            fno,
                            range,
                            jtz,
                            scheduledArrival,
                            estimatedArrival,
                            actualArrival,
                            scheduledTackOff, estimatedTakeOff,
                            actualTakeOff,
                            countryType,
                            serviceType,
                            flightStatus,
                            delayFreeText,
                            aircraftCode,
                            registration,
                            status
                        )
                    )
                }
                //3.调adpter展示
                if (currentPage == 1) {
                    adapter.notifyDataSetChanged()
                } else {
                    adapter.notifyItemRangeInserted((currentPage - 1) * 10, collectList.size)
                }
                refreshLayout.finishRefresh()
                refreshLayout.finishLoadMore()

            }

        }

        ///////////////    下拉框   start
        viewModel.flightType(System.currentTimeMillis().toString())
        viewModel.flightTypeObserver.observe(this) { vd ->
            val noneObj = JSONObject()
            noneObj["name"] = "请选择航班类型"
            noneObj["code"] = ""
            viewModel.flightTypeList.add(noneObj)
            viewModel.flightTypeList.addAll(vd.getJSONArray("data"))
        }
        viewModel.initInOrOutList()
        viewModel.countryType(System.currentTimeMillis().toString())
        viewModel.countryTypeObserver.observe(this) { vd ->
            val noneObj = JSONObject()
            noneObj["name"] = "请选择地区类型"
            noneObj["code"] = ""
            viewModel.countryTypeList.add(noneObj)
            viewModel.countryTypeList.addAll(vd.getJSONArray("data"))
        }
        ///////////////    下拉框   end


        //搜索
        resetSearch()

        ///////////////////////////////   加载刷新的布局
        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 {
                        setResult(RESULT_OK)
                        finish()
                    }
                }
                R.id.startDate -> {
                    Common.onYearMonthDay(this, startDate.text.toString()) { year, month, day ->
                        calendar.set(year, month - 1, day)
                        startDate.text = ymdSdf.format(calendar.time)
                    }
                }
                R.id.startDate -> {
                    Common.onYearMonthDay(this, endDate.text.toString()) { year, month, day ->
                        calendar.set(year, month - 1, day)
                        endDate.text = ymdSdf.format(calendar.time)
                    }
                }
                R.id.flightType -> {
                    Common.singleSelect(this, "航班类型", viewModel.flightTypeList, flightTypeValue) { _, item ->
                        val jsonObject = item as JSONObject
                        val name = jsonObject.getString("name")
                        val code = jsonObject.getString("code")
                        flightType.text = name
                        flightTypeValue = code
                    }
                }
                R.id.searchLayout -> {
//                    viewModel.queryPickByIdGnjChuKu("M000995643")
                    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.inOrOut -> {
                    Common.singleSelect(this, "进出港", viewModel.inOrOutList, inOrOutValue) { _, item ->
                        val jsonObject = item as JSONObject
                        val name = jsonObject.getString("name")
                        val code = jsonObject.getString("code")
                        inOrOut.text = name
                        inOrOutValue = code
                    }
                }
                R.id.countryType -> {
                    Common.singleSelect(this, "地区类型", viewModel.countryTypeList, countryTypeValue) { _, item ->
                        val jsonObject = item as JSONObject
                        val name = jsonObject.getString("name")
                        val code = jsonObject.getString("code")
                        countryType.text = name
                        countryTypeValue = code
                    }
                }
                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()
                }
            }
        }
    }

    /**
     * 扫码返回的结果
     */
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        // 扫描二维码/条码回传
        if (resultCode == RESULT_OK && data != null) {
            val content = data.getStringExtra(com.yzq.zxinglibrary.common.Constant.CODED_CONTENT)
            if (content == null) {
                Common.showToast(this, "条码错误！")
                return
            }
            when (requestCode) {
                Constant.RequestCode.gnj_chu_ku_list -> {

                }
            }
        }
    }

    /**
     * 搜索
     */
    private fun searchFun() {
        loading()
        listLayout.visibility = View.GONE
        var range = ""
        if (range1.text.toString() != "" && range2.text.toString() != "") {
            range = "${range1.text}-${range2.text}"
        } else if (range1.text.toString() != "" && range2.text.toString() == "") {
            range = "${range1.text}"
        } else if (range1.text.toString() == "" && range2.text.toString() != "") {
            range = "${range2.text}"
        } else {
            range = ""
        }

        viewModel.search(
            pageSize,
            currentPage,
            startDate.text.toString(),
            endDate.text.toString(),
            countryTypeValue,
            "",//flight.text.toString(),
            flightTypeValue,
            fno.text.toString(),
            range,
            inOrOutValue
        )
    }

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

    /**
     * 重置筛选条件
     */
    private fun resetFun() {
        currentPage = 1
        val format = ymdSdf.format(Date())
        startDate.text = format
        endDate.text = ymdSdf.format(calendar.time)
        fno.setText("")
        flightType.text = ""
        flightTypeValue = ""
        //flight.setText("")
        inOrOut.text = ""
        inOrOutValue = ""
        countryType.text = ""
        countryTypeValue = ""
        range1.setText("")
        range2.setText("")
    }
}