package com.lukouguoji.gjj.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.gjj.R
import com.lukouguoji.gjj.adapt.GjjCangDanListAdapter
import com.lukouguoji.gjj.model.GjjCangDanListModel
import com.lukouguoji.gjj.viewModel.GjjCangDanListViewModel
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_GJJ_CANG_DAN_LIST)
class GjjCangDanListActivity : BaseActivity(), View.OnClickListener {
    private lateinit var viewModel: GjjCangDanListViewModel
    private lateinit var adapter: GjjCangDanListAdapter
    private val collectList = ArrayList<GjjCangDanListModel>()
    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 fdep: EditText
    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 = 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() {
        viewModel = ViewModelProvider(this).get(GjjCangDanListViewModel::class.java)
        val layoutManager = LinearLayoutManager(this)
        adapter = GjjCangDanListAdapter(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)
        fdep = findViewById(R.id.fdep)
        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)

        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 = GjjCangDanListAdapter(
                        ActivityCollector.getLastActivity()!!,
                        viewModel,
                        filterCollectionList as MutableList<GjjCangDanListModel>
                    )
                } else {
                    recyclerView.adapter = GjjCangDanListAdapter(
                        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_gjj_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(
                        GjjCangDanListModel(
                            mfId.toString(),
                            no,
                            goods,
                            awbType,
                            startPort,
                            destPort,
                            agentCode,
                            spCode,
                            totalPc,
                            pc,
                            acWeight,
                            chWight,
                            false,
                            ref
                        )
                    )
                }
                //3.调adpter展示
                if (currentPage == 1) {
                    val layoutManager = LinearLayoutManager(this)
                    adapter = GjjCangDanListAdapter(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()
            resetSelCount(false)
        }

        //航班返回结果
        viewModel.intFlightGjjCangDanObserver.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")
                val actualArrival = jsonObject.getString("actualArrival")
                val fdepParam = jsonObject.getString("fdep")//始发港
                val fdest = jsonObject.getString("fdest")//目的港

                fdep.setText(fdepParam)
                dest.setText(fdest)
                endDate.text = actualArrival

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

            } else {
                //无数据
            }
        }

        //删除行 返回结果
        viewModel.deleteFestGjjCangDanObserver.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)
                resetSelCount(false)
                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.provideGjjCangDanObserver.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()
        }

        //监听 复选框选中
        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_GJJ_CANG_DAN_INFO).withString("id", null).withString("ref", null)
                        .withInt("fid", viewModel.fid ?: -9999).withString("prefix", viewModel.prefix)
                        .navigation(this, Constant.RequestCode.gjj_cang_dan_list)
                }
                R.id.checkIcon -> {
                    isAllCheck = !isAllCheck
                    resetSelCount(isAllCheck)
                    checkIcon.setImageResource(if (isAllCheck) R.drawable.img_check_all_checked else R.drawable.img_check_all_unchecked)
                }
                R.id.send -> {
                    val ids = collectList.filter { c -> c.isCheck }.map { c -> c.id.toInt() }
                    viewModel.provideGjjCangDan(viewModel.fid!!, ids)
                }
                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.gjj_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.intFlightGjjCangDan(fdate.text.toString(), fno.text.toString())
    }

    /**
     * 重新计算选中数量
     * isAllCheckParam  true：全选  false:全部全效选择
     */
    private fun resetSelCount(isAllCheckParam: Boolean) {
        var selCount = 0
        collectList.forEach { c ->
            //不是出库 并且 选中，可以选
            if (c.ref != "1" && isAllCheckParam) {
                c.isCheck = isAllCheckParam
                ++selCount
            } else {
                c.isCheck = false
            }
        }
        if (isAllCheckParam) {
            viewModel.setCheckCount(selCount)
        } else {
            viewModel.setCheckCount(0)
        }
        adapter.notifyDataSetChanged()
    }
}