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

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CheckedTextView
import android.widget.LinearLayout
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.pan_american.android.OASystem
import com.pan_american.android.R
import com.pan_american.android.base.BaseFragment
import com.pan_american.android.base.ListAdapter
import com.pan_american.android.data.model.common.adapter.SiftListAdapter
import com.pan_american.android.data.model.common.entity.Selector
import com.pan_american.android.data.model.common.entity.SiftListItem
import com.pan_american.android.data.model.common.network.SelectorResponse
import com.pan_american.android.data.model.customer_resource.company_customer.network.GroupInfoResponse
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.UpdateClientTypeRequest
import com.pan_american.android.data.model.customer_resource.company_customer.network.UpdateClientTypeResponse
import com.pan_american.android.data.network.APIService
import com.pan_american.android.data.network.ServiceCreator
import com.pan_american.android.databinding.FragmentCustomerFilterBinding
import org.greenrobot.eventbus.EventBus
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class CustomerSiftFragment : BaseFragment<FragmentCustomerFilterBinding>() {

    override fun getViewBinding(
        inflater: LayoutInflater, container: ViewGroup?, bundle: Bundle?
    ) = FragmentCustomerFilterBinding.inflate(inflater, container, false)

    //业务分类LinearLayout
    private lateinit var businessSiftPage: LinearLayout

    //客户等级LinearLayout
    private lateinit var customerLevelPage: LinearLayout

    //客户类别LinearLayout
    private lateinit var customerClassificationPage: LinearLayout

    //负责人LinearLayout
    private lateinit var directorPage: LinearLayout

    //省域LinearLayout
    private lateinit var provincePage: LinearLayout

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

    //业务分类数据模块(多选)
    private var serviceClass = ArrayList<SiftListItem>()
    private var serviceClassList = ArrayList<Int>()
    private var serviceClassAllSelect = true

    //客户级别数据模块
    private var customerLevel = ArrayList<Selector>()
    private var customerLevelPosition = -1
    private var lvlid = 0
    private var customerLevelAllSelect = true

    //客户类别数据模块
    private var customerClass = ArrayList<Selector>()
    private var customerClassPosition = -1
    private var category = 0
    private var customerClassAllSelect = true

    //负责人数据模块(多选)
    private var customerManager = ArrayList<SiftListItem>()
    private var managers = ArrayList<Int>()
    private var customerManagerAllSelect = true

    //省域数据模块
    private var provinceList = ArrayList<SiftListItem>()
    private var provincePosition = -1
    private var range = 0
    private var provinceAllSelect = true

    private var marketCustomerRequest = MarketCustomerRequest()

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

        //先获取出团数据，再初始化界面
        initDepartNumber()
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        requireArguments().getString("business")?.apply {
            if (isNotBlank()) {
                if (this.contains(",")) {
                    val itemList = this.split(",")
                    itemList.forEach {
                        serviceClassList.add(it.trim().toInt())
                    }
                } else {
                    serviceClassList.add(this.toInt())
                }
            }
        }

        lvlid = requireArguments().getInt("lvlId")

        category = requireArguments().getInt("category")

        requireArguments().getString("userId")?.apply {
            if (isNotBlank()) {
                if (this.contains(",")) {
                    val itemList = this.split(",")
                    itemList.forEach {
                        managers.add(it.trim().toInt())
                    }
                } else {
                    managers.add(this.toInt())
                }
            }
        }

        range = requireArguments().getInt("range")
    }

    override fun initViews() {

        //初始化右侧业务分类主界面LinearLayout
        businessSiftPage = binding.businessSiftPage

        //初始化右侧客户等级主界面LinearLayout
        customerLevelPage = binding.customerLevelPage

        //初始化右侧客户类别主界面LinearLayout
        customerClassificationPage = binding.customerClassificationPage

        //初始化右侧负责人主界面LinearLayout
        directorPage = binding.directorPage

        //初始化右侧省域主界面LinearLayout
        provincePage = binding.provincePage

        initProvince()

        if (OASystem.userInfo.userId != 21 && OASystem.userInfo.userId != 95) {
            binding.director.visibility = View.GONE
        }
    }

    override fun initEvents() {
        //设置左侧监听
        binding.siftMenu.setOnCheckedChangeListener { _, _ ->
            if (binding.businessSift.isChecked) {
                customerLevelPage.visibility = View.GONE
                customerClassificationPage.visibility = View.GONE
                directorPage.visibility = View.GONE
                provincePage.visibility = View.GONE
                businessSiftPage.visibility = View.VISIBLE

                initServiceClass()
            }
            if (binding.customerLevel.isChecked) {
                businessSiftPage.visibility = View.GONE
                customerClassificationPage.visibility = View.GONE
                directorPage.visibility = View.GONE
                provincePage.visibility = View.GONE
                customerLevelPage.visibility = View.VISIBLE

                initCustomerLevel()
            }
            if (binding.customerClassification.isChecked) {
                businessSiftPage.visibility = View.GONE
                customerLevelPage.visibility = View.GONE
                directorPage.visibility = View.GONE
                provincePage.visibility = View.GONE
                customerClassificationPage.visibility = View.VISIBLE

                initCustomerClass()
            }
            if (binding.director.isChecked) {
                businessSiftPage.visibility = View.GONE
                customerLevelPage.visibility = View.GONE
                customerClassificationPage.visibility = View.GONE
                provincePage.visibility = View.GONE
                directorPage.visibility = View.VISIBLE

                initCustomerManager()
            }
            if (binding.province.isChecked) {
                businessSiftPage.visibility = View.GONE
                customerLevelPage.visibility = View.GONE
                customerClassificationPage.visibility = View.GONE
                directorPage.visibility = View.GONE
                provincePage.visibility = View.VISIBLE

                initProvince()
            }
        }

        binding.reset.setOnClickListener {

            if (!serviceClassAllSelect) {
                binding.businessSiftAll.isChecked = true

                var i = 0
                serviceClass.forEach {
                    if (it.isChecked) {
                        it.isChecked = false
                        binding.businessSiftRecycle.adapter!!.notifyItemChanged(i)
                    }
                    i++
                }
            }

            serviceClassList.clear()

            if (!customerLevelAllSelect) {
                binding.customerLevelAll.isChecked = true
                customerLevel[customerLevelPosition].isChecked = false
                binding.customerLevelRecycle.adapter!!.notifyItemChanged(customerLevelPosition)
                customerLevelPosition = -1
            }

            lvlid = 0

            if (!customerClassAllSelect) {
                binding.customerClassificationAll.isChecked = true
                customerClass[customerClassPosition].isChecked = false
                binding.customerClassificationRecycle.adapter!!.notifyItemChanged(
                    customerClassPosition
                )
                customerClassPosition = -1
            }

            category = 0

            if (!customerManagerAllSelect) {
                binding.directorAll.isChecked = true

                var i = 0
                customerManager.forEach {
                    if (it.isChecked) {
                        it.isChecked = false
                        binding.directorRecycle.adapter!!.notifyItemChanged(i)
                    }
                    i++
                }
            }

            managers.clear()

            if (!provinceAllSelect) {
                if (!binding.provinceAll.isChecked) {
                    binding.provinceAll.isChecked = true
                    provinceList[provincePosition].isChecked = false
                    binding.provinceRecycle.adapter!!.notifyItemChanged(provincePosition)
                    provincePosition = -1
                }
            }

            range = 0

            showMessage(resources.getString(R.string.customer_sift_reset))
        }

        binding.commit.setOnClickListener {
            marketCustomerRequest.pageIndex = 1

            if (serviceClassList.size != 0) {
                marketCustomerRequest.business =
                    serviceClassList.toString().replace("[", "").replace("]", "")
            } else {
                marketCustomerRequest.business = ""
            }

            if (managers.size != 0) {
                marketCustomerRequest.userid = managers.toString().replace("[", "").replace("]", "")
            } else {
                marketCustomerRequest.userid = ""
            }

            marketCustomerRequest.category = category
            marketCustomerRequest.lvlid = lvlid
            marketCustomerRequest.range = range

            EventBus.getDefault().post(marketCustomerRequest)
        }
    }

    private fun initDepartNumber() {
        apiService.queryNumberGroups().enqueue(object : Callback<GroupInfoResponse> {
            override fun onResponse(
                call: Call<GroupInfoResponse>, response: Response<GroupInfoResponse>
            ) {
                val groupInfoResponse = response.body()
                if (groupInfoResponse != null) {
                    if (groupInfoResponse.code == 200) {
                        binding.predictGroup.text = groupInfoResponse.data.preDeleAll
                        binding.finishedGroup.text = groupInfoResponse.data.finlishedDeleAll

                        initData()
                        initViews()
                        initEvents()

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

            override fun onFailure(call: Call<GroupInfoResponse>, t: Throwable) {
                showMessage("网络错误，请检查网络设置")
            }
        })
    }

    private fun initData() {

        for (item in OASystem.customerLevel) {
            item.isChecked = false
            customerLevel.add(item)
        }

        for (item in OASystem.customerClass) {
            item.isChecked = false
            customerClass.add(item)
        }

        for (item in OASystem.customerManager) {
            item.isChecked = false
            customerManager.add(item)
        }

        for (item in OASystem.serviceClass) {
            item.isChecked = false
            serviceClass.add(item)
        }

        for (item in OASystem.province) {
            item.isChecked = false
            provinceList.add(item)
        }

    }

    private fun initServiceClass() {

        val getAll: CheckedTextView = binding.businessSiftAll

        val layoutManager = StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL)
        binding.businessSiftRecycle.layoutManager = layoutManager

        //初始化当前请求选中的选项
        if (serviceClassList.size == 0) {
            getAll.isChecked = true
            serviceClassAllSelect = true
        } else {
            serviceClass.forEach {
                if (serviceClassList.contains(it.id)) {
                    it.isChecked = true
                    serviceClassAllSelect = false
                }
            }
        }

        val adapter = SiftListAdapter(serviceClass, R.layout.item_customer_sift)
        binding.businessSiftRecycle.adapter = adapter

        //点击全选，其它项都重置为未选中状态
        getAll.setOnClickListener {
            if (!getAll.isChecked) {
                getAll.isChecked = true
                serviceClassAllSelect = true
                var i = 0
                serviceClass.forEach {
                    if (it.isChecked) {
                        it.isChecked = false
                        adapter.notifyItemChanged(i)
                    }
                    i++
                }
                serviceClassList.clear()
            }
        }

        adapter.onRecyclerViewItemClick =
            object : SiftListAdapter.OnRecyclerViewItemClick<SiftListItem> {
                override fun onItemClick(position: Int) {
                    //如果全选处于选中状态，则取消选中
                    if (getAll.isChecked) {
                        getAll.isChecked = false
                        serviceClassAllSelect = false
                    }
                    //如果没有子项被选中，选中全选
                    if (serviceClass[position].isChecked) {
                        serviceClassList.remove(serviceClass[position].id)
                        if (serviceClassList.size == 0) {
                            getAll.isChecked = true
                            serviceClassAllSelect = true
                        }
                    } else {
                        serviceClassList.add(serviceClass[position].id)
                    }
                }
            }
    }

    private fun initCustomerLevel() {

        val getAll: CheckedTextView = binding.customerLevelAll

        val layoutManager = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)
        binding.customerLevelRecycle.layoutManager = layoutManager

        //初始化当前请求选中的选项
        if (lvlid == 0) {
            getAll.isChecked = true
            customerLevelAllSelect = true
        } else {
            run breaking@{
                customerLevelPosition = 0
                customerLevel.forEach {
                    if (it.id == lvlid) {
                        it.isChecked = true
                        customerLevelAllSelect = false
                        return@breaking
                    }
                    customerLevelPosition++
                }
            }
        }

        val adapter = ListAdapter.Builder<Selector>().apply {
            setData(customerLevel)
            setLayoutId(R.layout.item_customer_sift)
            addBindView { itemView, data ->
                itemView.findViewById<CheckedTextView>(R.id.customer_sift).apply {
                    isChecked = data.isChecked
                    text = data.name
                }
            }
        }.create()

        binding.customerLevelRecycle.adapter = adapter

        //点击全选，其它项都置为未选中状态
        getAll.setOnClickListener {
            if (!getAll.isChecked) {
                getAll.isChecked = true
                customerLevelAllSelect = true
                customerLevel[customerLevelPosition].isChecked = false
                adapter.notifyItemChanged(customerLevelPosition)
                customerLevelPosition = -1
            }
        }

        adapter.onRecyclerViewItemClick = object : ListAdapter.OnRecyclerViewItemClick<Selector> {
            override fun onItemClick(position: Int) {
                //如果全选处于选中状态，则取消选中
                if (getAll.isChecked) {
                    getAll.isChecked = false
                    customerLevelAllSelect = false
                }

                customerLevel[position].apply {
                    if (isChecked) {
                        isChecked = false
                        adapter.notifyItemChanged(customerLevelPosition)
                        //再次点击选中的子项，子项设置为非选中，请求值为0，position清空为0，选中全部
                        lvlid = 0
                        customerLevelPosition = -1
                        getAll.isChecked = true
                        customerLevelAllSelect = true
                    } else {
                        isChecked = true
                        //点击未选中的子项，如果此前有选中其它项，其它项置为非选中
                        if (customerLevelPosition != -1) {
                            customerLevel[customerLevelPosition].isChecked = false
                            adapter.notifyItemChanged(customerLevelPosition)
                        }
                        lvlid = customerLevel[position].id
                        customerLevelPosition = position
                        adapter.notifyItemChanged(customerLevelPosition)
                    }
                }

                updateCustomerClass()
            }
        }
    }

    private fun initCustomerClass() {
        val getAll: CheckedTextView = binding.customerClassificationAll

        val layoutManager = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)
        binding.customerClassificationRecycle.layoutManager = layoutManager

        if (category == 0) {
            getAll.isChecked = true
            customerClassAllSelect = true
        } else {
            run breaking@{
                customerClassPosition = 0
                customerClass.forEach {
                    if (it.id == category) {
                        it.isChecked = true
                        customerClassAllSelect = false
                        return@breaking
                    }
                    customerLevelPosition++
                }
            }
        }

        val adapter = ListAdapter.Builder<Selector>().apply {
            setData(customerClass)
            setLayoutId(R.layout.item_customer_sift)
            addBindView { itemView, data ->
                itemView.findViewById<CheckedTextView>(R.id.customer_sift).apply {
                    isChecked = data.isChecked
                    text = data.name
                }
            }
        }.create()

        binding.customerClassificationRecycle.adapter = adapter

        //点击全选，其它项都置为未选中状态
        getAll.setOnClickListener {
            if (!getAll.isChecked) {
                getAll.isChecked = true
                customerClassAllSelect = true
                customerClass[customerClassPosition].isChecked = false
                adapter.notifyItemChanged(customerClassPosition)
                customerClassPosition = -1
            }
        }

        adapter.onRecyclerViewItemClick = object : ListAdapter.OnRecyclerViewItemClick<Selector> {
            override fun onItemClick(position: Int) {
                //如果全选处于选中状态，则取消选中
                if (getAll.isChecked) {
                    getAll.isChecked = false
                    customerClassAllSelect = false
                }

                customerClass[position].apply {
                    if (isChecked) {
                        isChecked = false
                        adapter.notifyItemChanged(customerClassPosition)
                        //再次点击选中的子项，子项设置为非选中，请求值为0，position清空为0，选中全部
                        category = 0
                        customerClassPosition = -1
                        getAll.isChecked = true
                        customerClassAllSelect = true
                    } else {
                        isChecked = true
                        //点击未选中的子项，如果此前有选中其它项，其它项置为非选中
                        if (customerClassPosition != -1) {
                            customerClass[customerClassPosition].isChecked = false
                            adapter.notifyItemChanged(customerClassPosition)
                        }
                        category = customerClass[position].id
                        customerClassPosition = position
                        adapter.notifyItemChanged(customerClassPosition)
                    }
                }
            }
        }
    }

    private fun initCustomerManager() {
        val getAll: CheckedTextView = binding.directorAll

        val layoutManager = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)
        binding.directorRecycle.layoutManager = layoutManager

        if (managers.size == 0) {
            getAll.isChecked = true
            customerManagerAllSelect = true
        } else {
            customerManager.forEach {
                if (managers.contains(it.id)) {
                    it.isChecked = true
                    customerManagerAllSelect = false
                }
            }
        }

        val adapter = SiftListAdapter(customerManager, R.layout.item_customer_sift)
        binding.directorRecycle.adapter = adapter

        //点击全选，其它项都重置为未选中状态
        getAll.setOnClickListener {
            if (!getAll.isChecked) {
                getAll.isChecked = true
                customerManagerAllSelect = true

                var i = 0
                customerManager.forEach {
                    if (it.isChecked) {
                        it.isChecked = false
                        adapter.notifyItemChanged(i)
                    }
                    i++
                }
                managers.clear()
            }
        }

        adapter.onRecyclerViewItemClick =
            object : SiftListAdapter.OnRecyclerViewItemClick<SiftListItem> {
                override fun onItemClick(position: Int) {
                    //如果全选处于选中状态，则取消选中
                    if (getAll.isChecked) {
                        getAll.isChecked = false
                        customerManagerAllSelect = false
                    }
                    if (customerManager[position].isChecked) {
                        managers.remove(customerManager[position].id)
                        if (managers.size == 0) {
                            getAll.isChecked = true
                            customerManagerAllSelect = true
                        }
                    } else {
                        managers.add(customerManager[position].id)
                    }
                }
            }
    }

    private fun initProvince() {
        val getAll: CheckedTextView = binding.provinceAll

        val layoutManager = StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL)
        binding.provinceRecycle.layoutManager = layoutManager

        if (range == 0) {
            getAll.isChecked = true
            provinceAllSelect = true
        } else {
            run breaking@{
                provincePosition = 0
                provinceList.forEach {
                    if (it.id == range) {
                        it.isChecked = true
                        provinceAllSelect = false
                        return@breaking
                    }
                    provincePosition++
                }
            }
        }

        val adapter = SiftListAdapter(provinceList, R.layout.item_customer_sift)
        binding.provinceRecycle.adapter = adapter

        //点击全选，其它项都重置为未选中状态
        getAll.setOnClickListener {
            if (!getAll.isChecked) {
                getAll.isChecked = true
                provinceAllSelect = true
                provinceList[provincePosition].isChecked = false
                adapter.notifyItemChanged(provincePosition)
                provincePosition = -1
            }
        }

        adapter.onRecyclerViewItemClick =
            object : SiftListAdapter.OnRecyclerViewItemClick<SiftListItem> {
                override fun onItemClick(position: Int) {
                    //如果全选处于选中状态，则取消选中
                    if (getAll.isChecked) {
                        getAll.isChecked = false
                        provinceAllSelect = false
                    }
                    if (provinceList[position].isChecked) {
                        //再次点击选中的子项，子项设置为非选中，请求值为0，position清空为0，选中全部
                        range = 0
                        provincePosition = -1
                        getAll.isChecked = true
                        provinceAllSelect = true
                    } else {
                        //点击未选中的子项，如果此前有选中其它项，其它项置为非选中
                        if (provincePosition != -1) {
                            provinceList[provincePosition].isChecked = false
                            adapter.notifyItemChanged(provincePosition)
                        }
                        range = provinceList[position].id
                        provincePosition = position
                    }

                    updateCustomerClassAndCustomerLevelList()
                }
            }
    }

    private fun updateCustomerClassAndCustomerLevelList() {
        apiService.updateClientTypeAndClassByProvince(UpdateClientTypeRequest(listOf(range))).enqueue(object : Callback<UpdateClientTypeResponse> {
            override fun onResponse(call: Call<UpdateClientTypeResponse>, response: Response<UpdateClientTypeResponse>) {
                val updateResponse = response.body()

                if (updateResponse != null) {
                    if (updateResponse.code == 200) {

                        customerClass.clear()
                        customerLevel.clear()

                        updateResponse.data.apply {
                            for (item in typeArr) {
                                customerClass.add(item)
                            }

                            for (item in lvArr) {
                                customerLevel.add(item)
                            }
                        }

                        lvlid = 0
                        category = 0

                        customerLevelPosition = -1
                        customerClassPosition = -1

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

            override fun onFailure(p0: Call<UpdateClientTypeResponse>, p1: Throwable) {
                showErrorInfo(R.string.interface_request_error)
            }
        })
    }

    private fun updateCustomerClass() {
        apiService.updateClientTypeList(UpdateClientTypeRequest(listOf(lvlid))).enqueue(object : Callback<SelectorResponse> {
            override fun onResponse(call: Call<SelectorResponse>, response: Response<SelectorResponse>) {
                val updateResponse = response.body()

                if (updateResponse != null) {
                    if (updateResponse.code == 200) {

                        customerClass.clear()

                        for (item in updateResponse.data) {
                            customerClass.add(item)
                        }

                        category = 0

                        customerClassPosition = -1

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

            override fun onFailure(p0: Call<SelectorResponse>, p1: Throwable) {
                showErrorInfo(R.string.interface_request_error)
            }
        })
    }
}