package com.pan_american.android.ui.customer_resource.company_customer

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.CheckedTextView
import android.widget.PopupWindow
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.pan_american.android.OASystem
import com.pan_american.android.R
import com.pan_american.android.base.BaseActivity
import com.pan_american.android.base.BaseResponse
import com.pan_american.android.base.ListAdapter
import com.pan_american.android.data.model.common.entity.SiftListItem
import com.pan_american.android.data.model.customer_resource.company_customer.adapter.MarketCustomerListAdapter
import com.pan_american.android.data.model.customer_resource.company_customer.entity.MarketCustomer
import com.pan_american.android.data.model.customer_resource.company_customer.entity.MarketCustomerListItem
import com.pan_american.android.data.model.customer_resource.company_customer.network.BatchAssignmentRequest
import com.pan_american.android.data.model.customer_resource.company_customer.network.CompanyCustomerBaseDataRequest
import com.pan_american.android.data.model.customer_resource.company_customer.network.MarketCustomerRequest
import com.pan_american.android.data.model.customer_resource.company_customer.network.MarketCustomerResponse
import com.pan_american.android.data.model.customer_resource.company_customer.network.MarketCustomerSiftListResponse
import com.pan_american.android.data.network.APIService
import com.pan_american.android.data.network.ServiceCreator
import com.pan_american.android.databinding.ActivityMarketCustomerBinding
import com.pan_american.android.databinding.LayoutTitleBinding
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.scwang.smart.refresh.header.ClassicsHeader
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class MarketCustomerActivity : BaseActivity<ActivityMarketCustomerBinding>() {

    private lateinit var titleBinding: LayoutTitleBinding

    private val apiService = ServiceCreator.create<APIService>()

    private lateinit var marketCustomerRequest: MarketCustomerRequest

    private var marketCustomerListItemList = ArrayList<MarketCustomerListItem>()

    private var listInit = false

    private var pageIndex = 1

    private var totalPage = 0

    //是否显示筛选fragment
    private var showSift: Boolean = false

    //是否点击了客户指派
    private var isAssign: Boolean = false

    //负责人选择弹窗popView
    private lateinit var popView: View

    //负责人列表
    private var customerManager = ArrayList<SiftListItem>()

    //客户 id列表
    private var customerIdList = ArrayList<Int>()

    //负责人 id列表
    private var customerManagerList = ArrayList<Int>()

    private lateinit var adapter: MarketCustomerListAdapter

    override fun getViewBinding() = ActivityMarketCustomerBinding.inflate(layoutInflater)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        screenAdaptation(binding)

        marketCustomerRequest = MarketCustomerRequest()

        marketCustomerRequest.pageIndex = pageIndex
        marketCustomerRequest.pageSize = 10

        //先获取客户筛选列表
        initCustomerSiftList()

        initTitle()
    }

    override fun onStart() {
        super.onStart()

        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this)
        }

        if (OASystem.needRefresh) {
            pageIndex = 1
            marketCustomerRequest.pageIndex = pageIndex
            marketCustomerListItemList.clear()
            OASystem.needRefresh = false
            initMarketCustomerList(2)
        }
    }

    override fun onStop() {
        super.onStop()

        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this)
        }
    }

    override fun initTitle() {
        titleBinding = LayoutTitleBinding.bind(binding.root).apply {
            titleText.text = resources.getString(R.string.company_customer_resource)
            searchView.visibility = View.VISIBLE
        }

        titleBinding.backButton.setOnClickListener {
            back()
        }
    }

    override fun initViews() {
        binding.resourceListContainer.setRefreshHeader(ClassicsHeader(OASystem.context))
        binding.resourceListContainer.setRefreshFooter(ClassicsFooter(OASystem.context))

        initMarketCustomerList(1)
    }

    override fun initEvents() {

        titleBinding.searchText.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

            }

            override fun afterTextChanged(changedText: Editable?) {

                marketCustomerRequest.pageIndex = 1

                if (changedText.isNullOrBlank()) {
                    marketCustomerRequest.client = ""
                } else {
                    marketCustomerRequest.client = changedText.toString()
                }

                pageIndex = 1
                binding.marketCustomerList.adapter!!.notifyItemRangeRemoved(0, marketCustomerListItemList.size)
                marketCustomerListItemList.clear()
                listInit = false
                initMarketCustomerList(1)

                binding.customerAssign.isClickable = true
            }
        })

        //客户筛选事件监听，为优化体验，当客户筛选界面打开时，设置搜索框不可用
        binding.customerSift.setOnClickListener {
            if (showSift) {
                binding.customerSift.setBackgroundResource(R.color.white)

                binding.customerAssign.isClickable = true
                titleBinding.searchText.isEnabled = true

                supportFragmentManager.popBackStack()
                showSift = false
            } else {

                //点击隐藏软键盘
                val inputMethodManager =
                    this.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                if (inputMethodManager.isActive) {
                    inputMethodManager.hideSoftInputFromWindow(this.window.decorView.windowToken, 0)
                }

                binding.customerSift.setBackgroundResource(R.color.background_color)

                binding.customerAssign.isClickable = false
                titleBinding.searchText.isEnabled = false

                val bundle = Bundle().apply {
                    putString("business", marketCustomerRequest.business)
                    putInt("lvlId", marketCustomerRequest.lvlid)
                    putInt("category", marketCustomerRequest.category)
                    putString("userId", marketCustomerRequest.userid)
                    putInt("range", marketCustomerRequest.range)
                }

                val customerSiftFragment = CustomerSiftFragment().apply {
                    arguments = bundle
                }

                supportFragmentManager.beginTransaction()
                    .add(R.id.container, customerSiftFragment).addToBackStack(null).commit()
                showSift = true
            }
        }

        binding.customerAssign.setOnClickListener {

            //点击隐藏软键盘
            val inputMethodManager =
                this.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            if (inputMethodManager.isActive) {
                inputMethodManager.hideSoftInputFromWindow(this.window.decorView.windowToken, 0)
            }

            if (!OASystem.authorization(OASystem.MARKET_CUSTOMER, OASystem.PROCESS)) {
                showMessage(resources.getString(R.string.permission_denied))
                return@setOnClickListener
            }

            if (isAssign) {
                isAssign = false
                binding.customerAssign.apply {
                    text = resources.getString(R.string.customer_assign)
                    setBackgroundResource(R.color.white)
                }

                initList()

                binding.commitView.visibility = View.GONE

                //清空客户ID list，将选中全部取消
                for (item in marketCustomerListItemList) {
                    if (item.isChecked) {
                        item.isChecked = false
                    }
                }

                customerIdList.clear()

            } else {
                isAssign = true
                binding.customerAssign.apply {
                    text = resources.getString(R.string.assign_cancel)
                    setBackgroundResource(R.color.background_color)
                }

                initList()

                binding.commitView.visibility = View.VISIBLE
            }
        }

        binding.addNewCustomer.setOnClickListener {

            if (!OASystem.authorization(OASystem.MARKET_CUSTOMER, OASystem.ADD)) {
                showMessage(resources.getString(R.string.permission_denied))
                return@setOnClickListener
            }

            val intent = Intent(OASystem.context, AddNewCustomerActivity::class.java)
            startActivity(intent)
        }

        binding.commit.setOnClickListener {
            if (customerIdList.size == 0) {
                showMessage(resources.getString(R.string.customer_assign_select_hint))
                return@setOnClickListener
            }

            initSiftListPopupWindow()
        }
    }

    private fun initCustomerSiftList() {
        apiService.marketCustomerQuerySelectData(CompanyCustomerBaseDataRequest())
            .enqueue(object : Callback<MarketCustomerSiftListResponse> {
                override fun onResponse(
                    call: Call<MarketCustomerSiftListResponse>,
                    response: Response<MarketCustomerSiftListResponse>
                ) {
                    val siftListResponse = response.body()
                    if (siftListResponse != null) {
                        if (siftListResponse.code == 200) {

                            OASystem.customerManager = siftListResponse.data.users
                            OASystem.customerLevel = siftListResponse.data.level
                            OASystem.customerClass = siftListResponse.data.customerClass
                            OASystem.serviceClass = siftListResponse.data.serviceClass
                            OASystem.province = siftListResponse.data.provinceClass

                            initViews()

                            initEvents()

                        } else {
                            showMessage(siftListResponse.msg)
                        }
                    }
                }

                override fun onFailure(call: Call<MarketCustomerSiftListResponse>, t: Throwable) {
                    showErrorInfo(R.string.base_resource_data_get_failed)
                }
            })
    }

    private fun initMarketCustomerList(type: Int) {

        apiService.queryNewClientData(marketCustomerRequest)
            .enqueue(object : Callback<MarketCustomerResponse> {
                override fun onResponse(
                    call: Call<MarketCustomerResponse>,
                    response: Response<MarketCustomerResponse>
                ) {
                    val marketCustomerResponse = response.body()

                    if (marketCustomerResponse != null) {
                        if (marketCustomerResponse.code == 200) {
                            for (item in marketCustomerResponse.data.pageSource) {
                                marketCustomerListItemList.add(item)
                            }

                            if (marketCustomerListItemList.size == 0) {
                                showMessage(resources.getString(R.string.no_data))
                            }

                            when (type) {
                                1 -> {
                                    totalPage = marketCustomerResponse.data.totalPage
                                    binding.resourceListContainer.setEnableLoadMore(pageIndex < totalPage)
                                    initList()
                                    listInit = true
                                }

                                2 -> {
                                    binding.resourceListContainer.finishRefresh()
                                    totalPage = marketCustomerResponse.data.totalPage
                                    binding.resourceListContainer.setEnableLoadMore(pageIndex < totalPage)
                                    initList()
                                    listInit = true
                                }

                                3 -> {
                                    binding.resourceListContainer.finishLoadMore()
                                    binding.resourceListContainer.setEnableLoadMore(pageIndex < totalPage)
                                    binding.marketCustomerList.adapter!!.notifyItemInserted(
                                        marketCustomerListItemList.size
                                    )
                                    listInit = true
                                }
                            }
                        } else {
                            showMessage(marketCustomerResponse.msg)
                        }
                    }
                }

                override fun onFailure(call: Call<MarketCustomerResponse>, t: Throwable) {
                    showErrorInfo(R.string.market_customer_list_get_failed)
                }

            })
    }

    private fun initList() {
        val layoutManager = LinearLayoutManager(this)
        binding.marketCustomerList.layoutManager = layoutManager

        adapter = MarketCustomerListAdapter(marketCustomerListItemList)

        adapter.isEnableMultiselectMode = isAssign

        binding.marketCustomerList.adapter = adapter

        adapter.onRecyclerViewItemClick =
            object : MarketCustomerListAdapter.OnRecyclerViewItemClick<MarketCustomer> {
                override fun onItemClick(position: Int) {
                    if (adapter.isEnableMultiselectMode) {
                        //如果该客户被选中，择加入客户ID list，如果取消选中，从ID list中删除
                        if (marketCustomerListItemList[position].isChecked) {
                            customerIdList.remove(marketCustomerListItemList[position].id)
                            marketCustomerListItemList[position].isChecked = false
                        } else {
                            customerIdList.add(marketCustomerListItemList[position].id)
                            marketCustomerListItemList[position].isChecked = true
                        }
                    } else {
                        val intent = Intent(OASystem.context, AddNewCustomerActivity::class.java)
                        intent.putExtra("id", marketCustomerListItemList[position].id)
                        intent.putExtra("fromList", true)
                        startActivity(intent)
                    }
                }
            }

        binding.resourceListContainer.setOnRefreshLoadMoreListener(object :
            OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                pageIndex = 1
                marketCustomerRequest.pageIndex = pageIndex
                binding.marketCustomerList.adapter!!.notifyItemRangeRemoved(0, marketCustomerListItemList.size)
                marketCustomerListItemList.clear()
                listInit = false
                initMarketCustomerList(2)
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                if (pageIndex < totalPage) {
                    pageIndex += 1
                    marketCustomerRequest.pageIndex = pageIndex
                    listInit = false
                    initMarketCustomerList(3)
                }
            }
        })
    }

    private fun initSiftListPopupWindow() {

        customerManager.clear()
        customerManagerList.clear()

        //准备数据源
        for (item in OASystem.customerManager) {
            item.isChecked = false
            customerManager.add(item)
        }

        popView = View.inflate(this, R.layout.popup_multi_item_selector, null)
        popupWindow = PopupWindow(
            popView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT
        )

        showPopupWindow {

            //初始化RecyclerView
            val selector: RecyclerView = popView.findViewById(R.id.selector_list)

            val adapter = ListAdapter.Builder<SiftListItem>().setData(customerManager)
                .setLayoutId(R.layout.item_customer_sift).addBindView { itemView, data ->

                    itemView.findViewById<CheckedTextView>(R.id.customer_sift).apply {
                        isChecked = data.isChecked
                        text = data.name
                    }

                }.create()

            val layoutManager = StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL)

            selector.layoutManager = layoutManager
            selector.adapter = adapter

            adapter.onRecyclerViewItemClick =
                object : ListAdapter.OnRecyclerViewItemClick<SiftListItem> {
                    override fun onItemClick(position: Int) {

                        customerManager[position].apply {

                            if (isChecked) {
                                isChecked = false
                                customerManagerList.removeAt(id)

                            } else {
                                isChecked = true
                                customerManagerList.add(id)
                            }

                            adapter.notifyItemChanged(position)
                        }
                    }
                }

            popView.findViewById<TextView>(R.id.commit).setOnClickListener {
                updateCustomerManager()
            }

            popupWindow.showAtLocation(binding.root, Gravity.BOTTOM, 0, 0)
        }
    }

    private fun updateCustomerManager() {
        apiService.customerBatchAssignment(
            BatchAssignmentRequest(
                customerIdList, customerManagerList
            )
        ).enqueue(object : Callback<BaseResponse> {
            override fun onResponse(call: Call<BaseResponse>, response: Response<BaseResponse>) {
                val assignmentResponse = response.body()

                if (assignmentResponse != null) {
                    if (assignmentResponse.code == 200) {
                        showMessage(resources.getString(R.string.customer_assign_success))
                        popupWindow.dismiss()

                        customerIdList.clear()
                        customerManagerList.clear()

                        //清空客户ID list，将选中全部取消
                        for (item in marketCustomerListItemList) {
                            if (item.isChecked) {
                                item.isChecked = false
                            }
                        }

                        initList()

                    } else {
                        showMessage(assignmentResponse.msg)
                    }
                }
            }

            override fun onFailure(call: Call<BaseResponse>, t: Throwable) {
                showErrorInfo(R.string.update_error)
            }
        })
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun searchWithCondition(marketCustomerRequest: MarketCustomerRequest) {
        binding.customerSift.setBackgroundResource(R.color.white)
        supportFragmentManager.popBackStack()
        showSift = false

        marketCustomerRequest.pageIndex = 1
        marketCustomerRequest.pageSize = 10

        this.marketCustomerRequest = marketCustomerRequest

        if (!titleBinding.searchText.text.isNullOrBlank()) {
            this.marketCustomerRequest.client = titleBinding.searchText.text.toString()
        }

        pageIndex = 1
        binding.marketCustomerList.adapter!!.notifyItemRangeRemoved(0, marketCustomerListItemList.size)
        marketCustomerListItemList.clear()
        listInit = false
        initMarketCustomerList(1)

        binding.customerAssign.isClickable = true
        titleBinding.searchText.isEnabled = true
    }
}