package com.quansu.heifengwuliu.fragment

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import android.widget.TextView.OnEditorActionListener
import androidx.recyclerview.widget.LinearLayoutManager
import com.quansu.heifengwuliu.activity.AddressAddActivity
import com.quansu.heifengwuliu.adapter.AddressAdapter
import com.quansu.heifengwuliu.base.MBRFragment
import com.quansu.heifengwuliu.config.MIntentAction
import com.quansu.heifengwuliu.databinding.FragmentAddressBinding
import com.quansu.heifengwuliu.model.AddressBean
import com.quansu.heifengwuliu.utils.net.NetEngine
import com.quansu.heifengwuliu.vmodel.AddressVModel
import com.ysnows.base.net.IResponse
import com.ysnows.base.utils.B
import com.ysnows.base.utils.UiSwitch
import io.reactivex.Observable
import kotlinx.android.synthetic.main.widget_search.view.*
import java.util.*

//发货 -卸货地址
class AddressFragment : MBRFragment<AddressVModel, AddressAdapter, FragmentAddressBinding>() {

    var type:String=""
    var  isShow:String=""
    var k:String=""
    private var sideBarData = arrayListOf<String>()

    override fun __before(savedInstanceState: Bundle?) {
        super.__before(savedInstanceState)
        val arguments = arguments
        if(null!=arguments) {
            type = arguments.getString("type")
            isShow = arguments.getString("isShow", "1")
        }
    }

    override fun vmClass(): Class<AddressVModel> {
        return AddressVModel::class.java
    }
    override fun init(savedInstanceState: Bundle?) {
        super.init(savedInstanceState)
        vm.inData(type,this)
        binding.sidebar.attachTipView(binding.tvTip)
    }

    override fun listeners() {
        super.listeners()

        binding.tvAdd.setOnClickListener {
            //添加地址
            UiSwitch.bundleRes(this, AddressAddActivity::class.java,
                    B.with().putString("type",type).ok(), MIntentAction.REQUEST_CODE_ONE)
        }

         binding.sidebar.setOnSelectedListener { position, text ->
           if (adapter().data != null && adapter().data.size > 0) {
               for (i in 0 until adapter().data.size) {
                   var client = adapter().data[i]
                   if (text == client.py) {
                       (binding.recyclerView.layoutManager as LinearLayoutManager).scrollToPositionWithOffset(i, 0)

                   }

               }

           }
       }

        binding.search.getIvDelete()!!.setOnClickListener {
            if (!TextUtils.isEmpty(binding.search.getEtName()!!.text.toString().trim { it <= ' ' })) {
                binding.search.getEtName()!!.setText(null)
                onRefresh()
            } else {
                toast( "已经删除搜索条件！")
            }
        }

        binding.search.getEtName()!!.setOnEditorActionListener(OnEditorActionListener { textView, i, keyEvent ->
            if (i == EditorInfo.IME_ACTION_SEARCH) {
                k = binding.search.getEtName()!!.text.toString().trim()
                onRefresh()
                return@OnEditorActionListener true
            }
            false
        })

        binding.search.getTvSearch()!!.setOnClickListener { t ->
            k = binding.search.getEtName()!!.text.toString().trim()
            onRefresh()
        }

    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (MIntentAction.REQUEST_CODE_ONE == requestCode && resultCode == Activity.RESULT_OK) {
            //刷新列表
            onRefresh()
        }
    }


    override fun onListReceive(res: IResponse<*>) {
        super.onListReceive(res)
        if (null != res) {
            sideBarData.clear()
            setSideBarData(res.data() as List<AddressBean>)
        }

    }

    private fun setSideBarData(data: List<AddressBean>) {
        for (i in data.indices) {
            if (!TextUtils.isEmpty(data[i].py)) {

                sideBarData.add(data[i].py.toString())
            }
        }
        //去重
        val list = removeDuplicateWithOrder(sideBarData)
        if (sideBarData != null && sideBarData.size > 0) {
            binding.sidebar.setData(list)
        } else {
            binding.sidebar.init()
        }
    }

    private fun removeDuplicateWithOrder(list: List<String>): ArrayList<String> {
        val set: MutableSet<String> = HashSet<String>()
        val newList: ArrayList<String> = ArrayList<String>()
        val iter = list.iterator()
        while (iter.hasNext()) {
            val element = iter.next()!!
            if (set.add(element)) newList.add(element)
        }
        return newList
    }

    override fun initAdapter(): AddressAdapter {
        return AddressAdapter(vm,isShow)
    }

    override fun api(): Observable<out IResponse<*>> {
        return NetEngine.service.addressList(type,k, vm?.repository()?.autoPage()!!)
    }

    override fun binding(inflater: LayoutInflater, container: ViewGroup?): FragmentAddressBinding {
        return FragmentAddressBinding.inflate(layoutInflater, container, false)
    }

    override fun title(): String? {
        return null
    }
}
