package com.cheng.blzb.ui.fragment.push.subscribe.add

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.provider.Settings
import android.text.TextUtils
import android.view.View
import android.view.animation.RotateAnimation
import com.cheng.blzb.R
import com.cheng.blzb.bean.AreaEntity
import com.cheng.blzb.bean.HotWordEntity
import com.cheng.blzb.bean.SourceEntity
import com.cheng.blzb.bean.SubscriptionEntity
import com.cheng.blzb.databinding.FragmentAddSubscribeBinding
import com.cheng.blzb.event.SourceDataEvent
import com.cheng.blzb.event.SubscriptionEvent
import com.cheng.blzb.manager.NotificationHelper
import com.cheng.blzb.manager.UserConfigManager
import com.cheng.blzb.ui.activity.PublicActivity
import com.cheng.blzb.ui.dialog.SelectAreaDialog
import com.cheng.blzb.ui.fragment.mine.vip.VipFragment
import com.cheng.blzb.ui.fragment.push.subscribe.source.SourceSearchFragment
import com.cheng.blzb.utils.PermissionUtils
import com.example.base.common.RxBus
import com.example.base.decoration.GridSpaceItemDecoration
import com.example.base.extensions.getColor
import com.example.base.extensions.gone
import com.example.base.extensions.invisible
import com.example.base.extensions.onClick
import com.example.base.extensions.toast
import com.example.base.extensions.visible
import com.example.base.ui.BaseFragment
import com.example.base.utils.DensityUtils
import com.example.base.utils.SpanUtils
import com.google.android.flexbox.FlexDirection
import com.google.android.flexbox.FlexWrap
import com.google.android.flexbox.FlexboxLayoutManager
import com.google.android.flexbox.JustifyContent
import com.google.gson.Gson
import com.google.gson.JsonObject
import okhttp3.RequestBody.Companion.toRequestBody


class AddSubscribeFragment : BaseFragment<FragmentAddSubscribeBinding, AddSubscribeViewModel>() {
    private val type by lazy { arguments?.getInt("type") ?: 1 } // 1 地区 2 数据源
    private var subscription: SubscriptionEntity? = null

    private val selectedKeywordAdapter by lazy { SelectedKeywordAdapter() }
    private val keywordAdapter by lazy { RecommendKeywordAdapter() }

    private val selectedCity = arrayListOf<AreaEntity>()
    private val selectedSource = arrayListOf<SourceEntity>()

    private var pushType = 3 //1 短信 2 邮箱 3 app推送

    override fun initView() {
        super.initView()
        mTitleBar?.setBackgroundColor(Color.WHITE)

        val layoutManager = FlexboxLayoutManager(requireContext())
        layoutManager.flexDirection = FlexDirection.ROW
        layoutManager.flexWrap = FlexWrap.WRAP
        layoutManager.justifyContent = JustifyContent.FLEX_START
        binding.rvSelectedKeywords.layoutManager = layoutManager
        binding.rvSelectedKeywords.adapter = selectedKeywordAdapter

        binding.rvKeywords.adapter = keywordAdapter
        binding.rvKeywords.addItemDecoration(GridSpaceItemDecoration(3, DensityUtils.dp2px(10f), DensityUtils.dp2px(10f)))
    }

    override fun initData() {
        super.initData()
        subscription = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            arguments?.getSerializable("item", SubscriptionEntity::class.java)
        } else {
            arguments?.getSerializable("item") as? SubscriptionEntity
        }
        setData()

        mViewModel.getKeywords("")
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun initListener() {
        super.initListener()

        binding.tvArea.onClick {
            val f = SelectAreaDialog.newInstance(selectedCity)
            f.setOnSelectListener { list ->
                selectedCity.clear()
                list.forEach { item -> selectedCity.add(item) }
                binding.tvArea.text =
                    if (selectedCity.size == UserConfigManager.getCityList().size) "全国" else selectedCity.joinToString(",") { it.name }
            }
            f.show(childFragmentManager, "")
        }

        binding.tvSource.onClick {
            PublicActivity.start(requireContext(), SourceSearchFragment::class.java, Pair("list", Gson().toJson(selectedSource)))
        }

        binding.tvNotificationState.onClick {
            PermissionUtils.checkNotificationPermission(requireActivity()) { isGranted ->
                if (isGranted) {
                    updatePushType()
                } else {
                    try {
                        val intent = Intent()
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                        intent.setAction(Settings.ACTION_APP_NOTIFICATION_SETTINGS)
                        intent.putExtra(Settings.EXTRA_APP_PACKAGE, requireContext().packageName)
                        requireActivity().startActivity(intent)
                    } catch (e: Exception) {
                        toast("跳转失败：${e.message}")
                    }
                }
            }
        }

        binding.layoutRefresh.onClick {
            startRotate()
            mViewModel.getKeywords(if (keywordAdapter.data.isNotEmpty()) keywordAdapter.data.last().name else "")
        }

        binding.tvAddKeywords.onClick {
            val keyword = binding.etKeyword.text.toString().trim()
            if (TextUtils.isEmpty(keyword)) {
                toast("请输入关键词")
                return@onClick
            }
            if (selectedKeywordAdapter.data.size == 5) {
                toast("最多添加5个关键词")
                return@onClick
            }
            selectedKeywordAdapter.addData(keyword)
            SpanUtils.with(binding.tvKeywordsCount)
                .append("${selectedKeywordAdapter.data.size}")
                .setForegroundColor(getColor(R.color.color_ff493c))
                .append("/5")
                .create()
            binding.etKeyword.setText("")
            binding.rvSelectedKeywords.visible()
        }

        selectedKeywordAdapter.setOnItemChildClickListener { _, view, i ->
            when (view.id) {
                R.id.iv_delete -> {
                    selectedKeywordAdapter.removeAt(i)
                    if (selectedKeywordAdapter.data.isEmpty()) {
                        binding.rvSelectedKeywords.gone()
                    }
                    SpanUtils.with(binding.tvKeywordsCount)
                        .append("${selectedKeywordAdapter.data.size}")
                        .setForegroundColor(getColor(R.color.color_ff493c))
                        .append("/5")
                        .create()
                }
            }
        }

        keywordAdapter.setOnItemClickListener { _, _, i ->
            val item = keywordAdapter.getItem(i)

            if (selectedKeywordAdapter.data.size == 5) {
                toast("最多添加5个关键词")
                return@setOnItemClickListener
            }
            if (selectedKeywordAdapter.data.contains(item.name)) {
                toast("关键词已存在")
                return@setOnItemClickListener
            }

            selectedKeywordAdapter.addData(item.name)
            SpanUtils.with(binding.tvKeywordsCount)
                .append("${selectedKeywordAdapter.data.size}")
                .setForegroundColor(getColor(R.color.color_ff493c))
                .append("/5")
                .create()
            binding.rvSelectedKeywords.visible()
        }

        binding.rgPushType.setOnCheckedChangeListener { _, checkedId ->
            when (checkedId) {
                R.id.rb1 -> pushType = 1

                R.id.rb2 -> pushType = 2

                R.id.rb3 -> pushType = 3
            }
            updatePushType()
        }

        binding.tv1.onClick {
            binding.rb1.isChecked = true
        }

        binding.tv2.onClick {
            binding.rb2.isChecked = true
        }

        binding.tv3.onClick {
            binding.rb3.isChecked = true
        }

        binding.btnNext.onClick {
            val phone = binding.etPhone.text.toString()
            val email = binding.etEmail.text.toString()
            if ((!TextUtils.isEmpty(phone) && pushType == 1) || (!TextUtils.isEmpty(email) && pushType == 2) || type == 2) {
                mViewModel.checkAuth()
            } else {
                commit()
            }
        }
    }

    override fun initObserve() {
        super.initObserve()
        mViewModel.keywordsLiveData.observe(this) {
            val list = mutableListOf<HotWordEntity.Child>()
            it.forEach { keyword ->
                list.add(HotWordEntity.Child(name = keyword))
            }
            keywordAdapter.setList(list)
        }

        mViewModel.authLiveData.observe(this) {
            if (it.auth) {
                commit()
            } else {
                PublicActivity.start(requireContext(), VipFragment::class.java, Pair("origin", "subscribe"))
            }
        }

        mViewModel.addLiveData.observe(this) {
            toast(if (subscription == null) "添加成功" else "修改成功")
            RxBus.defaultInstance.post(SubscriptionEvent())
            requireActivity().finish()
        }

        val sourceEvent = RxBus.defaultInstance.toObservable(SourceDataEvent::class.java).subscribe {
            selectedSource.clear()
            selectedSource.addAll(it.list)
            SpanUtils.with(binding.tvSource)
                .append("已增加 (")
                .append("${selectedSource.size}")
                .setForegroundColor(getColor(R.color.color_ff493c))
                .append("/5)")
                .create()
        }
        addDisposable(sourceEvent)
    }

    private fun commit() {
        val name = binding.etName.text.toString().trim()
        val phone = binding.etPhone.text.toString()
        val email = binding.etEmail.text.toString()
        if (type == 1 && selectedCity.isEmpty()) {
            toast("请选择订阅地区")
            return
        }
        if (type == 2 && selectedSource.isEmpty()) {
            toast("请选择数据源")
            return
        }
        if (selectedKeywordAdapter.data.isEmpty()) {
            toast("请添加关键词")
            return
        }
        if (pushType == 1 && TextUtils.isEmpty(phone)) {
            toast("请输入订阅手机号")
            return
        }
        if (pushType == 2 && TextUtils.isEmpty(email)) {
            toast("请输入订阅邮箱")
            return
        }

        val jsonObject = JsonObject()
        jsonObject.addProperty("name", if (!TextUtils.isEmpty(name)) name else "默认订阅")
        jsonObject.addProperty("keyword", selectedKeywordAdapter.data.joinToString(","))
        jsonObject.addProperty("push_type", "$pushType")
        jsonObject.addProperty("push_receiver", if (pushType == 1) phone else if (pushType == 2) email else "")
        if (type == 1) {
            jsonObject.addProperty("type", "1")
            jsonObject.addProperty("city_id", selectedCity.joinToString(",") { it.id.toString() })
            jsonObject.addProperty("source_id", "")

        } else {
            jsonObject.addProperty("type", "2")
            jsonObject.addProperty("source_id", selectedSource.joinToString(",") { it.id })
            jsonObject.addProperty("city_id", "")
        }
        if (subscription != null) {
            jsonObject.addProperty("id", subscription!!.id)
            mViewModel.updateSubscription(jsonObject.toString().toRequestBody())
        } else {
            mViewModel.addSubscription(jsonObject.toString().toRequestBody())
        }
    }

    private fun setData() {
        if (type == 1) {
            binding.tvTitle.text = "地区订阅"
            binding.ivVipTag.gone()
            binding.layoutArea.visible()
            binding.layoutSource.invisible()
            binding.ivVipTag1.visible()
            binding.ivVipTag2.visible()
        } else {
            binding.tvTitle.text = "数据源订阅"
            binding.ivVipTag.visible()
            binding.layoutArea.invisible()
            binding.layoutSource.visible()
            binding.ivVipTag1.gone()
            binding.ivVipTag2.gone()
        }

        if (subscription != null) {
            binding.etName.setText(subscription!!.name)

            val cityList = UserConfigManager.getCityList()
            subscription!!.city_id.forEach { id ->
                val city = cityList.find { it.id == id.toInt() }
                if (city != null) selectedCity.add(city)
            }
            binding.tvArea.text =
                if (subscription!!.city_name.size == UserConfigManager.getCityList().size) "全国" else subscription!!.city_name.joinToString(",")

            selectedSource.addAll(subscription!!.source)
            SpanUtils.with(binding.tvSource)
                .append("已增加 (")
                .append("${subscription!!.source.size}")
                .setForegroundColor(getColor(R.color.color_ff493c))
                .append("/5)")
                .create()

            selectedKeywordAdapter.setList(subscription!!.keyword)
            SpanUtils.with(binding.tvKeywordsCount)
                .append("${subscription!!.keyword.size}")
                .setForegroundColor(getColor(R.color.color_ff493c))
                .append("/5")
                .create()
            binding.rvSelectedKeywords.visibility = if (subscription!!.keyword.isNotEmpty()) View.VISIBLE else View.GONE

            pushType = if (!TextUtils.isEmpty(subscription!!.push_type)) subscription!!.push_type.toInt() else 3
            updatePushType(subscription!!.push_receiver)
        } else {
            SpanUtils.with(binding.tvSource)
                .append("已增加 (")
                .append("0")
                .setForegroundColor(getColor(R.color.color_ff493c))
                .append("/5)")
                .create()

            SpanUtils.with(binding.tvKeywordsCount)
                .append("0")
                .setForegroundColor(getColor(R.color.color_ff493c))
                .append("/5")
                .create()

            updatePushType()
        }
    }

    private fun updatePushType(receiver: String? = null) {
        when (pushType) {
            1 -> {
                binding.etPhone.setText(receiver)

                binding.etPhone.visible()
                binding.etEmail.gone()
                binding.layoutNotificationState.gone()
            }

            2 -> {
                binding.etEmail.setText(receiver)
                binding.etPhone.gone()
                binding.etEmail.visible()
                binding.layoutNotificationState.gone()
            }

            3 -> {
                if (NotificationHelper.isNotificationEnabled(requireContext())) {
                    binding.tvNotificationState.text = "已授权"
                } else {
                    binding.tvNotificationState.text = "点击授权"
                }

                binding.etPhone.gone()
                binding.etEmail.gone()
                binding.layoutNotificationState.visible()
            }
        }
    }

    private fun startRotate() {
        if (binding.ivRefreshKeywords.animation != null) {
            binding.ivRefreshKeywords.animation.cancel()
        }
        val anim = RotateAnimation(0f, 360f, RotateAnimation.RELATIVE_TO_SELF, 0.5f, RotateAnimation.RELATIVE_TO_SELF, 0.5f)
        anim.duration = 1000
        binding.ivRefreshKeywords.startAnimation(anim)
    }

    override fun onResume() {
        super.onResume()
        if (NotificationHelper.isNotificationEnabled(requireContext())) {
            binding.tvNotificationState.text = "已授权"
        } else {
            binding.tvNotificationState.text = "点击授权"
        }
    }
}