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.recyclerview.widget.LinearLayoutManager
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.gnj.R
import com.lukouguoji.gnj.adapt.GnjCangDanListAdapter
import com.lukouguoji.gnj.model.GnjCangDanListModel
import com.lukouguoji.gnj.viewModel.GnjCangDanListViewModel
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.lukouguoji.module_base.util.SwipeDeleteRecyclerView
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_GNJ_CANG_DAN_LIST)
class GnjCangDanListActivity : BaseActivity(), View.OnClickListener {
    private lateinit var viewModel: GnjCangDanListViewModel
    private lateinit var adapter: GnjCangDanListAdapter
    private val collectList = ArrayList<GnjCangDanListModel>()
    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 startDateIcon: ImageView
    private lateinit var fno: EditText
    private lateinit var start: TextView
    private var startCodeValue = ""
    private lateinit var dest: EditText
    private lateinit var endDate: TextView
    private lateinit var searchLayout: LinearLayout
    private lateinit var addIcon: ImageView
    private lateinit var checkIcon: ImageView
    private lateinit var quickSearch: EditText
    private var isAllCheck = true

    //列表
    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() {
        viewModel = ViewModelProvider(this).get(GnjCangDanListViewModel::class.java)
        val layoutManager = LinearLayoutManager(this)
        adapter = GnjCangDanListAdapter(this, viewModel, collectList)
        var recyclerView: SwipeDeleteRecyclerView = findViewById(R.id.collectList)
        recyclerView.layoutManager = layoutManager
        recyclerView.adapter = adapter
        refreshLayout = findViewById(R.id.refreshLayout)

        fdate = findViewById(R.id.fdate)
        startDateIcon = findViewById(R.id.startDateIcon)
        fno = findViewById(R.id.fno)
        start = findViewById(R.id.start)
        dest = findViewById(R.id.dest)
        endDate = findViewById(R.id.endDate)
        searchLayout = findViewById(R.id.searchLayout)
        addIcon = findViewById(R.id.addIcon)
        checkIcon = findViewById(R.id.checkIcon)
        quickSearch = findViewById(R.id.quickSearch)
        //列表
        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)

        fdate.setOnClickListener(this)
        startDateIcon.setOnClickListener(this)
        endDate.setOnClickListener(this)
        searchLayout.setOnClickListener(this)
        addIcon.setOnClickListener(this)
        checkIcon.setOnClickListener(this)
        send.setOnClickListener(this)
        start.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 = GnjCangDanListAdapter(
                        ActivityCollector.getLastActivity()!!,
                        viewModel,
                        filterCollectionList as MutableList<GnjCangDanListModel>
                    )
                } else {
                    recyclerView.adapter = GnjCangDanListAdapter(
                        ActivityCollector.getLastActivity()!!,
                        viewModel,
                        collectList
                    )
                }
                adapter.notifyDataSetChanged()
            }

            override fun afterTextChanged(s: Editable?) {

            }
        })

        fno.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-Z0-9]+)$)"
                    val matches = originText.matches(regularExpression.toRegex())
                    if(!matches){
                        val regularExpression2 = "([^A-Za-z0-9]+)"
                        val replaceStr = originText.replace(regularExpression2.toRegex(),"")
                        val replaceStrToUpper = replaceStr.uppercase(Locale.ROOT)//小写转大写
                        fno.setText(replaceStrToUpper)
                        fno.setSelection(replaceStrToUpper.length)
                    }
                }
            }
        })

        fdate.text = ymdSdf.format(Date())//tw2022年6月13日15:57:10 要求航班日期默认当天
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_gnj_cang_dan_list)
        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 no = itemObj.getString("wbNo") ?: ""
                    val goods = itemObj.getString("goods") ?: ""
                    val awbType = itemObj.getString("awbType") ?: ""
                    val startPort = itemObj.getString("origin") ?: ""
                    val destPort = itemObj.getString("dest") ?: ""
                    val agentCode = itemObj.getString("agentCode") ?: ""
                    val spCode = itemObj.getString("spCode") ?: ""
                    val totalPc = itemObj.getIntValue("totalPc")
                    val pc = itemObj.getIntValue("pc")
                    val acWeight = itemObj.getDoubleValue("weight")//实到重量
                    val chWight = itemObj.getDoubleValue("cashWeight")//计费重量

                    val ref = itemObj.getString("ref") ?: ""// 1查看

                    //列表赋值
                    collectList.add(
                        GnjCangDanListModel(
                            mfId.toString(),
                            no,
                            goods,
                            awbType,
                            startPort,
                            destPort,
                            agentCode,
                            spCode,
                            totalPc,
                            pc,
                            acWeight,
                            false,
                            ref
                        )
                    )
                }
                //3.调adpter展示
                if (currentPage == 1) {
                    val layoutManager = LinearLayoutManager(this)
                    adapter = GnjCangDanListAdapter(this, viewModel, collectList)
                    var recyclerView: SwipeDeleteRecyclerView = findViewById(R.id.collectList)
                    recyclerView.layoutManager = layoutManager
                    recyclerView.adapter = adapter
                } else {
                    adapter.notifyItemRangeInserted((currentPage - 1) * 10, collectList.size)
                }
                refreshLayout.finishRefresh()
                refreshLayout.finishLoadMore()

            }

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

        //航班返回结果
        viewModel.domFlightGnjCangDanObserver.observe(this) {
            loadingCancel()
            val status = it.getString("status")
            if (Constant.Result.succ == status) {
                var jsonObject = it.getJSONObject("data")
                viewModel.fid = jsonObject.getInteger("fid")
                viewModel.prefix = jsonObject.getString("prefix")
                viewModel.fdep=jsonObject.getString("fdep")
                viewModel.fdest=jsonObject.getString("fdest")
                val actualArrival = jsonObject.getString("actualArrival")
                val fdest = jsonObject.getString("fdest")

                dest.setText(fdest)
                endDate.text = actualArrival

                if (viewModel.fid != null) {
                    listLayout.visibility = View.VISIBLE
                    totalLayout.visibility = View.VISIBLE
                    resetSearch()
                }

            } else {
                //无数据
            }
        }

        //删除行 返回结果
        viewModel.deleteFestGnjCangDanObserver.observe(this) {
            loadingCancel()
            val positionDel = it.getInteger("positionDel")
            val status = it.getString("status")
            val msg = it.getString("msg")
            if (Constant.Result.succ == status) {
                collectList.removeAt(positionDel)
                adapter.notifyItemRemoved(positionDel)
                val dataStatus = it.getString("data")
                if (Constant.Result.succ == dataStatus) {
                    Common.showToast(this, "删除成功！")

                } else if (Constant.Result.code2 == dataStatus) {
                    Common.showToast(this, "货物已发放，不允许删除！")
                } else {
                    Common.showToast(this, "删除失败！")
                }
            } else {
                Common.showToast(this, "删除失败！")
            }
        }

        //货物发放 返回结果
        viewModel.provideGnjCangDanObserver.observe(this) {
            loadingCancel()
            val status = it.getString("status")
            val msg = it.getString("msg")
            if (Constant.Result.succ == status) {
                val data = it.getString("data")
                if (Constant.Result.succ == data) {
                    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, "货物发放失败！")
                }
            }
            //重新搜索
            resetSearch()
        }

        ///////////////    下拉框   start
        viewModel.start(System.currentTimeMillis().toString())
        viewModel.startObserver.observe(this) { vd ->
            val noneObj = JSONObject()
            noneObj["name"] = "请选择始发站"
            noneObj["code"] = ""
            viewModel.startList.add(noneObj)
            viewModel.startList.addAll(vd.getJSONArray("data"))
        }
        ///////////////    下拉框   end

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

        ///////////////////////////////   加载刷新的布局
        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.fdate -> {
                    Common.onYearMonthDay(this, fdate.text.toString()) { year, month, day ->
                        calendar.set(year, month - 1, day)
                        fdate.text = ymdSdf.format(calendar.time)
                    }
                }
                R.id.startDateIcon -> {
                    fdate.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.searchLayout -> {
                    endDate.text = ""
                    dest.setText("")
                    doFlight()
                }
                R.id.addIcon -> {
                    ARouter.getInstance().build(ARouterConstants.ACTIVITY_URL_GNJ_CANG_DAN_INFO).withString("id", null).withString("ref", null)
                        .withInt("fid", viewModel.fid ?: -9999).withString("prefix", viewModel.prefix).withString("fdep",viewModel.fdep).withString("fdest",viewModel.fdest)
                        .navigation(this, Constant.RequestCode.gnj_cang_dan_list)
                }
                R.id.checkIcon -> {
                    var selCount = 0
                    collectList.forEach { c ->
                        //不是出库 并且 选中，可以选
                        if (c.ref != "1" && isAllCheck) {
                            c.isCheck = isAllCheck
                            ++selCount
                        } else {
                            c.isCheck = false
                        }
                    }
                    if (isAllCheck) {
                        viewModel.setCheckCount(selCount)
                    } else {
                        viewModel.setCheckCount(0)
                    }
                    //重置 isAllCheck
                    isAllCheck = !isAllCheck
                    adapter.notifyDataSetChanged()
                }
                R.id.send -> {
                    val ids = collectList.filter { c -> c.isCheck }.map { c -> c.id.toInt() }
                    viewModel.provideGnjCangDan(viewModel.fid!!, ids)
                }
                R.id.start -> {
                    Common.singleSelect(this, "请选择始发站", viewModel.startList, startCodeValue) { _, item ->
                        val jsonObject = item as JSONObject
                        val name = jsonObject.getString("name")
                        val code = jsonObject.getString("code")
                        start.text = name
                        startCodeValue = code
                    }
                }
                else -> {
                    Toast.makeText(this, "未找到对应操作", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    /**
     * onActivityResult 回调
     */
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == Constant.RequestCode.gnj_cang_dan_list && resultCode == RESULT_OK) {
            resetSearch()
        }
    }


    /**
     * 搜索
     */
    private fun searchFun() {
        /*if (fdate.text.toString() == "" || fno.text.toString() == "") {
            Common.showToast(this, "航班日期和航班号不可为空！")
            return
        }*/
        loading()
        viewModel.search(
            pageSize,
            currentPage,
            "",
            "",
            "",
            fdate.text.toString(),
            fno.text.toString(),
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            "",
            ""
        )
    }

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

    /**
     * 查询航班是否存在
     */
    private fun doFlight() {
        if (fdate.text.toString() == "" || fno.text.toString() == "") {
            Common.showToast(this, "航班日期和航班号不可为空！")
            return
        }
        loading()
        listLayout.visibility = View.GONE
        totalLayout.visibility = View.GONE
        viewModel.domFlightGnjCangDan(fdate.text.toString(), fno.text.toString())
    }

}