package cn.muchinfo.rma.view.base.home

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Rect
import android.net.Uri
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import androidx.cardview.widget.CardView
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager.widget.PagerAdapter
import androidx.viewpager.widget.ViewPager
import cn.bingoogolapple.bgabanner.BGABanner
import cn.muchinfo.rma.R
import cn.muchinfo.rma.global.GlobalDataCollection
import cn.muchinfo.rma.global.data.NoticeData
import cn.muchinfo.rma.lifecycle.bindOptional
import cn.muchinfo.rma.view.autoWidget.*
import cn.muchinfo.rma.view.base.BaseFragment
import cn.muchinfo.rma.view.base.future.trade.GoodsTradeActivity
import cn.muchinfo.rma.view.base.home.business.BusinessManagementActivity
import cn.muchinfo.rma.view.base.home.commodity.CommodityInformationActivity
import cn.muchinfo.rma.view.base.home.contract.ContractActivity
import cn.muchinfo.rma.view.base.home.customerdata.CustomerDataActivity
import cn.muchinfo.rma.view.base.home.financial.FinancialActivity
import cn.muchinfo.rma.view.base.home.hedge.HedgePlanActivity
import cn.muchinfo.rma.view.base.home.reportquery.ReportQueryActivity
import cn.muchinfo.rma.view.base.home.tradingquery.TradingQueryActivity
import cn.muchinfo.rma.view.eventbus.EventConstent
import cn.muchinfo.rma.view.eventbus.MessageEvent
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.ConvertUtils
import com.blankj.utilcode.util.LogUtils
import com.facebook.drawee.view.SimpleDraweeView
import com.qmuiteam.qmui.util.QMUIDisplayHelper
import com.qmuiteam.qmui.widget.tab.QMUITabIndicator
import com.qmuiteam.qmui.widget.tab.QMUITabSegment

import mtp.polymer.com.autowidget.adapter.BaseAdapter
import mtp.polymer.com.autowidget.dialog.creatSelectAccountDialog
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

import org.jetbrains.anko.*
import org.jetbrains.anko.support.v4.UI
import org.jetbrains.anko.support.v4.viewPager

class HomeFragment : BaseFragment<HomeViewModel>() {

    companion object {
        fun newInstance() = HomeFragment()
    }

    private lateinit var statusLayout: StatusLayout
    lateinit var segment: QMUITabSegment
    lateinit var segment1: QMUITabSegment
    var selectedTabIndex: Int = 0
    private lateinit var viewPager: ViewPager
    private val announcementUI: AnnouncementUI by lazy { AnnouncementUI(this, viewModel) }//公告
    private val researchReportUI: ResearchReportUI by lazy { ResearchReportUI(this, viewModel) }//研报
    private val informationUI: InformationUI by lazy { InformationUI(this, viewModel) }//咨讯

    private val tabsArray: List<String> by lazy { arrayListOf("公告", "研报", "咨讯") }

    private val pagerAdapter: PagerAdapter by lazy {
        object : PagerAdapter() {

            override fun getPageTitle(position: Int): CharSequence? = tabsArray[position]

            override fun instantiateItem(container: ViewGroup, position: Int): Any {
                if (position == 0) {
                    return announcementUI.root.apply {
                        container.addView(this, ViewGroup.LayoutParams(matchParent, matchParent))
                    }
                } else if (position == 1) {
                    return researchReportUI.root.apply {
                        container.addView(this, ViewGroup.LayoutParams(matchParent, matchParent))
                    }
                } else if (position == 2) {
                    return informationUI.root.apply {
                        container.addView(this, ViewGroup.LayoutParams(matchParent, matchParent))
                    }
                }
                return super.instantiateItem(container, position)
            }

            override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
                (`object` as? View)?.let { container.removeView(it) }
            }

            override fun isViewFromObject(view: View, `object`: Any): Boolean = view == `object`

            override fun getCount(): Int = tabsArray.size

        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        EventBus.getDefault().register(this)
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(messageEvent : MessageEvent) {
        if (messageEvent.messageType == EventConstent.USERACCOUNTCHANGE){
            viewModel.initAccountData()
        }
    }


    @SuppressLint("SetTextI18n")
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return UI {
            // FIXME: - test
//            viewModel.login()
            viewModel.getBanner()

            verticalLayout {
                linearLayout {
                    background = resources.getDrawable(R.color.main_title_bg_color)
                    verticalLayout {
                        /** 资金账户选择 **/
                        onThrottleFirstClick {
                            (context as AppCompatActivity).creatSelectAccountDialog{
                                EventBus.getDefault().post(MessageEvent(EventConstent.USERACCOUNTCHANGE))
                            }.show()
                        }
                        textView {
                            viewModel.usedAccountData.bindOptional(context){
                                text = it?.accountname
                            }
                            text = GlobalDataCollection.instance?.loginRsp?.userID.toString()
                            textColorInt = R.color.white
                            textSizeAuto = 36
                        }.lparams(wrapContent, wrapContent) {
                            gravity = Gravity.CENTER_HORIZONTAL
                        }
                        textView {
                            viewModel.usedAccountData.bindOptional(context){
                                text = it?.accountname + "(" + it?.accountid + ")"
                            }
                            textColorStr = "#AED6F0"
                            textSizeAuto = 29
                        }.lparams(wrapContent, wrapContent) {
                            gravity = Gravity.CENTER_HORIZONTAL
                        }
                    }.lparams(autoSize(620), autoSize(90)) {
                        marginStart = autoSize(140)
                    }

                    imageView {
                        onThrottleFirstClick {
                            val intent = Intent()
                            intent.setClass(context, GoodsTradeActivity::class.java)
                            ActivityUtils.startActivity(intent)
                        }
                        imageResource = R.mipmap.main_search
                    }.lparams(autoSize(45), autoSize(45)) {
                        marginStart = autoSize(32)
                        topMargin = autoSize(20)
                    }

                }.lparams(matchParent, autoSize(120))

//                inflateLayout<NestedScrollView>(R.layout.view_home_scrollview) {
                relativeLayout {
                    nestedScrollView {
                        setOnScrollChangeListener(object : View.OnScrollChangeListener {
                            override fun onScrollChange(
                                p0: View?,
                                p1: Int,
                                p2: Int,
                                p3: Int,
                                p4: Int
                            ) {
                                val scrollRect = Rect()
                                getHitRect(scrollRect)
                                LogUtils.eTag("adakhsfkjahsfa", "x = " + p1 + "y = " + p2)
                                if (p2 > 1000) {
                                    segment1.visibility = View.VISIBLE
                                } else {
                                    segment1.visibility = View.INVISIBLE
                                }
                            }
                        })
                        verticalLayout {
                            background = resources.getDrawable(R.color.white)

                            imageView {
                                scaleType = ImageView.ScaleType.CENTER_CROP
                                imageResource = R.mipmap.banner
                            }.lparams(matchParent, autoSize(400))

                            inflateLayout<BGABanner>(R.layout.banner) {
                                visibility = View.GONE
                                // TODO 目前没有banner
//                                viewModel.bannerList.bindOptional(context) {
//                                    setData(
//                                        R.layout.item_fresco,
//                                        it,
//                                        null
//                                    )
//                                }


                                setAdapter(object : BGABanner.Adapter<CardView, String> {
                                    override fun fillBannerItem(
                                        banner: BGABanner?,
                                        itemView: CardView?,
                                        model: String?,
                                        position: Int
                                    ) {
                                        val simpleDraweeView: SimpleDraweeView =
                                            itemView!!.findViewById(R.id.sdv_item_fresco_content)
                                        simpleDraweeView.setImageURI(Uri.parse(model))
                                    }
                                })

                            }.lparams(matchParent, autoSize(400))

                            linearLayout {
                                verticalLayout {
                                    onThrottleFirstClick {
                                        val intent = Intent()
                                        intent.setClass(
                                            context,
                                            CustomerDataActivity::class.java
                                        )
                                        ActivityUtils.startActivity(intent)
                                    }
                                    imageView {
                                        imageResource = R.mipmap.main_business_1
                                    }.lparams(autoSize(72), autoSize(72)) {
                                        gravity = Gravity.CENTER_HORIZONTAL
                                    }

                                    textView {
                                        text = "客户资料"
                                        textColorInt = R.color.black
                                        textSizeAuto = 26
                                    }.lparams(wrapContent, wrapContent) {
                                        topMargin = autoSize(20)
                                        gravity = Gravity.CENTER_HORIZONTAL
                                    }
                                }.lparams(0, matchParent, 1f)

                                verticalLayout {
                                    onThrottleFirstClick {
                                        val intent = Intent()
                                        intent.setClass(
                                            context,
                                            CommodityInformationActivity::class.java
                                        )
                                        ActivityUtils.startActivity(intent)
                                    }
                                    imageView {
                                        imageResource = R.mipmap.main_business_2
                                    }.lparams(autoSize(72), autoSize(72)) {
                                        gravity = Gravity.CENTER_HORIZONTAL
                                    }

                                    textView {
                                        text = "商品信息"
                                        textColorInt = R.color.black
                                        textSizeAuto = 26
                                    }.lparams(wrapContent, wrapContent) {
                                        topMargin = autoSize(20)
                                        gravity = Gravity.CENTER_HORIZONTAL
                                    }
                                }.lparams(0, matchParent, 1f)
                                verticalLayout {
                                    onThrottleFirstClick {
                                        val intent = Intent()
                                        intent.setClass(context, ContractActivity::class.java)
                                        ActivityUtils.startActivity(intent)
                                    }
                                    imageView {
                                        imageResource = R.mipmap.main_business_3
                                    }.lparams(autoSize(72), autoSize(72)) {
                                        gravity = Gravity.CENTER_HORIZONTAL
                                    }

                                    textView {
                                        text = "现货合同"
                                        textColorInt = R.color.black
                                        textSizeAuto = 26
                                    }.lparams(wrapContent, wrapContent) {
                                        gravity = Gravity.CENTER_HORIZONTAL
                                        topMargin = autoSize(20)
                                    }
                                }.lparams(0, matchParent, 1f)
                                verticalLayout {
                                    onThrottleFirstClick {
                                        val intent = Intent()
                                        intent.setClass(context, HedgePlanActivity::class.java)
                                        ActivityUtils.startActivity(intent)
                                    }
                                    imageView {
                                        imageResource = R.mipmap.main_business_4
                                    }.lparams(autoSize(72), autoSize(72)) {
                                        gravity = Gravity.CENTER_HORIZONTAL
                                    }

                                    textView {
                                        text = "套保计划"
                                        textColorInt = R.color.black
                                        textSizeAuto = 26
                                    }.lparams(wrapContent, wrapContent) {
                                        gravity = Gravity.CENTER_HORIZONTAL
                                        topMargin = autoSize(20)
                                    }
                                }.lparams(0, matchParent, 1f)
                            }.lparams(matchParent, autoSize(140)) {
                                topMargin = autoSize(40)
                            }

                            linearLayout {
                                verticalLayout {

                                    onThrottleFirstClick {
                                        val intent = Intent()
                                        intent.setClass(
                                            context,
                                            BusinessManagementActivity::class.java
                                        )
                                        ActivityUtils.startActivity(intent)
                                    }
                                    imageView {
                                        imageResource = R.mipmap.main_business_5
                                    }.lparams(autoSize(72), autoSize(72)) {
                                        gravity = Gravity.CENTER_HORIZONTAL
                                    }

                                    textView {
                                        text = "业务管理"
                                        textColorInt = R.color.black
                                        textSizeAuto = 26
                                    }.lparams(wrapContent, wrapContent) {
                                        topMargin = autoSize(20)
                                        gravity = Gravity.CENTER_HORIZONTAL
                                    }
                                }.lparams(0, matchParent, 1f)

                                verticalLayout {
                                    onThrottleFirstClick {
                                        val intent = Intent()
                                        intent.setClass(context, FinancialActivity::class.java)
                                        ActivityUtils.startActivity(intent)
                                    }
                                    imageView {
                                        imageResource = R.mipmap.main_business_6
                                    }.lparams(autoSize(72), autoSize(72)) {
                                        gravity = Gravity.CENTER_HORIZONTAL
                                    }

                                    textView {
                                        text = "财务管理"
                                        textColorInt = R.color.black
                                        textSizeAuto = 26
                                    }.lparams(wrapContent, wrapContent) {
                                        topMargin = autoSize(20)
                                        gravity = Gravity.CENTER_HORIZONTAL
                                    }
                                }.lparams(0, matchParent, 1f)
                                verticalLayout {
                                    onThrottleFirstClick {
                                        val intent = Intent()
                                        intent.setClass(context,TradingQueryActivity::class.java)
                                        ActivityUtils.startActivity(intent)
                                    }
                                    imageView {
                                        imageResource = R.mipmap.main_business_7
                                    }.lparams(autoSize(72), autoSize(72)) {
                                        gravity = Gravity.CENTER_HORIZONTAL
                                    }

                                    textView {
                                        text = "交易查询"
                                        textColorInt = R.color.black
                                        textSizeAuto = 26
                                    }.lparams(wrapContent, wrapContent) {
                                        gravity = Gravity.CENTER_HORIZONTAL
                                        topMargin = autoSize(20)
                                    }
                                }.lparams(0, matchParent, 1f)
                                verticalLayout {
                                    onThrottleFirstClick {
                                        val intent = Intent()
                                        intent.setClass(context,ReportQueryActivity::class.java)
                                        ActivityUtils.startActivity(intent)
                                    }
                                    imageView {
                                        imageResource = R.mipmap.main_business_8
                                    }.lparams(autoSize(72), autoSize(72)) {
                                        gravity = Gravity.CENTER_HORIZONTAL
                                    }

                                    textView {
                                        text = "报表查询"
                                        textColorInt = R.color.black
                                        textSizeAuto = 26
                                    }.lparams(wrapContent, wrapContent) {
                                        gravity = Gravity.CENTER_HORIZONTAL
                                        topMargin = autoSize(20)
                                    }
                                }.lparams(0, matchParent, 1f)
                            }.lparams(matchParent, autoSize(140)) {
                                topMargin = autoSize(20)
                            }

                            view {
                                background = resources.getDrawable(R.color.main_hit_bg_color)
                            }.lparams(matchParent, autoSize(24)) {
                                topMargin = autoSize(64)
                            }


                            tabSegment {
                                segment = this
                                background = resources.getDrawable(R.color.white)
                                addOnTabSelectedListener(object :
                                    QMUITabSegment.OnTabSelectedListener {
                                    override fun onDoubleTap(index: Int) {}
                                    override fun onTabReselected(index: Int) {}
                                    override fun onTabUnselected(index: Int) {}
                                    override fun onTabSelected(index: Int) {
                                        selectedTabIndex = index
                                    }
                                })
                                setIndicator(
                                    QMUITabIndicator(
                                        QMUIDisplayHelper.dp2px(context, 2),
                                        false,
                                        true
                                    )
                                )
                                setDefaultTextSize(
                                    ConvertUtils.sp2px(16f),
                                    ConvertUtils.sp2px(16f)
                                )

                            }.lparams(matchParent, autoSize(100))

                            view {
                                background = resources.getDrawable(R.color.main_hit_bg_color)
                            }.lparams(matchParent, autoSize(1)) {
                                marginStart = autoSize(32)
                                marginEnd = autoSize(32)
                            }
                            viewPager {
                                background = resources.getDrawable(R.color.white)
                                viewPager = this
                                adapter = pagerAdapter
                            }.lparams(matchParent, autoSize(2000))

                            segment.setupWithViewPager(viewPager)
                            segment.selectTab(selectedTabIndex)
                        }
                    }.lparams(matchParent, matchParent)
                    tabSegment {
                        visibility = View.GONE
                        segment1 = this
                        visibility = View.INVISIBLE
                        background = resources.getDrawable(R.color.white)
                        addOnTabSelectedListener(object : QMUITabSegment.OnTabSelectedListener {
                            override fun onDoubleTap(index: Int) {}
                            override fun onTabReselected(index: Int) {}
                            override fun onTabUnselected(index: Int) {}
                            override fun onTabSelected(index: Int) {
                                selectedTabIndex = index
                            }
                        })
                        setIndicator(
                            QMUITabIndicator(
                                QMUIDisplayHelper.dp2px(context, 2),
                                false,
                                true
                            )
                        )
                        setDefaultTextSize(ConvertUtils.sp2px(16f), ConvertUtils.sp2px(16f))
//                        setHasIndicator(true)
//                        setDefaultNormalColor(Color.parseColor("#000000"))
//                        setDefaultSelectedColor(Color.parseColor("#60a1e3"))
//                        setTabTextSize(ConvertUtils.sp2px(16f))
                    }.lparams(matchParent, autoSize(100))

                    segment1.setupWithViewPager(viewPager)
                    segment1.selectTab(selectedTabIndex)
                }


//                }.lparams(matchParent, matchParent)
            }

        }.view
    }

}

/**
 * 公告
 */
class AnnouncementUI(private val baseFragment: Fragment, private val viewModule: HomeViewModel) {

    private lateinit var swipeToLayout: SwipeToLoadLayout
    private lateinit var statusLayout: StatusLayout

    lateinit var recyclerView: RecyclerView

    private val announcementAdapter: BaseAdapter<NoticeData, AnnouncementViewHolder> =
        BaseAdapter { _, _ -> AnnouncementViewHolder(baseFragment, viewModule) }

    val root = _FrameLayout(baseFragment.context!!).apply {
        verticalLayout {
            viewModule.queryNotice()
            statusLayout(contentBlock = {
                statusLayout = this
//                bindTaskStatus(viewModule.status)
                swipeToLoadLayout {
                    swipeToLayout = this
                    setEnableRefresh(false)
                    setEnableLoadMore(false)
                    setEnableScrollContentWhenLoaded(false)
                    setEnableLoadMoreWhenContentNotFull(false)
                    recyclerView {
                        background = resources.getDrawable(R.color.white)
                        adapter = announcementAdapter
                        isNestedScrollingEnabled = false
                    }.lparams(matchParent, matchParent) {
                        marginStart = autoSize(32)
                        marginEnd = autoSize(20)
                    }
                }
            }, emptyBlock = {
                emptyView(hint = resources.getString(R.string.now_no_data))
            }).lparams(matchParent, matchParent)
            viewModule.noticeDataList.bindOptional(context){
                announcementAdapter.setNewData(it)
            }
        }
    }
}


/**
 * 研报
 */
class ResearchReportUI(private val baseFragment: Fragment, private val viewModule: HomeViewModel) {
    val root = _FrameLayout(baseFragment.context!!).apply {
        verticalLayout {
            textView {
                text = "研报"
                textColorInt = R.color.black
                textSizeAuto = 100
            }.lparams(matchParent, wrapContent) {
                topMargin = autoSize(200)
            }
        }
    }
}


/**
 * 咨讯
 */

class InformationUI(private val baseFragment: Fragment, private val viewModule: HomeViewModel) {
    val root = _FrameLayout(baseFragment.context!!).apply {
        verticalLayout {
            textView {
                text = "咨讯"
                textColorInt = R.color.black
                textSizeAuto = 100
            }.lparams(matchParent, wrapContent) {
                topMargin = autoSize(200)
            }
        }
    }
}

