package com.casic.br.view

import android.graphics.Color
import android.util.Log
import androidx.lifecycle.ViewModelProvider
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.casic.br.R
import com.casic.br.callback.OnImageCompressListener
import com.casic.br.extensions.combineImagePath
import com.casic.br.extensions.compressImage
import com.casic.br.model.UserDetailModel
import com.casic.br.utils.*
import com.casic.br.vm.UploadFileViewModel
import com.casic.br.vm.UserViewModel
import com.github.gzuliyujiang.wheelpicker.BirthdayPicker
import com.gyf.immersionbar.ImmersionBar
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.pengxh.kt.lite.base.KotlinBaseActivity
import com.pengxh.kt.lite.extensions.*
import com.pengxh.kt.lite.utils.ImmerseStatusBarUtil
import com.pengxh.kt.lite.utils.SaveKeyValues
import com.pengxh.kt.lite.vm.LoadState
import com.pengxh.kt.lite.widget.dialog.AlertInputDialog
import com.pengxh.kt.lite.widget.dialog.BottomActionSheet
import kotlinx.android.synthetic.main.activity_edit_user.*
import java.io.File
import java.util.*


class EditUserActivity : KotlinBaseActivity() {

    private val kTag = "EditUserActivity"
    private val context = this@EditUserActivity
    private lateinit var uploadFileViewModel: UploadFileViewModel
    private lateinit var userViewModel: UserViewModel
    private lateinit var currentUser: UserDetailModel.DataModel

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

    override fun setupTopBarLayout() {
        ImmersionBar.with(this).statusBarDarkFont(true).init()
        ImmerseStatusBarUtil.setColor(this, R.color.white.convertColor(this))

        leftBackView.setOnClickListener { finish() }
    }

    override fun initData() {
        uploadFileViewModel = ViewModelProvider(this)[UploadFileViewModel::class.java]
        userViewModel = ViewModelProvider(this)[UserViewModel::class.java]

        currentUser = DeserializeModel.getUserModel() ?: return
        userViewModel.obtainUserDetail(currentUser.account)
        userViewModel.userDetailResult.observe(this, { user ->
            if (user.code == 200) {
                SaveKeyValues.putValue(LocaleConstant.USER_MODEL, user.toJson())
                currentUser = user.data
                if (currentUser.avatar == "") {
                    Glide.with(this)
                        .load(R.mipmap.ic_launcher)
                        .apply(RequestOptions.circleCropTransform())
                        .placeholder(R.mipmap.load_image_error)
                        .into(userAvatarView)
                } else {
                    Glide.with(this)
                        .load(currentUser.avatar.combineImagePath())
                        .apply(RequestOptions.circleCropTransform())
                        .placeholder(R.mipmap.load_image_error)
                        .into(userAvatarView)
                }
                userNameView.text = currentUser.name
                userPhoneView.text = currentUser.phone
                if (currentUser.sex.isBlank()) {
                    genderView.text = resources.getString(R.string.unknown)
                } else {
                    genderView.text = LocaleConstant.GENDER_ARRAY[(currentUser.sex).toInt() - 1]
                }
                birthdayView.text = currentUser.birthday
                calculateCompleteValue()
            }
        })
    }

    override fun initEvent() {
        changeAvatarView.setOnClickListener {
            BottomActionSheet.Builder()
                .setContext(this)
                .setActionItemTitle(listOf("拍照", "相册"))
                .setItemTextColor(Color.BLUE)
                .setOnActionSheetListener(object : BottomActionSheet.OnActionSheetListener {
                    override fun onActionItemClick(position: Int) {
                        when (position) {
                            0 -> {
                                PictureSelector.create(context)
                                    .openCamera(SelectMimeType.ofImage())
                                    .forResult(object : OnResultCallbackListener<LocalMedia> {
                                        override fun onResult(result: ArrayList<LocalMedia>?) {
                                            if (result == null) {
                                                "拍照保存失败，请重试".show(context)
                                                return
                                            }
                                            analyticalSelectResults(result[0])
                                        }

                                        override fun onCancel() {

                                        }
                                    })
                            }
                            1 -> {
                                PictureSelector.create(context)
                                    .openGallery(SelectMimeType.ofImage())
                                    .isGif(false)
                                    .isMaxSelectEnabledMask(true)
                                    .setFilterMinFileSize(100)
                                    .setMaxSelectNum(1)
                                    .isDisplayCamera(false)
                                    .setImageEngine(GlideLoadEngine.instance)
                                    .forResult(object : OnResultCallbackListener<LocalMedia> {
                                        override fun onResult(result: ArrayList<LocalMedia>?) {
                                            if (result == null) {
                                                "选择照片失败，请重试".show(context)
                                                return
                                            }
                                            analyticalSelectResults(result[0])
                                        }

                                        override fun onCancel() {

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

        uploadFileViewModel.resultModel.observe(this, {
            if (it.code == 200) {
                val url = it.data.fileId.toString()
                if (url.isNotBlank()) {
                    Glide.with(this)
                        .load(url.combineImagePath())
                        .apply(RequestOptions.circleCropTransform())
                        .placeholder(R.mipmap.load_image_error)
                        .into(userAvatarView)
                    currentUser.avatar = url
                    userViewModel.updateUserInfo(currentUser)
                }
            }
        })

        userNameLayout.setOnClickListener {
            AlertInputDialog.Builder()
                .setContext(this)
                .setTitle("修改用户名")
                .setHintMessage("请输入您的名字、昵称")
                .setNegativeButton("取消")
                .setPositiveButton("确定")
                .setOnDialogButtonClickListener(object :
                    AlertInputDialog.OnDialogButtonClickListener {
                    override fun onCancelClick() {

                    }

                    override fun onConfirmClick(value: String) {
                        //更新名字
                        currentUser.name = value
                        userViewModel.updateUserInfo(currentUser)
                        userNameView.text = value
                        calculateCompleteValue()
                    }
                })
                .build().show()
        }

        userPhoneLayout.setOnClickListener {
            AlertInputDialog.Builder()
                .setContext(this)
                .setTitle("修改登录手机号")
                .setHintMessage("请输入您新的手机号")
                .setNegativeButton("取消")
                .setPositiveButton("确定")
                .setOnDialogButtonClickListener(object :
                    AlertInputDialog.OnDialogButtonClickListener {
                    override fun onCancelClick() {

                    }

                    override fun onConfirmClick(value: String) {
                        //更新手机号
                        if (value.isPhoneNumber()) {
                            currentUser.phone = value
                            userViewModel.updateUserInfo(currentUser)
                            userPhoneView.text = value
                            calculateCompleteValue()
                        } else {
                            "无效手机号，请检查".show(context)
                        }
                    }
                })
                .build().show()
        }

        genderLayout.setOnClickListener {
            BottomActionSheet.Builder()
                .setContext(this)
                .setActionItemTitle(LocaleConstant.GENDER_ARRAY)
                .setItemTextColor(Color.BLUE)
                .setOnActionSheetListener(object : BottomActionSheet.OnActionSheetListener {
                    override fun onActionItemClick(position: Int) {
                        //更新性别
                        currentUser.sex = (position + 1).toString()
                        userViewModel.updateUserInfo(currentUser)
                        genderView.text = LocaleConstant.GENDER_ARRAY[position]
                        calculateCompleteValue()
                    }
                })
                .build().show()
        }

        birthdayLayout.setOnClickListener {
            val birthdayPicker = BirthdayPicker(this)
            birthdayPicker.setDefaultValue(1991, 8, 3)
            birthdayPicker.setOnDatePickedListener { year, month, day ->
                val birthdayDate = String.format("%s-%s-%s", year, month, day)
                //更新生日
                currentUser.birthday = birthdayDate
                userViewModel.updateUserInfo(currentUser)
                birthdayView.text = currentUser.birthday
                calculateCompleteValue()
            }
            val layout = birthdayPicker.wheelLayout
            layout.setTextSize(14f.sp2px(context).toFloat())
            layout.setSelectedTextSize(16f.sp2px(context).toFloat())
            layout.setSelectedTextColor(Color.BLUE)
            layout.setSelectedTextBold(true)
            layout.setResetWhenLinkage(false)
            birthdayPicker.show()
        }
    }

    /**
     * 计算个人信息完成度
     * */
    private fun calculateCompleteValue() {
        var value = 0
        if (userNameView.text.toString().isNotBlank()) {
            value += 25
        }
        if (userPhoneView.text.toString().isNotBlank()) {
            value += 25
        }
        if (genderView.text.toString().isNotBlank()) {
            value += 25
        }
        if (birthdayView.text.toString().isNotBlank()) {
            value += 25
        }
        userCompleteView.text = "资料完成度${value}%"
    }

    override fun observeRequestState() {
        uploadFileViewModel.loadState.observe(this, {
            when (it) {
                LoadState.Loading -> LoadingDialogHub.show(this, "头像上传中")
                else -> LoadingDialogHub.dismiss()
            }
        })

        userViewModel.loadState.observe(this, {
            when (it) {
                LoadState.Loading -> LoadingDialogHub.show(this, "信息修改中")
                else -> LoadingDialogHub.dismiss()
            }
        })
    }

    private fun analyticalSelectResults(result: LocalMedia) {
        //压缩图片后上传
        result.realPath.compressImage(this, object : OnImageCompressListener {
            override fun onSuccess(file: File) {
                Log.d(kTag, "onSuccess: " + file.absolutePath)
                //上传图片
                uploadFileViewModel.uploadImage(file)
            }

            override fun onError(e: Throwable) {
                e.printStackTrace()
            }
        })
    }
}