package com.lukouguoji.gnj.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.lifecycle.viewModelScope
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.gnj.R
import com.lukouguoji.gnj.adapt.GnjChuKuListAdapter
import com.lukouguoji.gnj.model.GnjChuKuListModel
import com.lukouguoji.gnj.viewModel.GnjChuKuListViewModel
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 kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.*

@Route(path = ARouterConstants.ACTIVITY_URL_GNJ_CHU_KU_LIST)
class GnjChuKuListActivity : BaseActivity(), View.OnClickListener {
    private val currentTitleName = "国内进港出库"

    private lateinit var viewModel: GnjChuKuListViewModel
    private lateinit var adapter: GnjChuKuListAdapter
    private val collectList = ArrayList<GnjChuKuListModel>()
    private lateinit var refreshLayout: RefreshLayout
    private var currentPage = 1
    private var pageSize = 10
    private var totalPage = 0
    private var totalCount = 0  //总条数
    private var totalWeightValue = 0.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 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 wbNo: EditText
    private lateinit var pickNo: EditText
    private lateinit var scanIcon: ImageView
    private lateinit var wbScanIcon: ImageView
    private lateinit var searchLayout: LinearLayout
    private lateinit var checkIcon: ImageView
    private lateinit var quickSearch: EditText
    private var isAllCheck = true

    //筛选页
    private lateinit var searchListFragment: LinearLayout
    private lateinit var filtrateLayout: LinearLayout
    private lateinit var filtrateFragment: LinearLayout
    private lateinit var agentCode: TextView
    private var agentCodeValue = ""
    private lateinit var submit: TextView
    private lateinit var reset: TextView

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

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

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

        //标题
        toolBack = findViewById(R.id.tool_back)
        titleName = findViewById(R.id.title_name)

        beginDate = findViewById(R.id.beginDate)
        beginDateIcon = findViewById(R.id.beginDateIcon)
        endDate = findViewById(R.id.endDate)
        endDateIcon = findViewById(R.id.endDateIcon)
        wbNo = findViewById(R.id.wbNo)
        pickNo = findViewById(R.id.pickNo)
        scanIcon = findViewById(R.id.scanIcon)
        wbScanIcon = findViewById(R.id.wbScanIcon)

        searchLayout = findViewById(R.id.searchLayout)
        filtrateLayout = findViewById(R.id.filtrateLayout)
        checkIcon = findViewById(R.id.checkIcon)
        quickSearch = findViewById(R.id.quickSearch)

        //筛选页
        searchListFragment = findViewById(R.id.searchListFragment)
        filtrateFragment = findViewById(R.id.filtrateFragment)
        agentCode = findViewById(R.id.agentCode)
        submit = findViewById(R.id.submit)
        reset = findViewById(R.id.reset)

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

        toolBack.setOnClickListener(this)

        beginDate.setOnClickListener(this)
        beginDateIcon.setOnClickListener(this)
        endDate.setOnClickListener(this)
        endDateIcon.setOnClickListener(this)
        scanIcon.setOnClickListener(this)
        wbScanIcon.setOnClickListener(this)

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

        filtrateLayout.setOnClickListener(this)
        agentCode.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() != "" && s.length == 4) {
                    viewModel.queryWbNoGnjChuKu(s.toString())
                }
            }

            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()) }
                    recyclerView.adapter = GnjChuKuListAdapter(
                        ActivityCollector.getLastActivity()!!,
                        viewModel,
                        filterCollectionList as MutableList<GnjChuKuListModel>
                    )
                } else {
                    recyclerView.adapter = GnjChuKuListAdapter(
                        ActivityCollector.getLastActivity()!!,
                        viewModel,
                        collectList
                    )
                }
                adapter.notifyDataSetChanged()
            }

            override fun afterTextChanged(s: Editable?) {

            }
        })

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

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_gnj_chu_ku_list)
        setBackArrow("国内进港出库")
        initView()
//查询返回结果
        viewModel.searchParamLive.observe(this) {
            loadingCancel()
            //1.获取数据
            var listArr: JSONArray = it["list"] as JSONArray
            totalCount = it.getIntValue("total")
            totalWeightValue = it.getDoubleValue("totalWeight")
            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 id = itemObj.getIntValue("id")
                    val pkId = itemObj.getString("pkId") ?: ""
                    val no = itemObj.getString("wbNo") ?: ""
                    val fno = itemObj.getString("fno") ?: ""
                    val pc = itemObj.getIntValue("pc")
                    val weight = itemObj.getDoubleValue("weight")//实到重量

                    val goods = itemObj.getString("goods") ?: ""
                    val agentCode = itemObj.getString("agentCode") ?: ""
                    val spCode = itemObj.getString("spCode") ?: ""
                    val pickDate = itemObj.getString("chargeTime") ?: ""

                    //列表赋值
                    collectList.add(
                        GnjChuKuListModel(
                            id,
                            no,
                            pkId,
                            fno,
                            pc,
                            weight,
                            "9999-99-99",
                            goods,
                            agentCode,
                            spCode,
                            pickDate, false
                        )
                    )
                }
                //3.调adpter展示
                if (currentPage == 1) {
                    adapter.notifyDataSetChanged()
                } else {
                    adapter.notifyItemRangeInserted((currentPage - 1) * 10, collectList.size)
                }
                refreshLayout.finishRefresh()
                refreshLayout.finishLoadMore()

            }

            totalPc.text = totalCount.toString()
            totalWeight.text = totalWeightValue.toString()
            selPc.text = viewModel.checkCount.value.toString()
        }

//查询运单号四位返回结果
        viewModel.viewModelScope.launch {
            viewModel.queryWbNoGnjChuKuParamLive.collect {
                //1.获取数据
                if (it["status"] == Constant.Result.succ && it.getJSONArray("data").size > 0) {
                    val tempArr = JSONArray()
                    it.getJSONArray("data").forEach { wayNo ->
                        val tempObj = JSONObject()
                        tempObj["name"] = wayNo.toString()
                        tempObj["code"] = wayNo.toString()
                        tempArr.add(tempObj)
                    }

                    Common.singleSelect(ActivityCollector.getLastActivity()!!, "请选择运单号", tempArr, "") { _, item ->
                        val jsonObject = item as JSONObject
                        val name = jsonObject.getString("name")
                        val code = jsonObject.getString("code")
                        wbNo.setText(code)
                        resetSearch()
                    }
                }

            }

        }

        //根据id返回结果
        viewModel.queryPickByIdGnjChuKuObserver.observe(this) {
            loadingCancel()
            //1.获取数据
            var status = it.getString("status")
            if (status == Constant.Result.succ) {
                var itemObj = it.getJSONObject("data")
                val id = itemObj.getIntValue("id")
                val pkId = itemObj.getString("pkId") ?: ""
                val no = itemObj.getString("wbNo") ?: ""
                val fno = itemObj.getString("fno") ?: ""
                val pc = itemObj.getIntValue("pc")
                val weight = itemObj.getDoubleValue("weight")//实到重量

                val goods = itemObj.getString("goods") ?: ""
                val agentCode = itemObj.getString("agentCode") ?: ""
                val spCode = itemObj.getString("spCode") ?: ""
                val pickDate = itemObj.getString("chargeTime") ?: ""

                //列表赋值
                collectList.add(
                    GnjChuKuListModel(
                        id,
                        no,
                        pkId,
                        fno,
                        pc,
                        weight,
                        "9999-99-99",
                        goods,
                        agentCode,
                        spCode,
                        pickDate, false
                    )
                )

                //3.调adpter展示
                adapter.notifyDataSetChanged()
                refreshLayout.finishRefresh()
                refreshLayout.finishLoadMore()

                totalCount = 1
                viewModel.setCheckCount(0, 0.0)
                totalPc.text = totalCount.toString()
                totalWeight.text = totalWeightValue.toString()
                selPc.text = viewModel.checkCount.value.toString()
            }
        }

        //货物发放 返回结果
        viewModel.completedGnjChuKuObserver.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, "出库成功！")
                    }
                } 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, "出库失败！")
                }
            }
            //重新刷新列表
            resetSearch()
        }

        //监听 复选框选中
        viewModel.checkCount.observe(this) {
            selPc.text = it.toString()
        }
        //监听 复选框选中
        viewModel.checkCountWeight.observe(this) {
//            totalWeight.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
        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"))
        }
        ///////////////    下拉框   end
    }

    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.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.scanIcon -> {
                    scanCode(Constant.RequestCode.gnj_chu_ku_list)
                }
                R.id.wbScanIcon -> {
                    scanCode(Constant.RequestCode.gnj_chu_ku_waybill)
                }
                R.id.searchLayout -> {
//                    viewModel.queryPickByIdGnjChuKu("M000995643")
                    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
                    }
                }
                R.id.checkIcon -> {
                    collectList.forEach { c ->
                        c.isCheck = isAllCheck
                    }
                    if (isAllCheck) {
                        viewModel.setCheckCount(totalCount, totalWeightValue)
                    } else {
                        viewModel.setCheckCount(0, 0.0)
                    }
                    //重置 isAllCheck
                    isAllCheck = !isAllCheck
                    adapter.notifyDataSetChanged()
                }
                R.id.send -> {
                    val ids = collectList.filter { c -> c.isCheck }.map { c -> c.id }
                    viewModel.completedGnjChuKu(ids)
                }
                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.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()
                }
            }
        }
    }

    /**
     * 扫码返回的结果
     */
    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) {
                Constant.RequestCode.gnj_chu_ku_list -> {
                    collectList.clear()
                    pickNo.setText("$content")
                    viewModel.queryPickByIdGnjChuKu(content)
                }
                Constant.RequestCode.gnj_chu_ku_waybill -> {
                    wbNo.setText("$content")
                }
            }
        }
    }

    /**
     * 搜索
     */
    private fun searchFun() {
        loading()
        listLayout.visibility = View.GONE
        totalLayout.visibility = View.GONE
        viewModel.search(
            pageSize,
            currentPage,
            wbNo.text.toString(),
            agentCode.text.toString(),
            pickNo.text.toString(),
            //  startDate.text.toString(),
            // endDate.text.toString()
        )
    }

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

    /**
     * 重置筛选条件
     */
    private fun resetFun() {
        currentPage = 1
        //    startDate.text = "${ymdSdf.format(Date())} 00:00:00"
        //   endDate.text = "${ymdSdf.format(Date())} 23:59:59"
        wbNo.setText("")
        pickNo.setText("")

        agentCode.text = ""
        agentCodeValue = ""

    }

}