package com.lukouguoji.gjc.activity

import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
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.android.arouter.launcher.ARouter
import com.alibaba.fastjson.JSONArray
import com.alibaba.fastjson.JSONObject
import com.lukouguoji.gjc.R
import com.lukouguoji.gjc.adapt.GjcReceiveListAdapter
import com.lukouguoji.gjc.model.GjcReceive
import com.lukouguoji.gjc.viewModel.GjcReceiveListViewModel
import com.lukouguoji.module_base.BaseActivity
import com.lukouguoji.module_base.router.ARouterConstants
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.scwang.smart.refresh.header.ClassicsHeader
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.yzq.zxinglibrary.common.Constant
import java.util.*


@Route(path = ARouterConstants.ACTIVITY_URL_GJC_RECEIVE_LIST)
class GjcReceiveListActivity : BaseActivity() {
    private lateinit var adapter: GjcReceiveListAdapter
    private val collectList = ArrayList<GjcReceive>()

    private var currentPage = 1
    private var pageSize = 10
    private var totalPage = 0
    private var text = ""
    private lateinit var refreshLayout: RefreshLayout
    private lateinit var search: TextView
    private lateinit var wbNo: EditText
    private lateinit var wbNoScanIcon: ImageView

    //是否刷新
    private var refresh = false
    private lateinit var viewModel: GjcReceiveListViewModel


    private fun initView() {
        search = findViewById(R.id.search)
        wbNo = findViewById(R.id.wbNo)
        wbNoScanIcon = findViewById(R.id.wbNoScanIcon)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_gjc_receive_list)
        setBackArrow("国际出港待收运")
        initView()
        viewModel = ViewModelProvider(this).get(GjcReceiveListViewModel::class.java)


        val layoutManager = LinearLayoutManager(this)
        adapter = GjcReceiveListAdapter(this, collectList)
        var recyclerView: RecyclerView = findViewById(R.id.guo_nei_collect_list)
        recyclerView.layoutManager = layoutManager
        recyclerView.adapter = adapter

        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 mawbId = itemObj.getIntValue("maWbId")
                    val wbNo = itemObj.getString("wbNo") ?: ""
                    val pc = itemObj.getIntValue("pc")
                    val weight = itemObj.getDoubleValue("grossWeight")
                    val agentCode = itemObj.getString("agent") ?: ""
                    val spCode = itemObj.getString("spCode") ?: ""
                    val goods = itemObj.getString("goodsCn") ?: ""
                    val flight = itemObj.getString("flight") ?: ""
                    val businessType = itemObj.getString("businessType") ?: ""

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

            }
        }
        //初始化查询
        viewModel.search(pageSize, currentPage, text)
        loading()

        ///////////////////////////////   加载刷新的布局
        refreshLayout = findViewById<View>(R.id.refreshLayout) as RefreshLayout
        refreshLayout.setRefreshHeader(ClassicsHeader(this))
        refreshLayout.setRefreshFooter(ClassicsFooter(this))
        /////////////////////////////// 下拉刷新
        refreshLayout.setOnRefreshListener {
            refresh = true
            currentPage = 1
            //recyclerView 清除所有数据数据
            adapter.notifyItemRangeRemoved(0, collectList.size)
            collectList.clear()
            //初始化查询
            viewModel.search(pageSize, currentPage, text)
            adapter.notifyItemRangeInserted(0, collectList.size)
        }
        /////////////////////////////// 上拉加载
        refreshLayout.setOnLoadMoreListener {
            refresh = false
            if (currentPage < totalPage) {
                currentPage++
                //初始化查询
                viewModel.search(pageSize, currentPage, text)
            } else {
                refreshLayout.finishLoadMoreWithNoMoreData()
            }
        }

        search.setOnClickListener {
            currentPage = 1
            //recyclerView 清除所有数据数据
            adapter.notifyItemRangeRemoved(0, collectList.size)
            collectList.clear()
            //初始化查询
            viewModel.search(pageSize, currentPage, wbNo.text.toString())
        }


        //点击扫码
        wbNoScanIcon.setOnClickListener {
            scanCode(com.lukouguoji.module_base.common.Constant.RequestCode.gjc_shouyun_search)
        }

    }

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

        // 扫描二维码/条码回传
        if (requestCode == com.lukouguoji.module_base.common.Constant.RequestCode.gjc_shouyun_search) {
            if (data != null) {
                val content = data.getStringExtra(Constant.CODED_CONTENT)
                wbNo.setText("$content")

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

            }
        }

        if (requestCode == com.lukouguoji.module_base.common.Constant.RequestCode.gjc_shouyun_refresh && resultCode == RESULT_OK) {
            collectList.clear()
            currentPage = 1
            refreshLayout.setNoMoreData(false)
            viewModel.search(10, currentPage, "")
            loading()
        }
    }

}