package com.yidianling.user.ui.collect

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.support.v4.content.ContextCompat
import android.util.Log
import android.view.KeyEvent
import android.widget.NumberPicker
import android.widget.RelativeLayout
import com.ydl.webview.H5Params
import com.ydl.webview.NewH5Activity
import com.ydl.ydl_router.manager.YDLRouterManager
import com.ydl.ydl_router.manager.YDLRouterParams
import com.ydl.ydlcommon.base.BaseActivity
import com.ydl.ydlcommon.data.http.RxUtils
import com.ydl.ydlcommon.router.IYDLRouterConstant
import com.ydl.ydlcommon.utils.StatusBarUtils
import com.ydl.ydlcommon.utils.actionutil.ActionCountUtils
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.constants.UserBIConstants
import com.yidianling.user.http.UserHttpImpl
import com.yidianling.user.http.request.UserInfoCollectParam
import com.yidianling.user.http.request.UserInfoCollectUploadParam
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.user_activity_sex_birth_layout.*
import java.util.*


/**
 * 收集用户性别与出生年页面
 */

class CollectSexAndBirthActivity : BaseActivity() {

    private var selectedSex = -1 // 1 男 2 女
    private var selectedYear = 1995
    private var originYear = 1900
    private var nowYear: Int = 0
    private var collectOutDialog: YDLCommonDialog? = null
    private var yearList: ArrayList<String> = ArrayList()

    override fun initDataAndEvent() {

        ActionCountUtils.count(UserBIConstants.COLLECT_USER_INFO_PAGE + "|" + UserBIConstants.COLLECT_USER_INFO_PAGE_VISIT)

        sex_and_birth_upload_btn.setOnClickListener {
            // 只需要选择了性别即可点击上传数据，因为年份默认就是有选择的
            if (selectedSex != -1) {
                uploadSexAndBirth()
            } else {
                ToastUtil.toastShort("请选择性别")
            }
        }

        male_rl.setOnClickListener {
            if (selectedSex != 1) {
                selectedSex = 1
                checkUpSelect()
                ActionCountUtils.count(
                    UserBIConstants.COLLECT_USER_INFO_PAGE + "|" + UserBIConstants.COLLECT_USER_INFO_SEX_MAN_CLICK,
                    "1"
                )
            } else {
                selectedSex = -1
                checkUpSelect()
                ActionCountUtils.count(
                    UserBIConstants.COLLECT_USER_INFO_PAGE + "|" + UserBIConstants.COLLECT_USER_INFO_SEX_MAN_CLICK,
                    "2"
                )
            }
        }
        female_rl.setOnClickListener {
            if (selectedSex != 2) {
                selectedSex = 2
                checkUpSelect()
                ActionCountUtils.count(
                    UserBIConstants.COLLECT_USER_INFO_PAGE + "|" + UserBIConstants.COLLECT_USER_INFO_SEX_FEMALE_CLICK,
                    "1"
                )

            } else {
                selectedSex = -1
                checkUpSelect()
                ActionCountUtils.count(
                    UserBIConstants.COLLECT_USER_INFO_PAGE + "|" + UserBIConstants.COLLECT_USER_INFO_SEX_FEMALE_CLICK,
                    "2"
                )
            }
        }

        sex_and_birth_out.setOnClickListener {
            ActionCountUtils.count(UserBIConstants.COLLECT_USER_INFO_PAGE + "|" + UserBIConstants.COLLECT_USER_INFO_EXIT_CLICK)
            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()
        }
        //年份选择器
        val date = Calendar.getInstance()
        nowYear = date.get(Calendar.YEAR)
        while (originYear <= nowYear) {
            yearList.add("$originYear")
            originYear++
        }

        user_collect_date_pick.setDividerColor("#CCCCCC")
        user_collect_date_pick.setNumberPickerDividerHeight(1)

        user_collect_date_pick.post {
            if (user_collect_date_pick.measuredHeight > RxImageTool.dp2px(175f)) {
                val param = RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.MATCH_PARENT,
                    RxImageTool.dp2px(175f)
                )
                user_collect_date_pick.layoutParams = param

                user_collect_date_pick?.value = selectedYear

            }
        }

        user_collect_date_pick.displayedValues = yearList.toTypedArray()
        user_collect_date_pick.minValue = 1900
        user_collect_date_pick.maxValue = nowYear
        user_collect_date_pick.descendantFocusability =
            NumberPicker.FOCUS_BLOCK_DESCENDANTS // 关闭编辑功能
        user_collect_date_pick.wrapSelectorWheel = false // 关闭循环

        user_collect_date_pick.value = selectedYear

        //更新用户选择的年份
        user_collect_date_pick.setOnValueChangedListener { _, _, newVal -> selectedYear = newVal }
    }

    @SuppressLint("CheckResult")
    private fun uploadSexAndBirth() {

        ActionCountUtils.count(
            UserBIConstants.COLLECT_USER_INFO_PAGE + "|" + UserBIConstants.COLLECT_USER_INFO_NEXT_CLICK,
            "$selectedYear"
        )
        val userInfoBean = UserInfoCollectUploadParam()
        userInfoBean.userInfoList = ArrayList()
        userInfoBean.userInfoList.add(
            UserInfoCollectParam(
                if (selectedSex == 1) "男" else "女",
                "gener"
            )
        )
        userInfoBean.userInfoList.add(UserInfoCollectParam("$selectedYear", "age"))
        UserHttpImpl.getInstance().userInfoCollectUpload(userInfoBean)
            .compose(RxUtils.resultJavaData())
            .subscribeOn(Schedulers.newThread())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                CollectFocusActivity.start(this, nowYear - selectedYear <= 16)
                finish()
            }, {
                Log.i("上传数据异常", it.toString())
            })
    }

    @SuppressLint("CheckResult")
    private fun jumpToNewUserH5() {
        UserHttpImpl.getInstance().getNewUserJumpUrl()
            .compose(RxUtils.resultJavaData())
            .subscribeOn(Schedulers.newThread())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({
                if (!isFinishing) {
                    val h5Params = H5Params(
                        "$it?barHeight=" + StatusBarUtils.getStatusBarHeight(
                            this
                        ).toString(), H5Params.BackLimit.NEW_USER_PAGE, true
                    )
                    NewH5Activity.start(this, h5Params)
                    finish()
                }
            }, {
            })
    }

    @SuppressLint("ResourceAsColor")
    private fun checkUpSelect() {
        if (selectedSex == 1) {
            male_rl.setBackgroundResource(R.drawable.user_collect_select_bg)
            female_rl.setBackgroundResource(R.drawable.user_collect_unselect_bg)
            male_img.setImageResource(R.drawable.user_male_selected)
            female_img.setImageResource(R.drawable.user_female_unselected)
            male_txt.setTextColor(ContextCompat.getColor(mContext, R.color.platform_main_theme))
            female_txt.setTextColor(Color.parseColor("#242424"))

            sex_and_birth_upload_btn.setBackgroundResource(R.drawable.user_collect_bottom_btn_bg)
        } else if (selectedSex == 2) {
            male_rl.setBackgroundResource(R.drawable.user_collect_unselect_bg)
            female_rl.setBackgroundResource(R.drawable.user_collect_select_bg)
            male_img.setImageResource(R.drawable.user_male_unselected)
            female_img.setImageResource(R.drawable.user_female_selected)
            male_txt.setTextColor(Color.parseColor("#242424"))
            female_txt.setTextColor(ContextCompat.getColor(mContext, R.color.platform_main_theme))

            sex_and_birth_upload_btn.setBackgroundResource(R.drawable.user_collect_bottom_btn_bg)
        } else {
            male_rl.setBackgroundResource(R.drawable.user_collect_unselect_bg)
            female_rl.setBackgroundResource(R.drawable.user_collect_unselect_bg)
            male_img.setImageResource(R.drawable.user_male_unselected)
            female_img.setImageResource(R.drawable.user_female_unselected)
            male_txt.setTextColor(Color.parseColor("#242424"))
            female_txt.setTextColor(Color.parseColor("#242424"))

            sex_and_birth_upload_btn.setBackgroundResource(R.drawable.user_collect_bottom_btn_un_bg)
        }
    }

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

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