package com.casic.br.fragment

import android.graphics.Color
import androidx.lifecycle.ViewModelProvider
import com.bumptech.glide.Glide
import com.casic.br.R
import com.casic.br.adapter.ConnectGridAdapter
import com.casic.br.adapter.HomeGridAdapter
import com.casic.br.adapter.RecommendAdapter
import com.casic.br.extensions.combineImagePath
import com.casic.br.extensions.initLayoutImmersionBar
import com.casic.br.model.BannerImageModel
import com.casic.br.model.RecommendModel
import com.casic.br.utils.DeserializeModel
import com.casic.br.utils.GridItemDecoration
import com.casic.br.utils.LocaleConstant
import com.casic.br.view.LoginActivity
import com.casic.br.view.MainActivity
import com.casic.br.view.WebsiteActivity
import com.casic.br.view.home.*
import com.casic.br.vm.BannerViewModel
import com.pengxh.kt.lite.base.KotlinBaseFragment
import com.pengxh.kt.lite.extensions.navigatePageTo
import com.pengxh.kt.lite.utils.PageNavigationManager
import com.pengxh.kt.lite.utils.SaveKeyValues
import com.pengxh.kt.lite.widget.dialog.AlertControlDialog
import com.pengxh.kt.lite.widget.dialog.BottomActionSheet
import com.youth.banner.Banner
import com.youth.banner.adapter.BannerImageAdapter
import com.youth.banner.holder.BannerImageHolder
import com.youth.banner.indicator.CircleIndicator
import com.youth.banner.transformer.AlphaPageTransformer
import kotlinx.android.synthetic.main.activity_edit_user.*
import kotlinx.android.synthetic.main.fragment_home.*
import java.util.*

class HomePageFragment : KotlinBaseFragment() {

    private lateinit var bannerViewModel: BannerViewModel

    override fun initLayoutView(): Int = R.layout.fragment_home

    override fun setupTopBarLayout() {
        requireContext().initLayoutImmersionBar(rootView)
    }

    override fun initData() {
        bannerViewModel = ViewModelProvider(this)[BannerViewModel::class.java]
        //初始化轮播图
        initBanner()

        val homeAdapter = HomeGridAdapter(requireContext(), LocaleConstant.HOME_FUNC_OPERATE)
        homeRecyclerView.addItemDecoration(GridItemDecoration(requireContext()))
        homeRecyclerView.adapter = homeAdapter
        homeAdapter.setOnGridItemClickListener(object : HomeGridAdapter.OnGridItemClickListener {
            override fun onItemClick(position: Int) {
                when (position) {
                    0 -> if (DeserializeModel.isLogin()) {
                        requireContext().navigatePageTo<AccountManageActivity>()
                    } else {
                        requireContext().navigatePageTo<LoginActivity>()
                    }
                    1 -> if (DeserializeModel.isLogin()) {
                        requireContext().navigatePageTo<PaymentActivity>()
                    } else {
                        requireContext().navigatePageTo<LoginActivity>()
                    }
                    2 -> if (DeserializeModel.isLogin()) {
                        requireContext().navigatePageTo<HistoricalBillActivity>()
                    } else {
                        requireContext().navigatePageTo<LoginActivity>()
                    }
                    3 -> if (DeserializeModel.isLogin()) {
                        requireContext().navigatePageTo<GasAnalysisActivity>()
                    } else {
                        requireContext().navigatePageTo<LoginActivity>()
                    }
                    4 -> if (DeserializeModel.isLogin()) {
                        requireContext().navigatePageTo<ServiceNetworkActivity>()
                    } else {
                        requireContext().navigatePageTo<LoginActivity>()
                    }
                    5 -> if (DeserializeModel.isLogin()) {
                        requireContext().navigatePageTo<SubsidyActivity>()
                    } else {
                        requireContext().navigatePageTo<LoginActivity>()
                    }
                }
            }
        })

        val connectGridAdapter =
            ConnectGridAdapter(
                requireContext(), LocaleConstant.CONNECT_IMAGE, LocaleConstant.CONNECT_ARRAY
            )
        connectRecyclerView.addItemDecoration(GridItemDecoration(requireContext()))
        connectRecyclerView.adapter = connectGridAdapter
        connectGridAdapter.setOnGridItemClickListener(object :
            ConnectGridAdapter.OnGridItemClickListener {
            override fun onItemClick(position: Int) {
                when (position) {
                    0 -> callPhone(arrayListOf("010-96777"))
                    1 -> callPhone(arrayListOf("010-96777"))
                }
            }
        })

        //TODO 现为模拟数据，待后期调整
        val imageArray = arrayOf(
            "https://gw.alicdn.com/imgextra/i1/1638292152/O1CN01tMPitu1Rlf73Jrbsw_!!1638292152.jpg_Q75.jpg_.webp",
            "https://gw.alicdn.com/imgextra/i1/2286859561/O1CN01zrNz1S2KUzXGC5Qux_!!2286859561.jpg_Q75.jpg_.webp",
            "https://gw.alicdn.com/imgextra/i1/2438527556/O1CN01Q4yxYQ25ghLySaetu_!!2438527556.png_.webp"
        )
        val recommendModels = ArrayList<RecommendModel>()
        for (i in 0..2) {
            val model = RecommendModel()
            model.imageLink = imageArray[i]

            recommendModels.add(model)
        }
        val recommendAdapter = RecommendAdapter(requireContext(), recommendModels)
        recommendRecyclerView.adapter = recommendAdapter
        recommendAdapter.setOnItemClickListener(object : RecommendAdapter.OnItemClickListener {
            override fun onItemClick(position: Int) {

            }
        })
    }

    private fun callPhone(phoneNumber: ArrayList<String>) {
        BottomActionSheet.Builder()
            .setContext(requireContext())
            .setActionItemTitle(phoneNumber)
            .setItemTextColor(Color.BLUE)
            .setOnActionSheetListener(object : BottomActionSheet.OnActionSheetListener {
                override fun onActionItemClick(position: Int) {

                }
            })
            .build().show()
    }

    private fun initBanner() {
        bannerViewModel.obtainBanner("", "1")
        bannerViewModel.listModel.observe(this, {
            if (it.code == 200) {
                val banner = homeBannerView as Banner<BannerImageModel.DataModel.RowsModel,
                        BannerImageAdapter<BannerImageModel.DataModel.RowsModel>>
                banner.apply {
                    setAdapter(object :
                        BannerImageAdapter<BannerImageModel.DataModel.RowsModel>(it.data.rows) {
                        override fun onBindView(
                            holder: BannerImageHolder,
                            data: BannerImageModel.DataModel.RowsModel,
                            position: Int,
                            size: Int
                        ) {
                            Glide.with(holder.itemView)
                                .load(data.bannerPicture.combineImagePath())
                                .placeholder(R.mipmap.load_image_error)
                                .into(holder.imageView)
                        }
                    })
                    indicator = CircleIndicator(requireContext())
                    addPageTransformer(AlphaPageTransformer())
                    addBannerLifecycleObserver(this@HomePageFragment)

                    //Banner点击事件
                    setOnBannerListener { imageModel, _ ->
                        requireContext().navigatePageTo<WebsiteActivity>(imageModel.skipUrl)
                    }
                }
            }
        })
    }

    override fun observeRequestState() {

    }

    override fun initEvent() {
        rightOperateView.setOnClickListener {
            if (rightOperateView.text == "退出") {
                AlertControlDialog.Builder()
                    .setContext(requireContext())
                    .setTitle("退出确认")
                    .setMessage("退出当前账号，将不能同步数据")
                    .setNegativeButton("取消")
                    .setPositiveButton("确认退出")
                    .setOnDialogButtonClickListener(object :
                        AlertControlDialog.OnDialogButtonClickListener {
                        override fun onCancelClick() {

                        }

                        override fun onConfirmClick() {
                            SaveKeyValues.putValue(LocaleConstant.USER_IS_LOGIN, false)
                            requireContext().navigatePageTo<MainActivity>()
                            PageNavigationManager.finishAllActivity()
                        }
                    })
                    .build().show()
            } else {
                requireContext().navigatePageTo<LoginActivity>()
            }
        }
    }

    override fun onResume() {
        if (DeserializeModel.isLogin()) {
            rightOperateView.text = "退出"
        } else {
            rightOperateView.text = "登录"
        }
        super.onResume()
    }
}