package com.yidianling.user.ui.collect

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.view.KeyEvent
import android.view.ViewGroup
import android.widget.LinearLayout
import com.ydl.webview.H5Params
import com.ydl.webview.NewH5Activity
import com.ydl.ydlcommon.base.BaseActivity
import com.ydl.ydlcommon.data.http.RxUtils
import com.ydl.ydlcommon.utils.StatusBarUtils
import com.ydl.ydlcommon.view.dialog.YDLCommonDialog
import com.yidianling.common.tools.RxImageTool
import com.yidianling.common.tools.ToastUtil
import com.yidianling.user.R
import com.yidianling.user.bean.CollectFocusItemBean
import com.yidianling.user.constants.UserBIConstants
import com.yidianling.user.http.UserHttpImpl
import com.yidianling.user.http.request.UserInfoCollectParam
import com.yidianling.user.http.request.UserInfoCollectUploadParam
import com.yidianling.user.ui.collect.dialog.CompleteCollectUserInfoDialog
import com.yidianling.user.ui.collect.widget.CollectFocusView
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.user_activity_focus_layout.*

/**
 * 收集用户关注问题页面
 */

class CollectFocusActivity : BaseActivity() {

    private var completeDialog: CompleteCollectUserInfoDialog? = null
    private var collectOutDialog: YDLCommonDialog? = null
    private var selectedNumber: Int = 0
    private var mList: ArrayList<CollectFocusItemBean> = ArrayList()

    private var isYfd: Boolean = false //是否是云凤蝶


    companion object {
        private const val IS_YFD = "is_yfd" //是否是云凤蝶key

        fun start(context: Context, isYFD: Boolean) {
            val intent = Intent(context, CollectFocusActivity::class.java)
            intent.putExtra(IS_YFD, isYFD)
            context.startActivity(intent)
        }
    }

    override fun initDataAndEvent() {

        isYfd = intent.getBooleanExtra(IS_YFD, false)


        // 获取关注数据
        getFocusData()

        //上传关注数据
        upload_focus_info_btn.setOnClickListener {
            uploadFocusData()

        }

        // 退出
        collect_focus_out_btn.setOnClickListener {
            if (null == collectOutDialog) {
                collectOutDialog =
                    YDLCommonDialog(this, object : YDLCommonDialog.OnYDLCommonDialogListener {
                        override fun onCancel() {
                            // 这是左侧按钮 - 确定
                            collectOutDialog?.dismiss()
                            jumpToNewUserH5()
                        }

                        override fun onSure() {
                            // 这是右侧按钮 - 取消
                            collectOutDialog?.dismiss()
                        }

                    }).setNullTitleDesc(
                        "确定要退出吗？\n" +
                                "很多人在这里得到了帮助哦"
                    ).setCancelText("确定").setSureText("取消")
            }
            collectOutDialog?.show()
        }
    }

    /**
     * 上传关注问题数据
     */
    @SuppressLint("CheckResult")
    private fun uploadFocusData() {
        if (selectedNumber > 0) {
            if (completeDialog == null) {
                completeDialog = CompleteCollectUserInfoDialog(this)
                completeDialog?.show()
            }

            val userInfoBean = UserInfoCollectUploadParam()
            userInfoBean.userInfoList = ArrayList()
            userInfoBean.userInfoList.add(
                UserInfoCollectParam(
                    mList.filter { it.isFocus }.map { it.id }.joinToString(","),
                    "consultAttention"
                )
            )
            UserHttpImpl.getInstance().userInfoCollectUpload(userInfoBean)
                .compose(RxUtils.resultJavaData())
                .subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe({
                    if (!isFinishing) {
                        jumpToNewUserH5()
                    }
                }, {
                    completeDialog?.dismiss()
                })
        } else {
            ToastUtil.toastShort("至少选择1项")
        }
    }

    /**
     * 获取关注数据
     */
    @SuppressLint("CheckResult")
    private fun getFocusData() {
        UserHttpImpl.getInstance().getFocusData()
            .compose(RxUtils.resultJavaData())
            .subscribeOn(Schedulers.newThread())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({ res ->
                if (res.isNotEmpty()) {
                    mList.addAll(res.filter { it.des.isNotEmpty() })
                    initScrollViewData()
                }
            }, {
            })
    }

    override fun layoutResId(): Int {
        return R.layout.user_activity_focus_layout
    }

    private fun initScrollViewData() {
        if (!this.isFinishing) {
            mList.forEachIndexed { index, item: CollectFocusItemBean ->
                if (index % 2 == 0) {
                    var ll = getHLinearLayout(this)
                    // 添加左侧布局
                    var leftItem = getLeftFocusItem()
                    leftItem.setData(item.cateName, item.des)
                    leftItem.setOnClickListener {
                        item.isFocus = !item.isFocus
                        leftItem.setFocus(item.isFocus)
                        calculateSelectedNumber(item.isFocus)

                    }
                    ll.addView(leftItem)
                    if (mList.lastIndex >= index + 1) {
                        // 添加右侧布局
                        var rightItem = getRightFocusItem()
                        rightItem.setData(mList[index + 1].cateName, mList[index + 1].des)
                        rightItem.setOnClickListener {
                            mList[index + 1].isFocus = !mList[index + 1].isFocus
                            rightItem.setFocus(mList[index + 1].isFocus)
                            calculateSelectedNumber(mList[index + 1].isFocus)

                        }
                        ll.addView(rightItem)
                    }

                    focus_scrollview_ll.addView(ll)
                }
            }
        }
    }

    private fun calculateSelectedNumber(isFocus: Boolean) {
        if (isFocus) {
            selectedNumber++
            upload_focus_info_btn.setBackgroundResource(R.drawable.user_collect_bottom_btn_bg)
        } else {
            selectedNumber--
            if (selectedNumber == 0) {
                upload_focus_info_btn.setBackgroundResource(R.drawable.user_collect_bottom_btn_un_bg)
            }
        }
    }

    private fun getLeftFocusItem(): CollectFocusView {
        var item = CollectFocusView(this)
        var params = item.layoutParams as ViewGroup.MarginLayoutParams
        params.setMargins(RxImageTool.dp2px(20f), 0, 0, 0)
        item.layoutParams = params

        return item
    }

    private fun getRightFocusItem(): CollectFocusView {
        var item = CollectFocusView(this)
        var params = item.layoutParams as ViewGroup.MarginLayoutParams
        params.setMargins(RxImageTool.dp2px(19f), 0, 0, 0)
        item.layoutParams = params

        return item
    }


    private fun getHLinearLayout(mContext: Context): LinearLayout {
        val params = LinearLayout.LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT
        )
        val ll = LinearLayout(mContext)
        ll.layoutParams = params
        var marginParams = ll.layoutParams as ViewGroup.MarginLayoutParams
        marginParams.setMargins(0, RxImageTool.dp2px(20f), 0, 0)
        ll.layoutParams = marginParams
        ll.orientation = LinearLayout.HORIZONTAL
        return ll
    }

    @SuppressLint("CheckResult")
    private fun jumpToNewUserH5() {
        var cateIds = mList.filter { it.isFocus }.map { it.id }.joinToString(",")
        UserHttpImpl.getInstance().getNewUserJumpUrl()
            .compose(RxUtils.resultJavaData())
            .subscribeOn(Schedulers.newThread())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                if (!isFinishing) {
                    upload_focus_info_btn.postDelayed({
                        completeDialog?.dismiss()
                        if (!isFinishing) {
                            val h5Params = H5Params(
                                "$it?cateIds=$cateIds&barHeight=" + StatusBarUtils.getStatusBarHeight(
                                    this
                                ).toString(), H5Params.BackLimit.NEW_USER_PAGE, true
                            )
                            NewH5Activity.start(this, h5Params)
                            finish()
                        }
                    }, 1000)
                }
            }, {
            })

    }

    /**
     * 当前页面不能退出
     */
    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return true
        }
        return super.onKeyDown(keyCode, event)
    }
}