package com.lukouguoji.gnc.activity

import android.content.Intent
import android.os.Bundle
import android.util.Log
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.gnc.R
import com.lukouguoji.gnc.adapt.GncChuKuListAdapter
import com.lukouguoji.module_base.BaseActivity

import com.lukouguoji.module_base.common.Constant
import com.lukouguoji.module_base.router.ARouterConstants
import com.lukouguoji.gnc.model.GncFuBangList
import com.lukouguoji.gnc.viewModel.GoutFuBangListViewModel
import com.lukouguoji.gnc.adapt.GncFuBangListAdapter
import com.lukouguoji.module_base.util.Common
import com.ninetripods.sydialoglib.IDialog
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.scwang.smart.refresh.header.ClassicsHeader
import com.scwang.smart.refresh.layout.api.RefreshLayout
import java.util.*
//出库装机操作页面
@Route(path = ARouterConstants.ACTIVITY_URL_GOUT_CHU_KU_LIST_ACTIVITY)
class GoutChuKuListActivity : BaseActivity() {
    public lateinit var viewModel: GoutFuBangListViewModel

    private lateinit var adapter: GncChuKuListAdapter
    private val collectList = ArrayList<GncFuBangList>()

    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 searchContent: EditText
    private lateinit var scanCodeImg: ImageView

    //是否刷新
    private var refresh = false


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

        search = findViewById(R.id.search)
        searchContent = findViewById(R.id.search_content)
        scanCodeImg = findViewById(R.id.scanCodeImg)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_fu_bang_list)
        setBackArrow("出库确认")
        initView()

        val layoutManager = LinearLayoutManager(this)
        adapter = GncChuKuListAdapter(this, collectList)
        var recyclerView: RecyclerView = findViewById(R.id.guo_nei_collect_list)
        recyclerView.layoutManager = layoutManager
        recyclerView.adapter = adapter
        viewModel.chukuParamLive.observe(this){
            loadingCancel();
        }
        viewModel.loadParamLive.observe(this){
            loadingCancel();
        }
        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 useId = itemObj.getIntValue("useId")
                    val carId = itemObj.getString("carId") ?: ""
                    val fno = itemObj.getString("fno") ?: ""
                    val dest = itemObj.getString("fdest") ?: ""
                    val totalWeight = itemObj.getDoubleValue("totalWeight")
                    val volume = itemObj.getDoubleValue("volume")
                    val pc = itemObj.getIntValue("pc")
                    val reviewer = itemObj.getString("reviewer") ?: ""
                    val opDate = itemObj.getString("opDate") ?: ""
                    val outer = itemObj.getString("outer") ?: ""
                    val loader = itemObj.getString("loader") ?: ""
                    collectList.add(GncFuBangList(useId, carId,fno,dest, totalWeight, volume, pc, opDate,reviewer,outer,loader))
                }
                //3.调adpter展示
                if (currentPage == 1) {
                    adapter.notifyDataSetChanged()
                } else {
                    adapter.notifyItemRangeInserted((currentPage - 1) * 10, collectList.size)
                }
                refreshLayout.finishRefresh()
                refreshLayout.finishLoadMore()

            }
        }
        //初始化查询
        viewModel.search(pageSize, currentPage, text,"2")
        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,"2")
            adapter.notifyItemRangeInserted(0, collectList.size)
        }
        /////////////////////////////// 上拉加载
        refreshLayout.setOnLoadMoreListener {
            refresh = false
            if (currentPage < totalPage) {
                currentPage++
                //初始化查询
                viewModel.search(pageSize, currentPage, text,"2")
            } else {
                refreshLayout.finishLoadMoreWithNoMoreData()
            }
        }

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


        //点击扫码
        scanCodeImg.setOnClickListener {
            scanCode(Constant.RequestCode.gnc_fubang_search)
        }
    }
    public  fun ChuKu(useId:Int,carId:String)
    {
        Common.secondConfirmDialog(this,"板车："+carId+"确定完成出库吗？")
             {dialog-> dialog.dismiss()
                viewModel.chuku(useId,carId)
                Common.showToastLong(this, carId+"出库成功！")
                currentPage = 1
                //recyclerView 清除所有数据数据
                adapter.notifyItemRangeRemoved(0, collectList.size)
                collectList.clear()
                //初始化查询
                viewModel.search(pageSize, currentPage, searchContent.text.toString(),"2")
            }
    }

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

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

                //调用接口查询进入详情页
                if (content != null && content != "") {
                    Log.i("刷新：${content}",content.toString())
                    ARouter.getInstance().build(ARouterConstants.ACTIVITY_URL_GOUT_FU_BANG_ACTIVITY).withString("carNoParam", content)
                        .navigation(this, Constant.RequestCode.gnc_shouyun_list_refresh)
                }

            }
        }

        if (requestCode == Constant.RequestCode.gnc_shouyun_list_refresh && resultCode == RESULT_OK) {
            collectList.clear()
            currentPage = 1
            refreshLayout.setNoMoreData(false)
            viewModel.search(10, currentPage, "","2")
            loading()
        }
    }
}