package com.lukouguoji.gjj.activity

import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.TextView
import android.widget.Toast
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.gjj.R
import com.lukouguoji.gjj.adapt.GjjWareHouseListAdapter
import com.lukouguoji.gjj.model.GjjWareHouseList
import com.lukouguoji.gjj.viewModel.GjjWareHouseListViewModel
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 java.text.SimpleDateFormat
import java.util.*

//@Route(path = ARouterConstants.ACTIVITY_URL_GJJ_WARE_HOUSE)
class GjjWareHouseActivity : BaseActivity(), View.OnClickListener {
    private lateinit var viewModel: GjjWareHouseListViewModel
    private val currentTitleName = "国际进港仓库管理"

    private lateinit var adapter: GjjWareHouseListAdapter
    private val collectList = ArrayList<GjjWareHouseList>()

    private lateinit var refreshLayout: RefreshLayout
    private var currentPage = 1
    private var pageSize = 10
    private var totalPage = 0

    //是否刷新
    private var refresh = false

    //标题
    private lateinit var toolBack: LinearLayout
    private lateinit var titleName: TextView

    //搜索条件
    private lateinit var searchListFragment: LinearLayout

    private lateinit var wayNo: EditText
    private lateinit var agentCode: TextView
    private var agentCodeValue = ""
    private lateinit var carrier: EditText
    private lateinit var location: EditText
    private lateinit var searchLayout: LinearLayout
    private lateinit var summaryText: TextView

    //筛选页
    private lateinit var filtrateLayout: LinearLayout
    private lateinit var filtrateFragment: LinearLayout
    private lateinit var fdep: EditText
    private lateinit var isGroup: TextView
    private var isGroupStatus = ""
    private val isGroupArr = JSONArray()

    private lateinit var submit: TextView
    private lateinit var reset: TextView

    private val ymdSdf = SimpleDateFormat("yyyy-MM-dd")//年月日
    private val ymdHmsSdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")//年月日 时分秒
    private val calendar = Calendar.getInstance()

    private fun initView() {
        viewModel = ViewModelProvider(this).get(GjjWareHouseListViewModel::class.java)

        val layoutManager = LinearLayoutManager(this)
        adapter = GjjWareHouseListAdapter(this, collectList)
        var recyclerView: RecyclerView = findViewById(R.id.guo_nei_collect_list)
        recyclerView.layoutManager = layoutManager
        recyclerView.adapter = adapter

        refreshLayout = findViewById(R.id.refreshLayout)

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

        //搜索列表页
        searchListFragment = findViewById(R.id.searchListFragment)
        wayNo = findViewById(R.id.waybillNo)
        agentCode = findViewById(R.id.agentCode)
        carrier = findViewById(R.id.carrier)
        location = findViewById(R.id.location)
        searchLayout = findViewById(R.id.searchLayout)
        filtrateLayout = findViewById(R.id.filtrateLayout)
        summaryText = findViewById(R.id.summaryText)
        //筛选页
        filtrateFragment = findViewById(R.id.filtrateFragment)
        fdep = findViewById(R.id.fdep)
        isGroup = findViewById(R.id.isGroup)

        submit = findViewById(R.id.submit)
        reset = findViewById(R.id.reset)

        toolBack.setOnClickListener(this)
        searchLayout.setOnClickListener(this)
        filtrateLayout.setOnClickListener(this)
        submit.setOnClickListener(this)
        reset.setOnClickListener(this)
        isGroup.setOnClickListener(this)
        agentCode.setOnClickListener(this)

        wayNo.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 ->
                        wayNo.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)
                    }
                }
            }
        })

        //赋值
        //是否上舱单
        val noneGroup = JSONObject()
        noneGroup["name"] = "请选择分组类型"
        noneGroup["code"] = ""
        val yesGroup = JSONObject()
        yesGroup["name"] = "航程"
        yesGroup["code"] = "dest"
        val noGroup = JSONObject()
        noGroup["name"] = "库位"
        noGroup["code"] = "location"
        val dateGroup = JSONObject()
        dateGroup["name"] = "入库时间"
        dateGroup["code"] = "date"
        isGroupArr.add(noneGroup)
        isGroupArr.add(yesGroup)
        isGroupArr.add(noGroup)
        isGroupArr.add(dateGroup)

    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_gjj_ware_house)
        initView()

        //查询返回结果
        viewModel.searchParamLive.observe(this) {
            loadingCancel()
            //1.获取数据
            var listArr = JSONArray()
            try {
                listArr = it["list"] as JSONArray
            } catch (e: Exception) {
                return@observe
            }
            totalPage = it["pages"] as Int
//            var listArr :JSONArray =it["list"] as JSONArray
            if (listArr.size > 0) {
                //2.循环遍历塞入collectList
                listArr.forEach {
                    val itemObj = it as JSONObject
                    val whId = itemObj.getIntValue("whid")
                    val no = itemObj.getString("wbNo") ?: ""
                    val weight = itemObj.getDouble("weight")
                    val pc = itemObj.getIntValue("pc")
                    val fno = itemObj.getString("fno") ?: ""
                    val flight = itemObj.getString("flight") ?: ""
                    val opDate = itemObj.getString("opDate") ?: ""
                    val gdate = itemObj.getString("gdate") ?: ""
                    val locStatus = itemObj.getString("locStatus") ?: ""
                    val dest = itemObj.getString("dest") ?: ""
                    val location = itemObj.getString("location") ?: ""
                    val goods = itemObj.getString("goods") ?: ""
                    val spCode = itemObj.getString("spCode") ?: ""
                    val agentCode = itemObj.getString("agentCode") ?: ""
                    val by1 = itemObj.getString("by1") ?: ""
                    val origin = itemObj.getString("origin") ?: ""
                    val awbType = itemObj.getString("awbType") ?: ""
                    val businessType = itemObj.getString("businessType") ?: ""
                    val status = itemObj.getString("status") ?: ""
                    val days = itemObj.getIntValue("days")


                    var groupTitle = ""
                    var groupName = ""
                    var daysString: String? = null
                    when (isGroupStatus) {
                        "dest" -> {
                            groupTitle = "目的港："
                            groupName = dest
                        }
                        "location" -> {
                            groupTitle = "库位："
                            groupName = location
                        }
                        "date" -> {
                            groupTitle = "入库时间："
                            groupName = "$gdate，入库天数："
                            daysString = days.toString()
                        }
                        else -> {

                        }
                    }

                    collectList.add(
                        GjjWareHouseList(
                            whId,
                            no,
                            pc,
                            weight,
                            fno,
                            flight,
                            opDate,
                            locStatus,
                            groupTitle,
                            groupName,
                            daysString,
                            goods,
                            spCode,
                            agentCode,
                            by1,
                            origin,
                            location,
                            awbType,
                            businessType,
                            status,
                        )
                    )
                }
                //3.调adpter展示
                if (currentPage == 1) {
                    adapter.notifyDataSetChanged()
                } else {
                    adapter.notifyItemRangeInserted((currentPage - 1) * 10, collectList.size)
                }
                refreshLayout.finishRefresh()
                refreshLayout.finishLoadMore()

            }
        }

        //汇总返回结果
        viewModel.summaryObserver.observe(this) {
            loadingCancel()
            val status = it.getString("status")
            if (Constant.Result.succ == status) {
                var jsonObject = it.getJSONObject("data")
                val totalTemp = jsonObject.getIntValue("total")
                val totalPcTemp = jsonObject.getIntValue("pc")
                val totalWeightTemp = jsonObject.getDoubleValue("weight")
                summaryText.text = "总票数：$totalTemp，总件数：$totalPcTemp，总重量：$totalWeightTemp"
            } else {
                //无数据
            }
        }

        //初始化查询
        searchFun()
        loading()

        ///////////////    下拉框   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"))
        }

        viewModel.business(Constant.businessType.II)
        viewModel.businessObserver.observe(this) { vd ->
            val noneObj = JSONObject()
            noneObj["name"] = "请选择业务类型"
            noneObj["code"] = ""
            viewModel.businessList.add(noneObj)
            viewModel.businessList.addAll(vd.getJSONArray("data"))
        }
        ///////////////    下拉框   end

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

    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.searchLayout -> {
                    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.isGroup -> {
                    Common.singleSelect(this, "分组类型", isGroupArr, isGroupStatus) { position, item ->
                        val jsonObject = item as JSONObject
                        val name = jsonObject.getString("name")
                        val code = jsonObject.getString("code")
                        isGroup.text = name
                        isGroupStatus = code
                    }
                }
                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()
                }
            }
        }
    }


    /**
     * 搜索
     */
    private fun searchFun() {
        viewModel.search(
            pageSize,
            currentPage,
            carrier.text.toString(),
            "",
            "",
            "",
            "",
            fdep.text.toString(),
            "",
            "",
            "",
            "",//isCangDanStatus
            wayNo.text.toString(),
            isGroupStatus,
            agentCodeValue,
            location.text.toString()
        )
    }

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

    /**
     * 重置筛选条件
     */
    private fun resetFun() {
        currentPage = 1
        wayNo.setText("")
        agentCode.text = ""
        agentCodeValue = ""
        carrier.setText("")
        location.setText("")

        fdep.setText("")
        isGroup.text = ""
        isGroupStatus = ""

    }


}