package com.lukouguoji.gnj.fragment

import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.fastjson.JSONArray
import com.alibaba.fastjson.JSONObject
import com.lukouguoji.gnj.R
import com.lukouguoji.gnj.activity.GnjYiKuListActivity
import com.lukouguoji.gnj.adapt.GnjYiKuListAdapter
import com.lukouguoji.gnj.model.GnjYiKuListModel
import com.lukouguoji.gnj.viewModel.GnjYiKuListViewModel
import com.lukouguoji.module_base.ActivityCollector
import com.lukouguoji.module_base.common.Constant
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.util.*
import kotlin.collections.ArrayList


class GnjYiKuFragment : Fragment(), View.OnClickListener {
    private lateinit var yiKuActivity: GnjYiKuListActivity
    private lateinit var viewModel: GnjYiKuListViewModel
    private lateinit var adapter: GnjYiKuListAdapter
    private val collectList = ArrayList<GnjYiKuListModel>()
    private lateinit var refreshLayout: RefreshLayout
    private var currentPage = 1
    private var pageSize = 10
    private var totalPage = 0
    private var totalCount = 0  //总条数

    //搜索
    private lateinit var awbType: TextView
    private var awbTypeValue = ""
    private lateinit var wbNo: EditText
    private lateinit var carrier: EditText

    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

    private fun initView() {
        yiKuActivity = activity!! as GnjYiKuListActivity

        viewModel = ViewModelProvider(this).get(GnjYiKuListViewModel::class.java)
        val layoutManager = LinearLayoutManager(yiKuActivity)
        adapter = GnjYiKuListAdapter(yiKuActivity, viewModel, collectList)
        var recyclerView: RecyclerView = yiKuActivity.findViewById(R.id.collectList)
        recyclerView.layoutManager = layoutManager
        recyclerView.adapter = adapter
        refreshLayout = yiKuActivity.findViewById(R.id.refreshLayout)

        awbType = yiKuActivity.findViewById(R.id.awbType)
        wbNo = yiKuActivity.findViewById(R.id.wbNo)
        carrier = yiKuActivity.findViewById(R.id.carrier)

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

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

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

            override fun afterTextChanged(s: Editable?) {

            }
        })

        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().length > 11) {
                    Common.alertDialog(ActivityCollector.getLastActivity()!!, "运单号不能超过11位！") { dialog ->
                        wbNo.setText(s.toString().substring(0, 11))
                        dialog.dismiss()
                    }
                }
            }

            override fun afterTextChanged(s: Editable?) {

            }
        })

        carrier.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) {

            }

            override fun afterTextChanged(editable: Editable?) {
                val originText = editable.toString()
                if (originText != null && originText != "") {
                    val regularExpression = "(^([A-Z]+)$)"
                    val matches = originText.matches(regularExpression.toRegex())
                    if(!matches){
                        val regularExpression2 = "([^A-Za-z]+)"
                        val replaceStr = originText.replace(regularExpression2.toRegex(),"")
                        val replaceStrToUpper = replaceStr.uppercase(Locale.ROOT)//小写转大写
                        carrier.setText(replaceStrToUpper)
                        carrier.setSelection(replaceStrToUpper.length)
                    }
                }
            }
        })
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_gnj_yi_ku, container, false)
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        initView()
        yiKuActivity.setBackArrow("国内进港移库")
//查询返回结果
        viewModel.searchParamLive.observe(yiKuActivity) {
            yiKuActivity.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 id = itemObj.getIntValue("mawbId")
                    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") ?: ""
                    val origin = itemObj.getString("origin") ?: ""
                    val dest = itemObj.getString("dest") ?: ""
                    val awbType = itemObj.getString("awbType") ?: ""

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

            }

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

        //确认移库 返回结果
        viewModel.moveGnjYiKuObserver.observe(yiKuActivity) {
            yiKuActivity.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(yiKuActivity, msg)
                    } else {
                        Common.showToast(yiKuActivity, "移库成功！")
                    }
                } else {
                    if (msg != null && msg != "") {
                        Common.showToast(yiKuActivity, msg)
                    } else {
                        Common.showToast(yiKuActivity, "移库失败！")
                    }
                }
            } else {
                if (msg != null && msg != "") {
                    Common.showToast(yiKuActivity, msg)
                } else {
                    Common.showToast(yiKuActivity, "移库失败！")
                }
            }
            //重新搜索
            resetSearch()
        }

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

        //搜索
        resetSearch()

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

        ///////////////    下拉框   start
        viewModel.awb(System.currentTimeMillis().toString())
        viewModel.awbObserver.observe(yiKuActivity) { vd ->
            val noneObj = JSONObject()
            noneObj["name"] = "请选择运单类型"
            noneObj["code"] = ""
            viewModel.awbList.add(noneObj)
            viewModel.awbList.addAll(vd.getJSONArray("data"))
        }
        ///////////////    下拉框   end
    }

    override fun onClick(v: View?) {
        v?.let {
            when (it.id) {
                R.id.awbType -> {
                    Common.singleSelect(yiKuActivity, "运单类型", viewModel.awbList, awbTypeValue) { _, item ->
                        val jsonObject = item as JSONObject
                        val name = jsonObject.getString("name")
                        val code = jsonObject.getString("code")
                        awbType.text = name
                        awbTypeValue = code
                    }
                }
                R.id.searchLayout -> {
//                    viewModel.queryPickByIdGnjChuKu("M000995643")
                    resetSearch()
                }
                R.id.checkIcon -> {
                    //重置 isAllCheck
                    isAllCheck = !isAllCheck

                    collectList.forEach { c ->
                        c.isCheck = isAllCheck
                    }
                    if (isAllCheck) {
                        viewModel.setCheckCount(totalCount)
                    } else {
                        viewModel.setCheckCount(0)
                    }
                    adapter.notifyDataSetChanged()
                }
                R.id.send -> {
                    val ids = collectList.filter { c -> c.isCheck }.map { c -> c.id }
                    viewModel.moveGnjYiKu(ids)
                }
                else -> {
                    Toast.makeText(yiKuActivity, "未找到对应操作", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    /**
     * 扫码返回的结果
     */
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        // 扫描二维码/条码回传
        if (resultCode == AppCompatActivity.RESULT_OK && data != null) {
            val content = data.getStringExtra(com.yzq.zxinglibrary.common.Constant.CODED_CONTENT)
            if (content == null) {
                Common.showToast(yiKuActivity, "条码错误！")
                return
            }
            when (requestCode) {
                Constant.RequestCode.gnj_chu_ku_list -> {

                }
            }
        }
    }

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

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