package com.lukouguoji.gnc.activity

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
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.android.arouter.launcher.ARouter
import com.alibaba.fastjson.JSONArray
import com.alibaba.fastjson.JSONObject
import com.lukouguoji.gnc.R
import com.lukouguoji.gnc.adapt.GncTransferListAdapter
import com.lukouguoji.gnc.model.GncTransferList
import com.lukouguoji.gnc.viewModel.GoutTransferViewModel
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.*

@Route(path = ARouterConstants.ACTIVITY_URL_GOUT_TRANSFER_ACTIVITY)
class GoutTransferActivity : BaseActivity(), View.OnClickListener {
    private lateinit var viewModel: GoutTransferViewModel

    private lateinit var adapter: GncTransferListAdapter
    private val collectList = ArrayList<GncTransferList>()

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

    private lateinit var fdate: TextView
    private lateinit var fdateIcon: ImageView
    private lateinit var fno: EditText
    private lateinit var location: EditText
    private lateinit var locationScan: ImageView
    private lateinit var search: LinearLayout


    private val ymdSdf = SimpleDateFormat("yyyy-MM-dd")//年月日
    private val calendar = Calendar.getInstance()

    private fun initView() {
        viewModel = ViewModelProvider(this).get(GoutTransferViewModel::class.java)
        //加载列表
        val layoutManager = LinearLayoutManager(this)
        adapter = GncTransferListAdapter(this, collectList)
        val recyclerView: RecyclerView = findViewById(R.id.recyclerList)
        recyclerView.layoutManager = layoutManager
        recyclerView.adapter = adapter

        locationScan = findViewById(R.id.locationScan)
        location = findViewById(R.id.location)
        fdate = findViewById(R.id.fdateParam)
        fdateIcon = findViewById(R.id.fdateIcon)
        fno = findViewById(R.id.fno)
        search = findViewById(R.id.search)


        fdate.setOnClickListener(this)
        fdateIcon.setOnClickListener(this)
        locationScan.setOnClickListener(this)
        search.setOnClickListener(this)

        fdate.text = ymdSdf.format(Date())
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_gout_transfer)
        setBackArrow("国内出港转运列表")
        viewModel = ViewModelProvider(this).get(GoutTransferViewModel::class.java)
        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("useId")
                    val carId = itemObj.getString("carId") ?: ""
                    val transId = itemObj.getString("transId") ?: ""// 确认人（如果此值不空，只能查看，也就是转运确定按钮隐藏）
                    val transDate = itemObj.getString("transDate") ?: ""//确认时间

                    collectList.add(GncTransferList(id, carId, transId, transDate))
                }
                //3.调adpter展示
                if (currentPage == 1) {
                    adapter.notifyDataSetChanged()
                } else {
                    adapter.notifyItemRangeInserted((currentPage - 1) * 10, collectList.size)
                }
                refreshLayout.finishRefresh()
                refreshLayout.finishLoadMore()

            }
        }

        ///////////////////////////////   加载刷新的布局
        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()
            }
        }
    }

    override fun onClick(v: View?) {
        v?.let {
            when (it.id) {
                R.id.search -> {
                    loading()
                    resetSearch()
                }
                R.id.fdateParam -> {
                    Common.onYearMonthDay(this, fdate.text.toString()) { year, month, day ->
                        calendar.set(year, month - 1, day)
                        fdate.text = ymdSdf.format(calendar.time)
                    }
                }
                R.id.fdateIcon -> {
                    fdate.text = ""
                }
                R.id.locationScan -> {
                    scanCode(Constant.RequestCode.gnc_transfer_car_no)
                }
                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 || content == "") {
                Common.showToast(this, "条码错误！")
                return
            }
            when (requestCode) {
                Constant.RequestCode.gnc_transfer_car_no -> {
                    ARouter.getInstance().build(ARouterConstants.ACTIVITY_URL_GOUT_TRANSFER_INFO_ACTIVITY)
                        .withString("carId", content)
                        .navigation()
                }
            }
        }
    }

    /**
     * 搜索
     */
    private fun searchFun() {
        viewModel.search(
            pageSize,
            currentPage,
            fdate.text.toString(),
            fno.text.toString(),
            location.text.toString()
        )
    }

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