package com.lukouguoji.gnj.activity

import android.annotation.SuppressLint
import android.app.AlertDialog
import android.content.DialogInterface
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
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.fastjson.JSONArray
import com.alibaba.fastjson.JSONObject
import com.lukouguoji.gnj.R
import com.lukouguoji.gnj.adapt.GnjRuKuRefListAdapter
import com.lukouguoji.gnj.model.GnjRuKuRef
import com.lukouguoji.gnj.viewModel.GnjRuKuViewModel
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


@Route(path = ARouterConstants.ACTIVITY_URL_GNJ_RU_KU)
class GnjRuKuActivity : BaseActivity(), View.OnClickListener {
    private lateinit var viewModel: GnjRuKuViewModel
    private lateinit var refreshLayout: RefreshLayout
    private var currentPage = 1
    private var pageSize = 10
    private var totalPage = 0

    private lateinit var carNoScan: ImageView
    private lateinit var search: TextView
    private lateinit var searchContent: EditText
    private lateinit var addIcon: ImageView
    private lateinit var checkIcon: ImageView
    private var isAllCheck = false

    private var dialogWaybillNo: EditText? = null

    //关联运单号
    private lateinit var adapter: GnjRuKuRefListAdapter
    private lateinit var recyclerView: RecyclerView
    private lateinit var recyclerViewLayout: LinearLayout


    //确认
    private lateinit var operatorLayout: LinearLayout
    private lateinit var submit: TextView
    private lateinit var unloading: TextView

    private fun initView() {
//        carNo = findViewById(R.id.carNo)
        carNoScan = findViewById(R.id.carNoScan)
        searchContent = findViewById(R.id.search_content)
        search = findViewById(R.id.search)
        addIcon = findViewById(R.id.addIcon)
        checkIcon = findViewById(R.id.checkIcon)
        operatorLayout = findViewById(R.id.operatorLayout)
        submit = findViewById(R.id.submit)
        unloading = findViewById(R.id.unloading)
        //加载列表
        recyclerViewLayout = findViewById(R.id.gnc_transfer_list_layout)
        val layoutManager = LinearLayoutManager(this)
        adapter = GnjRuKuRefListAdapter(this, viewModel.gncTransferRefList)
        recyclerView = findViewById(R.id.gnc_transfer_waybill_list)
        recyclerView.layoutManager = layoutManager
        recyclerView.adapter = adapter
        refreshLayout = findViewById(R.id.refreshLayout)

        carNoScan.setOnClickListener(this)
        search.setOnClickListener(this)
        addIcon.setOnClickListener(this)
        checkIcon.setOnClickListener(this)
        submit.setOnClickListener(this)
        unloading.setOnClickListener(this)
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_gnj_ru_ku)
        setBackArrow("国内进港转运确认")
        viewModel = ViewModelProvider(this).get(GnjRuKuViewModel::class.java)
        initView()

        viewModel.searchGnjRuKuObserver.observe(this) {
            loadingCancel()
            refreshLayout.finishRefresh()
            refreshLayout.finishLoadMore()

            var listArr = JSONArray()
            try {
                listArr = it["list"] as JSONArray
            } catch (e: Exception) {
                return@observe
            }

            totalPage = it["pages"] as Int
            if (listArr.size > 0) {
                operatorLayout.visibility = View.VISIBLE
                viewModel.wbListArrFromNet = listArr

                //板车号
//                carNo.text = searchContent.text.toString()

                //加载关联运单列表
                viewModel.wbListArrFromNet.forEach { waybill ->
                    val waybillObj = waybill as JSONObject
                    viewModel.idsArray.add(waybillObj.getString("wbNo"))
                    val gncTransferRef = GnjRuKuRef(
                        waybillObj.getIntValue("mfId"), waybillObj.getString("wbNo") ?: "",
                        waybillObj.getIntValue("totalPc"), waybillObj.getIntValue("pc"),
                        waybillObj.getDoubleValue("weight"), waybillObj.getDoubleValue("cashWeight"),
                        waybillObj.getString("origin") ?: "", waybillObj.getString("dest") ?: "",
                        waybillObj.getString("agentCode") ?: "", waybillObj.getString("spCode") ?: "",
                        waybillObj.getString("goods") ?: "", waybillObj.getString("confirmDate") ?: "",
                        waybillObj.getString("confirmId") ?: "", false
                    )
                    viewModel.gncTransferRefList.add(gncTransferRef)
                }
                adapter.notifyDataSetChanged()
            }
            resetSelCount(false)
        }

        viewModel.loadCarGnjRuKuObserver.observe(this) {
            loadingCancel()
            val status = it.getString("status")
            val data = it.getString("data")
            if (Constant.Result.succ == status) {
                if (Constant.Result.succ == data) {
                    Common.alertDialog(this, "装车成功！") { dialog ->
                        dialog.dismiss()
                        resetSearch()
                    }
                } else {
                    Common.alertDialog(this, "装车失败！") { dialog ->
                        dialog.dismiss()
                    }
                }
            } else {
                Common.alertDialog(this, "装车失败！") { dialog ->
                    dialog.dismiss()
                }
            }
        }

        viewModel.unloadCarGnjRuKuObserver.observe(this) {
            loadingCancel()
            val status = it.getString("status")
            val data = it.getString("data")
            if (Constant.Result.succ == status) {
                if (Constant.Result.succ == data) {
                    Common.alertDialog(this, "卸车成功！") { dialog ->
                        dialog.dismiss()
                        resetSearch()
                    }
                } else {
                    Common.alertDialog(this, "卸车失败！") { dialog ->
                        dialog.dismiss()
                    }
                }
            } else {
                Common.alertDialog(this, "卸车失败！") { dialog ->
                    dialog.dismiss()
                }
            }
        }

        ///////////////////////////////   加载刷新的布局
        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 -> {
                    resetSearch()
                }
                R.id.carNoScan -> {
                    scanCode(Constant.RequestCode.gnj_ru_ku_car_no)
                }
//                R.id.fade -> {
//                    onYearMonthDayTime()
//                }
                R.id.addIcon -> {
                    if (searchContent.text.toString() == "") {
                        Common.showToast(this, "请先填写板车号！")
                        return
                    }

                    val builder: AlertDialog.Builder = AlertDialog.Builder(this)
                    builder.setTitle("请输入运单号")
                    // 通过LayoutInflater来加载一个xml的布局文件作为一个View对象
                    val view: View = LayoutInflater.from(this).inflate(
                        R.layout.gnj_ru_ku_waybill_dialog, null
                    )
                    // 设置我们自己定义的布局文件作为弹出框的Content
                    builder.setView(view)

                    dialogWaybillNo = view.findViewById(R.id.waybillNo)
                    dialogWaybillNo?.requestFocus()
                    val dialogCarNoScan: ImageView = view.findViewById(R.id.carNoScan)

                    dialogCarNoScan.setOnClickListener {
                        scanCode(Constant.RequestCode.gnj_ru_ku_waybill_no)
                    }

                    builder.setPositiveButton("确定",
                        DialogInterface.OnClickListener { dialog, which ->
                            //确定操作的内容
                            var inputWaybillNo = dialogWaybillNo?.text.toString()
                            if (inputWaybillNo == "") {
                                Common.showToast(this, "请输入运单号！")
                                return@OnClickListener
                            }
                            val tempRuKuRefList = arrayListOf<GnjRuKuRef>()
                            tempRuKuRefList.add(
                                GnjRuKuRef(
                                    -999, inputWaybillNo, 0, 0, 0.0, 0.0,
                                    "", "", "", "", "", "", "", true
                                )
                            )
                            //添加进idsArray里
                            if (viewModel.idsArray.contains(inputWaybillNo)) {
                                Common.showToast(this, "运单号重复，请重新输入！")
                                return@OnClickListener
                            }
                            viewModel.idsArray.add(inputWaybillNo)
                            //添加一条数据置顶端
                            tempRuKuRefList.addAll(viewModel.gncTransferRefList)
                            viewModel.gncTransferRefList.clear()
                            viewModel.gncTransferRefList.addAll(tempRuKuRefList)
                            adapter.notifyDataSetChanged()
                            operatorLayout.visibility = View.VISIBLE
                        })

                    builder.setNegativeButton("取消",
                        DialogInterface.OnClickListener { dialog, which ->

                        })
                    builder.show()
                }
                R.id.checkIcon -> {
                    //重置 isAllCheck
                    isAllCheck = !isAllCheck
                    resetSelCount(isAllCheck)
                }
                R.id.submit -> {
                    val ids = arrayListOf<String>()
                    viewModel.gncTransferRefList.forEach { tf ->
                        if(tf.isCheck){
                            ids.add(tf.wbNo)
                            if(tf.confirmDate != ""){
                                Common.showToast(this, "装车确认下有确认时间的运单不可选择！")
                                return@let
                            }
                        }
                    }
                    if (ids.isEmpty()) {
                        Common.showToast(this, "请至少选择一单！")
                        return
                    }
                    viewModel.idsArray.clear()
                    viewModel.idsArray.addAll(ids)
                    loading()
                    viewModel.loadCarGnjRuKu(searchContent.text.toString(), viewModel.idsArray)
                }
                R.id.unloading -> {
                    val ids = arrayListOf<String>()
                    viewModel.gncTransferRefList.forEach { tf ->
                        if(tf.isCheck){
                            ids.add(tf.wbNo)
                            if(tf.confirmDate == ""){
                                Common.showToast(this, "卸车确认下没有确认时间的运单不可选择！")
                                return@let
                            }
                        }
                    }
                    if (ids.isEmpty()) {
                        Common.showToast(this, "请至少选择一单！")
                        return
                    }
                    viewModel.idsArray.clear()
                    viewModel.idsArray.addAll(ids)
                    loading()
                    viewModel.unloadCarGnjRuKu(searchContent.text.toString(), viewModel.idsArray)
                }
                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_ru_ku_car_no -> {
                    searchContent.setText(content)
                    resetSearch()
                }
                Constant.RequestCode.gnj_ru_ku_waybill_no -> {
                    dialogWaybillNo?.setText(content)
                }
            }
        }
    }

    /**
     * 搜索
     */
    private fun searchFun() {
        if (searchContent.text.toString() == "") {
            Common.showToast(this, "平板车号不能为空！")
            refreshLayout.finishRefresh()
            refreshLayout.finishLoadMore()
            return
        }
        loading()
        operatorLayout.visibility = View.GONE
        viewModel.searchGnjRuKu(pageSize, currentPage, searchContent.text.toString())
    }

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

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