package com.lukouguoji.gnc.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 androidx.recyclerview.widget.RecyclerView
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.gnc.R
import com.lukouguoji.gnc.adapt.GoutCollectionAdapter
import com.lukouguoji.gnc.model.GuoNeiOutCollect
import com.lukouguoji.gnc.page.shouyun.list.GncShouYunListActivity
import com.lukouguoji.gnc.viewModel.GoutCollectionViewModel
import com.lukouguoji.module_base.BaseActivity
import com.lukouguoji.module_base.MyApplication
import com.lukouguoji.module_base.adapter.bindAdapter
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 com.yzq.zxinglibrary.common.Constant
import dev.utils.app.info.KeyValue
import dev.utils.common.StringUtils
import java.text.SimpleDateFormat
import java.util.*

@Route(path = ARouterConstants.ACTIVITY_URL_GOUT_COLLECTION_ACTIVITY)
class GoutCollectionActivity : BaseActivity(), View.OnClickListener {

    private lateinit var adapter: GoutCollectionAdapter
    private val collectList = ArrayList<GuoNeiOutCollect>()

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

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

    private lateinit var searchListFragment: LinearLayout
    private lateinit var filtrateFragment: LinearLayout
    private lateinit var filtrateLayout: LinearLayout
    private lateinit var dest: EditText

    private lateinit var agentCode: Spinner
    private var agentCodeValue = ""
    private lateinit var spCode: Spinner
    private var spCodeValue = ""

    private lateinit var search: LinearLayout
    private lateinit var add: LinearLayout
    private lateinit var searchContent: EditText
    private lateinit var scanCodeImg: ImageView
    private lateinit var fdate: TextView

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

    //是否刷新
    private var refresh = false
    private lateinit var viewModel: GoutCollectionViewModel

    val topTitleName = "国内出港待收运"

    private fun initView() {

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

        agentCode = findViewById(R.id.agentCode)
        spCode = findViewById(R.id.spCode)

        search = findViewById(R.id.search)
        searchListFragment = findViewById(R.id.searchListFragment)
        filtrateFragment = findViewById(R.id.filtrateFragment)
        filtrateLayout = findViewById(R.id.filtrateLayout)
        add = findViewById(R.id.add)
        dest = findViewById(R.id.dest)
        searchContent = findViewById(R.id.search_content)
        scanCodeImg = findViewById(R.id.scanCodeImg)
        fdate = findViewById(R.id.fdate)


        toolBack.setOnClickListener(this)
        search.setOnClickListener(this)
        add.setOnClickListener(this)
        fdate.setOnClickListener(this)
        filtrateLayout.setOnClickListener(this)
        findViewById<View>(R.id.shouyun).setOnClickListener(this)



        viewModel.agentCode(System.currentTimeMillis().toString())
        viewModel.agentCodeObserver.observe(this) { vd ->
            viewModel.agentCodeList.clear()
            viewModel.agentCodeList.addAll(vd.getJSONArray("data"))
            initSpinner(agentCode, viewModel.agentCodeList, null, "请选择代理人")
        }

        viewModel.specialCode(System.currentTimeMillis().toString())
        viewModel.specialCodeObserver.observe(this) { vd ->
            viewModel.specialCodeList.clear()
            viewModel.specialCodeList.addAll(vd.getJSONArray("data"))
            initSpinner(spCode, viewModel.specialCodeList, null, "请选择特码")
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_check_in_list)
        viewModel = ViewModelProvider(this).get(GoutCollectionViewModel::class.java)
        initView()


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

        viewModel.searchParamLive.observe(this) {
            loadingCancel()
            //1.获取数据
            var listArr: JSONArray = it["list"] as JSONArray
            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 mawbId = itemObj.getIntValue("mawbId")
                    val wbNo = itemObj.getString("wbNo") ?: ""
                    val agentCode = itemObj.getString("agentCode") ?: ""
                    val dest = itemObj.getString("dest") ?: ""
                    val spCode = itemObj.getString("pc") ?: ""
                    val goods = itemObj.getString("goods") ?: ""
                    //todo 增加预计起飞并且升序显示
                    val planDate = itemObj.getString("estimatedTakeOff") ?: ""
                    val flight = itemObj.getString("flight") ?: ""
                    val range = itemObj.getString("range") ?: ""

                    collectList.add(
                        GuoNeiOutCollect(
                            mawbId,
                            wbNo,
                            dest,
                            agentCode,
                            spCode,
                            goods,
                            planDate,
                            range,
                            flight
                        )
                    )
                }
                //3.调adpter展示
                if (currentPage == 1) {
                    adapter.notifyDataSetChanged()
                } else {
                    adapter.notifyItemRangeInserted((currentPage - 1) * 10, collectList.size)
                }
                refreshLayout.finishRefresh()
                refreshLayout.finishLoadMore()

            }
        }
        //初始化查询
        viewModel.search(pageSize, currentPage, text)
        loading()

        ///////////////////////////////   加载刷新的布局
        refreshLayout = findViewById<View>(R.id.refreshLayout) as RefreshLayout
        refreshLayout.setRefreshHeader(ClassicsHeader(this))
        refreshLayout.setRefreshFooter(ClassicsFooter(this))
        /////////////////////////////// 下拉刷新
        refreshLayout.setOnRefreshListener {
            refresh = true
            currentPage = 1
            //recyclerView 清除所有数据数据
            adapter.notifyItemRangeRemoved(0, collectList.size)
            collectList.clear()
            //初始化查询
            viewModel.search(pageSize, currentPage, text)
            adapter.notifyItemRangeInserted(0, collectList.size)
        }
        /////////////////////////////// 上拉加载
        refreshLayout.setOnLoadMoreListener {
            refresh = false
            if (currentPage < totalPage) {
                currentPage++
                //初始化查询
                viewModel.search(pageSize, currentPage, text)
            } else {
                refreshLayout.finishLoadMoreWithNoMoreData()
            }
        }

        search.setOnClickListener {
            currentPage = 1
            //recyclerView 清除所有数据数据
            adapter.notifyItemRangeRemoved(0, collectList.size)
            collectList.clear()
            //初始化查询
            viewModel.search(pageSize, currentPage, searchContent.text.toString())
        }


        //点击扫码
        scanCodeImg.setOnClickListener {
            scanCode(com.lukouguoji.module_base.common.Constant.RequestCode.gnc_shouyun_search)
        }
        searchContent.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.toString() != "" && s.toString().length == 12) {
                    ARouter.getInstance()
                        .build(ARouterConstants.ACTIVITY_URL_GOUT_START_COT_ACTIVITY)
                        .withString("wbNoParam", s.toString())
                        .navigation(MyApplication.context)
                }
            }

            override fun afterTextChanged(s: Editable?) {

            }
        })

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        // 扫描二维码/条码回传
        if (requestCode == com.lukouguoji.module_base.common.Constant.RequestCode.gnc_shouyun_search && resultCode == RESULT_OK) {
            if (data != null) {
                val content = data.getStringExtra(Constant.CODED_CONTENT)
                searchContent.setText("$content")

                //调用接口查询进入详情页
                if (content != null && content != "") {
                    ARouter.getInstance()
                        .build(ARouterConstants.ACTIVITY_URL_GOUT_START_COT_ACTIVITY)
                        .withString("wbNoParam", content)
                        .navigation(this)
                }

            }
        }

        if (requestCode == com.lukouguoji.module_base.common.Constant.RequestCode.gnc_shouyun_refresh && resultCode == RESULT_OK) {
            collectList.clear()
            currentPage = 1
            refreshLayout.setNoMoreData(false)
            viewModel.search(10, 1, "")
            loading()
        }
    }

    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 = topTitleName
                    } else {
                        finish()
                    }
                }
                R.id.search -> {

                }
                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 = topTitleName
                    }
//                    Common.showToast(this,"筛选")
                }
                R.id.add -> {
                    ARouter.getInstance()
                        .build(ARouterConstants.ACTIVITY_URL_GOUT_START_COT_ACTIVITY)
                        .withString("wbNoParam", "")
                        .navigation(MyApplication.context)
                }

                R.id.shouyun -> {
                    GncShouYunListActivity.start(this)
                }

                R.id.fdate -> {
                    Common.onYearMonthDay(this, fdate.text.toString()) { year, month, day ->
                        calendar.set(year, month - 1, day)
                        fdate.text = ymdSdf.format(calendar.time)
                    }
                }

                else -> {
                    Toast.makeText(this, "未找到对应操作", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }

    private fun initSpinner(sp: Spinner, dataListArr: JSONArray, selPosition: Int?, hint: String?) {
        val jsonObjectList: List<JSONObject> = (0 until dataListArr.size).map { dataListArr.getJSONObject(it) }
        val dataList: List<KeyValue> = jsonObjectList.map { KeyValue(it.getString("name"),it.getString("code")) }

        bindAdapter(sp, dataList, hint, null)
        selPosition?.let { sp.setSelection(it) }
        //给下拉框设置选择监听器，一旦用户选中某一项，就触发监听器的onItemSelected方法
        sp.onItemSelectedListener = MySelectedListener(sp.id, hint)
    }

    /**
     * 下拉框监听
     */
    inner class MySelectedListener(private val spinnerView: Int, val hint: String?) : AdapterView.OnItemSelectedListener {
        override fun onItemSelected(adapterView: AdapterView<*>?, view: View, i: Int, l: Long) {
            when (spinnerView) {
                R.id.agentCode -> {
                    agentCodeValue = if (StringUtils.isNotEmpty(hint) && i == viewModel.agentCodeList.size) {
                        ""
                    } else {
                        viewModel.agentCodeList.getJSONObject(i).getString("code")
                    }
                }
                R.id.spCode -> {
                    spCodeValue = if (StringUtils.isNotEmpty(hint) && i == viewModel.specialCodeList.size) {
                        ""
                    } else {
                        viewModel.specialCodeList.getJSONObject(i).getString("code")
                    }
                }
            }
        }

        override fun onNothingSelected(adapterView: AdapterView<*>?) {}
    }
}