package com.lukouguoji.mit.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.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.fastjson.JSONArray
import com.alibaba.fastjson.JSONObject
import com.lukouguoji.mit.R
import com.lukouguoji.mit.adapt.OutLoadingPullAdapter
import com.lukouguoji.mit.model.OutLoadingPullModel
import com.lukouguoji.mit.viewModel.OutLoadingPullViewModel
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.*

@Route(path = ARouterConstants.ACTIVITY_URL_MONITOR_OUT_LOADING_PULL)
class OutLoadingPullActivity : BaseActivity(), View.OnClickListener {
    private lateinit var viewModel: OutLoadingPullViewModel
    private lateinit var adapter: OutLoadingPullAdapter
    private val collectList = ArrayList<OutLoadingPullModel>()
    private var collectListFromNet = ArrayList<OutLoadingPullModel>()
    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 fdate: TextView
    private lateinit var fno: EditText
    private lateinit var carNo: AutoCompleteTextView
    private lateinit var carListPop: ListPopupWindow

    private lateinit var searchLayout: LinearLayout
    private lateinit var checkIcon: ImageView
    private lateinit var quickSearch: EditText
    private var isAllCheck = false

    //列表
    private lateinit var listLayout: LinearLayout
    private lateinit var totalLayout: LinearLayout

    //底部
    private lateinit var totalPc: TextView
    private lateinit var selPc: TextView
    private lateinit var send: TextView

    @JvmField
    @Autowired
    var fidParam: Int = -9999

    @JvmField
    @Autowired
    var fnoParam: String = ""

    @JvmField
    @Autowired
    var fdateParam: String = ""

    @JvmField
    @Autowired
    var carsParam: String = ""

    private fun initView() {
        viewModel = ViewModelProvider(this).get(OutLoadingPullViewModel::class.java)
        val layoutManager = LinearLayoutManager(this)
        adapter = OutLoadingPullAdapter(this, viewModel, collectList)
        var recyclerView: RecyclerView = findViewById(R.id.collectList)
        recyclerView.layoutManager = layoutManager
        recyclerView.adapter = adapter
        refreshLayout = findViewById(R.id.refreshLayout)
        //搜索框
        fdate = findViewById(R.id.fdate)
        fno = findViewById(R.id.fno)
        carNo = findViewById(R.id.carNo)
        val split = carsParam.split(",")

        carNo.setAdapter(ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, split))

        //快捷搜索
        searchLayout = findViewById(R.id.searchLayout)
        checkIcon = findViewById(R.id.checkIcon)
        quickSearch = findViewById(R.id.quickSearch)

        //cars的下拉框初始化
        /*carListPop = ListPopupWindow(this)
        carListPop.setAdapter(ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, split))
        carListPop.setWidth(ActionBar.LayoutParams.WRAP_CONTENT)
        carListPop.setHeight(ActionBar.LayoutParams.WRAP_CONTENT)
        carListPop.setAnchorView(carNo) //设置ListPopupWindow的锚点，即关联PopupWindow的显示位置和这个锚点
        carListPop.setModal(true) //设置是否是模式
        carListPop.setOnItemClickListener { _, _, position, _ ->
            carNo.setText(split[position])
            carListPop.dismiss()
        }*/

        //列表
        listLayout = findViewById(R.id.listLayout)
        totalLayout = findViewById(R.id.totalLayout)
        //底部
        totalPc = findViewById(R.id.totalPc)
        selPc = findViewById(R.id.selPc)
        send = findViewById(R.id.send)

        searchLayout.setOnClickListener(this)
        checkIcon.setOnClickListener(this)
        send.setOnClickListener(this)

        /*carNo.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() != "") {
                    val filterCollectionList = split.filter { c -> c.contains(s.toString()) }
                    if (filterCollectionList.isNotEmpty()) {
                        carListPop.setAdapter(
                            ArrayAdapter<String>(
                                ActivityCollector.getLastActivity()!!,
                                android.R.layout.simple_list_item_1,
                                filterCollectionList
                            )
                        )
                        carListPop.setOnItemClickListener { _, _, position, _ ->
                            carNo.setText(filterCollectionList[position])
                            carListPop.dismiss()
                        }
                        carListPop.show()
                    }
                } else {
                    if (split.isNotEmpty()) {
                        carListPop.setAdapter(
                            ArrayAdapter<String>(
                                ActivityCollector.getLastActivity()!!,
                                android.R.layout.simple_list_item_1,
                                split
                            )
                        )
                        carListPop.setOnItemClickListener { _, _, position, _ ->
                            carNo.setText(split[position])
                            carListPop.dismiss()
                        }
                        carListPop.show()
                    }
                }
                carNo.isFocusable = true
                carNo.requestFocus()
                carNo.setSelection(carNo.getText().length);
            }

            override fun afterTextChanged(s: Editable?) {

            }
        })*/

        quickSearch.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() != "") {
                    val filterCollectionList = collectList.filter { c -> c.wbNo.contains(s.toString()) }
                    collectList.clear()
                    collectList.addAll(filterCollectionList)
                    recyclerView.adapter = OutLoadingPullAdapter(
                        ActivityCollector.getLastActivity()!!,
                        viewModel,
                        collectList
                    )
                } else {
                    collectList.clear()
                    collectList.addAll(collectListFromNet)
                    recyclerView.adapter = OutLoadingPullAdapter(
                        ActivityCollector.getLastActivity()!!,
                        viewModel,
                        collectList
                    )
                }
                val checkList = collectList.filter { c -> c.isCheck }
                viewModel.setCheckCount(checkList.size)
                adapter.notifyDataSetChanged()
            }

            override fun afterTextChanged(s: Editable?) {

            }
        })

        fdate.text = fdateParam
        fno.setText(fnoParam)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_out_loading_pull)
        setBackArrow("出港装机拉货")
        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
                totalLayout.visibility = View.VISIBLE
                //2.循环遍历塞入collectList
                listArr.forEach {
                    val itemObj = it as JSONObject

                    val mfId = itemObj.getIntValue("mfId")
                    val whId = itemObj.getIntValue("whId")
                    val no = itemObj.getString("wbNo") ?: ""
                    val pc = itemObj.getIntValue("pc")
                    val weight = itemObj.getDoubleValue("weight")//实到重量
                    val volume = itemObj.getDoubleValue("volume")
                    val location = itemObj.getString("location") ?: ""

                    //列表赋值
                    collectList.add(
                        OutLoadingPullModel(
                            no,
                            mfId,
                            whId,
                            pc,
                            weight,
                            volume,
                            location,
                            false
                        )
                    )
                }
                collectListFromNet.clear()
                collectListFromNet = collectList.clone() as ArrayList<OutLoadingPullModel>

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

            }

            totalPc.text = totalCount.toString()
            resetSelCount(false, totalCount)
        }

        //货物发放 返回结果
        viewModel.completedObserver.observe(this) {
            loadingCancel()
            val status = it.getString("status")
            val msg = it.getString("msg")
            if (Constant.Result.succ == status) {
                var dataStatus = it.getString("data")
                if (Constant.Result.succ == dataStatus) {
                    if (msg != null && msg != "") {
                        Common.showToast(this, msg)
                    } else {
                        Common.showToast(this, "拉货成功！")
                    }
                    //重新刷新列表
                    resetSearch()
                } else {
                    if (msg != null && msg != "") {
                        Common.showToast(this, msg)
                    } else {
                        Common.showToast(this, "拉货失败！")
                    }
                }
            } else {
                if (msg != null && msg != "") {
                    Common.showToast(this, msg)
                } else {
                    Common.showToast(this, "拉货失败！")
                }
            }
        }

        //监听 复选框选中
        viewModel.checkCount.observe(this) {
            selPc.text = it.toString()
        }

        //搜索
        resetSearch()

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

        ///////////////    下拉框   start

        ///////////////    下拉框   end
    }

    override fun onClick(v: View?) {
        v?.let {
            when (it.id) {
                R.id.searchLayout -> {
//                    viewModel.queryPickByIdGnjChuKu("M000995643")
                    resetSearch()
                }
                R.id.checkIcon -> {
                    //重置 isAllCheck
                    isAllCheck = !isAllCheck
                    resetSelCount(isAllCheck, totalCount)
                }
                R.id.send -> {
                    val paramArr = JSONArray()
                    collectList.forEach { c ->
                        if (c.isCheck) {
                            val paramObj = JSONObject()
                            paramObj["fid"] = fidParam
                            paramObj["mfId"] = c.mfId
                            paramObj["weight"] = c.weight
                            paramObj["pc"] = c.pc
                            paramObj["whId"] = c.whId
                            paramArr.add(paramObj)
                        }
                    }
                    if (paramArr.size > 0) {
                        viewModel.completed(paramArr)
                    } else {
                        Common.alertDialog(this, "请至少选择一票货物！") { dialog ->
                            dialog.dismiss()
                        }
                    }
                }
                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) {
            }
        }
    }

    /**
     * 搜索
     */
    private fun searchFun() {
        loading()
        listLayout.visibility = View.GONE
        totalLayout.visibility = View.GONE
        viewModel.search(
            pageSize,
            currentPage,
            fidParam,
            carNo.text.toString()
        )
    }

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

    /**
     * 重新计算选中数量
     * isAllCheckParam  true：全选  false:全部全效选择
     */
    private fun resetSelCount(isAllCheckParam: Boolean, totalCount: Int) {
        collectList.forEach { c ->
            c.isCheck = isAllCheckParam
        }
        if (isAllCheckParam) {
            viewModel.setCheckCount(totalCount)
        } else {
            viewModel.setCheckCount(0)
        }
        adapter.notifyDataSetChanged()
    }
}