package com.lukouguoji.gjj.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 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.gjj.R
import com.lukouguoji.gjj.adapt.GjjQueryListAdapter
import com.lukouguoji.gjj.model.GjjQueryList
import com.lukouguoji.gjj.viewModel.GjjQueryListViewModel
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.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("旧版国际进港查询列表，使用 IntImpQueryActivity 替代")
//@Route(path = ARouterConstants.ACTIVITY_URL_GJJ_QUERY_LIST)
class GjjQueryListActivity : BaseActivity(), View.OnClickListener {
    private val currentTitleName = "国际进港查询"

    private lateinit var viewModel: GjjQueryListViewModel

    private lateinit var adapter: GjjQueryListAdapter
    private val collectList = ArrayList<GjjQueryList>()

    private var currentPage = 1
    private var pageSize = 10
    private var totalPage = 0
    private lateinit var refreshLayout: RefreshLayout

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

    //搜索条件
    private lateinit var beginDate: TextView
    private lateinit var beginDateIcon: ImageView
    private lateinit var endDate: TextView
    private lateinit var endDateIcon: ImageView
    private lateinit var searchListFragment: LinearLayout
    private lateinit var filtrateLayout: LinearLayout
    private lateinit var wbNo: EditText
    private lateinit var fno: EditText
    private lateinit var mudiGang: EditText
    private lateinit var searchLayout: LinearLayout

    //筛选页
    private lateinit var filtrateFragment: LinearLayout


    private lateinit var spCode: TextView
    private var spCodeValue = ""
    private lateinit var agentCode: TextView
    private var agentCodeValue = ""
    private lateinit var goods: EditText
    private lateinit var awbType: TextView
    private var awbTypeValue = ""
    private lateinit var businessType: TextView
    private var businessTypeValue = ""

    private lateinit var submit: TextView
    private lateinit var reset: TextView


    private val ymdSdf = SimpleDateFormat("yyyy-MM-dd")//年月日
    private val ymdHmsSdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")//年月日 时分秒
    private val calendar = Calendar.getInstance()

    private fun initView() {
        viewModel = ViewModelProvider(this).get(GjjQueryListViewModel::class.java)
        val layoutManager = LinearLayoutManager(this)
        adapter = GjjQueryListAdapter(this, collectList)
        var recyclerView: RecyclerView = findViewById(R.id.recyclerList)
        recyclerView.layoutManager = layoutManager
        recyclerView.adapter = adapter

        //标题
        toolBack = findViewById(R.id.tool_back)
        titleName = findViewById(R.id.title_name)
        //搜索列表页
        searchListFragment = findViewById(R.id.searchListFragment)
        wbNo = findViewById(R.id.wbNo)
        fno = findViewById(R.id.fno)
        beginDate = findViewById(R.id.beginDate)
        beginDateIcon = findViewById(R.id.beginDateIcon)
        endDate = findViewById(R.id.endDate)
        endDateIcon = findViewById(R.id.endDateIcon)
        mudiGang = findViewById(R.id.mudiGang)
        searchLayout = findViewById(R.id.searchLayout)
        filtrateLayout = findViewById(R.id.filtrateLayout)
        //筛选页
        filtrateFragment = findViewById(R.id.filtrateFragment)
        goods = findViewById(R.id.goods)
        spCode = findViewById(R.id.spCode)
        agentCode = findViewById(R.id.agentCode)
        businessType = findViewById(R.id.businessType)
        awbType = findViewById(R.id.awbType)
        submit = findViewById(R.id.submit)
        reset = findViewById(R.id.reset)

        toolBack.setOnClickListener(this)
        searchLayout.setOnClickListener(this)
        beginDate.setOnClickListener(this)
        beginDateIcon.setOnClickListener(this)
        endDate.setOnClickListener(this)
        endDateIcon.setOnClickListener(this)

        spCode.setOnClickListener(this)
        agentCode.setOnClickListener(this)
        businessType.setOnClickListener(this)
        awbType.setOnClickListener(this)
//        isCangDan.setOnClickListener(this)
        filtrateLayout.setOnClickListener(this)
        submit.setOnClickListener(this)
        reset.setOnClickListener(this)

        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) {
                    Common.alertDialog(ActivityCollector.getLastActivity()!!, "运单号不能超过11位！") { dialog ->
                        wbNo.setText(s.toString().substring(0, 11))
                        dialog.dismiss()
                    }
                }
            }

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

        mudiGang.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)//小写转大写
                        mudiGang.setText(replaceStrToUpper)
                        mudiGang.setSelection(replaceStrToUpper.length)
                    }
                }
            }
        })

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

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

        //初始化查询
        searchFun()
        loading()
        viewModel.searchParamLive.observe(this) {
            loadingCancel()
            //1.获取数据
            var listArr: JSONArray = it["list"] as JSONArray
            totalPage = it["pages"] as Int
//            var listArr :JSONArray =it["list"] as JSONArray
            if (listArr.size > 0) {
                //2.循环遍历塞入collectList
                listArr.forEach {
                    val itemObj = it as JSONObject
                    val id = itemObj.getIntValue("mawbid")
                    val wbNo = (itemObj.getString("prefix") ?: "") + (itemObj.getString("no") ?: "")
                    val agentCode = itemObj.getString("agent") ?: ""
                    val spCode = itemObj.getString("spCode") ?: ""
                    val goods = itemObj.getString("goods") ?: ""
                    val flight = itemObj.getString("flight") ?: ""
                    val range = itemObj.getString("range") ?: ""
                    val pc = itemObj.getString("pc") ?: ""
                    val weight = itemObj.getString("weight") ?: ""

                    collectList.add(GjjQueryList(id, wbNo, agentCode, spCode, goods, flight, range,pc,weight))
                }
                //3.调adpter展示
                if (currentPage == 1) {
                    adapter.notifyDataSetChanged()
                } else {
                    adapter.notifyItemRangeInserted((currentPage - 1) * 10, collectList.size)
                }
                refreshLayout.finishRefresh()
                refreshLayout.finishLoadMore()

            }
        }

        ///////////////    下拉框   start
        viewModel.agentCode(System.currentTimeMillis().toString())
        viewModel.agentCodeObserver.observe(this) { vd ->
            val noneObj = JSONObject()
            noneObj["name"] = "请选择代理人"
            noneObj["code"] = ""
            viewModel.agentCodeList.add(noneObj)
            viewModel.agentCodeList.addAll(vd.getJSONArray("data"))
        }

        viewModel.business(Constant.businessType.II)
        viewModel.businessObserver.observe(this) { vd ->
            val noneObj = JSONObject()
            noneObj["name"] = "请选择业务类型"
            noneObj["code"] = ""
            viewModel.businessList.add(noneObj)
            viewModel.businessList.addAll(vd.getJSONArray("data"))
        }

        viewModel.specialCode(System.currentTimeMillis().toString())
        viewModel.specialCodeObserver.observe(this) { vd ->
            val noneObj = JSONObject()
            noneObj["name"] = "请选择特码"
            noneObj["code"] = ""
            viewModel.specialCodeList.add(noneObj)
            viewModel.specialCodeList.addAll(vd.getJSONArray("data"))
        }

        viewModel.awb(Constant.businessType.II)
        viewModel.awbObserver.observe(this) { vd ->
            val noneObj = JSONObject()
            noneObj["name"] = "请选择运单类型"
            noneObj["code"] = ""
            viewModel.awbList.add(noneObj)
            viewModel.awbList.addAll(vd.getJSONArray("data"))
        }
        ///////////////    下拉框   end

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

        //点击扫码
        /*scanCodeImg.setOnClickListener {
            scanCode(Constant.RequestCode.gnc_query_list)
        }*/
    }

    /**
     * onActivityResult 回调
     */
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        // 扫描二维码/条码回传
        /*if (requestCode == Constant.RequestCode.gnc_query_list && resultCode == RESULT_OK) {
            if (data != null) {
                val content = data.getStringExtra(com.yzq.zxinglibrary.common.Constant.CODED_CONTENT)
                searchContent.setText("$content")

                //调用接口查询进入详情页
                if (content != null && content != "") {
                    ARouter.getInstance().build(ARouterConstants.ACTIVITY_URL_GNC_QUERY_INFO).withString("wbNoParam", content)
                        .navigation(this)
                }

            }
        }*/
    }

    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.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.beginDate -> {
                    Common.onYearMonthDay(this, beginDate.text.toString()) { year, month, day ->
                        calendar.set(year, month - 1, day)
                        beginDate.text = ymdSdf.format(calendar.time)
                    }
                }
                R.id.beginDateIcon -> {
                    beginDate.text = ""
                }
                R.id.endDate -> {
                    Common.onYearMonthDay(this, endDate.text.toString()) { year, month, day ->
                        calendar.set(year, month - 1, day)
                        endDate.text = ymdSdf.format(calendar.time)
                    }
                }
                R.id.endDateIcon -> {
                    endDate.text = ""
                }
                /* R.id.startDateParam -> {
                     Common.onYearMonthDayTime(this, startDateParam.text.toString()) { year, month, day, hour, minute, second ->
                         calendar.set(year, month - 1, day, hour, minute, second)
                         startDateParam.text = ymdHmsSdf.format(calendar.time)
                     }
                 }
                 R.id.endDateParam -> {
                     Common.onYearMonthDayTime(this, endDateParam.text.toString()) { year, month, day, hour, minute, second ->
                         calendar.set(year, month - 1, day, hour, minute, second)
                         endDateParam.text = ymdHmsSdf.format(calendar.time)
                     }
                 }*/
                R.id.agentCode -> {
                    Common.singleSelect(this, "代理", viewModel.agentCodeList, agentCodeValue) { _, item ->
                        val jsonObject = item as JSONObject
                        val name = jsonObject.getString("name")
                        val code = jsonObject.getString("code")
                        agentCode.text = name
                        agentCodeValue = code
                    }
                }
                R.id.businessType -> {
                    Common.singleSelect(this, "业务类型", viewModel.businessList, businessTypeValue) { _, item ->
                        val jsonObject = item as JSONObject
                        val name = jsonObject.getString("name")
                        val code = jsonObject.getString("code")
                        businessType.text = name
                        businessTypeValue = code
                    }
                }
                R.id.spCode -> {
                    Common.singleSelect(this, "特码", viewModel.specialCodeList, spCodeValue) { _, item ->
                        val jsonObject = item as JSONObject
                        val name = jsonObject.getString("name")
                        val code = jsonObject.getString("code")
                        spCode.text = name
                        spCodeValue = code
                    }
                }
                R.id.awbType -> {
                    Common.singleSelect(this, "运单类型", viewModel.awbList, awbTypeValue) { _, item ->
                        val jsonObject = item as JSONObject
                        val name = jsonObject.getString("name")
                        val code = jsonObject.getString("code")
                        awbType.text = name
                        awbTypeValue = 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()
                }
            }
        }
    }

    /**
     * 搜索
     */
    private fun searchFun() {
        viewModel.search(
            pageSize,
            currentPage,
            "", //            carrier.text.toString(),
            agentCodeValue,
            awbTypeValue,
            beginDate.text.toString(),// startDateParam.text.toString(),
            endDate.text.toString(),// endDateParam.text.toString(),
            "",
            fno.text.toString(),
            mudiGang.text.toString(),
            "",// kuWei.text.toString(),
            "",// hangCheng.text.toString(),
            businessTypeValue,
            "",// isCangDanStatus,
            wbNo.text.toString(),
            spCodeValue,
            goods.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("")
        mudiGang.setText("")

        beginDate.text = ""
        endDate.text = ""
        fno.setText("")

        spCode.text = ""
        spCodeValue = ""
        agentCode.text = ""
        agentCodeValue = ""
        goods.setText("")
        businessType.text = ""
        businessTypeValue = ""
        awbType.text = ""
        awbTypeValue = ""

    }
}