package com.halo.assistant.fragment.user.avatar

import android.app.Activity
import android.app.Dialog
import android.content.ActivityNotFoundException
import android.content.Intent
import android.os.Bundle
import android.provider.MediaStore
import android.text.TextUtils
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.core.os.bundleOf
import com.gh.common.util.NewFlatLogUtils
import com.gh.gamecenter.R
import com.gh.gamecenter.common.base.activity.BaseActivity
import com.gh.gamecenter.common.base.fragment.BaseDialogFragment
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.common.utils.PermissionHelper.checkStoragePermissionBeforeAction
import com.gh.gamecenter.common.utils.viewModelProvider
import com.gh.gamecenter.core.utils.SPUtils
import com.gh.gamecenter.core.utils.ToastUtils
import com.gh.gamecenter.databinding.DialogChangeAvatarBinding
import com.gh.gamecenter.login.user.UserViewModel
import com.halo.assistant.HaloApp
import com.halo.assistant.fragment.user.UserPortraitCropImageActivity
import com.lightgame.utils.Utils
import com.zhihu.matisse.internal.utils.PathUtils
import org.json.JSONException
import org.json.JSONObject
import java.text.SimpleDateFormat
import java.util.*

class ChangeAvatarDialog : BaseDialogFragment() {
    private lateinit var mBinding: DialogChangeAvatarBinding
    private var mUserViewModel: UserViewModel? = null
    private var mUploadAvatar = false

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        return DialogChangeAvatarBinding.inflate(layoutInflater, null, false).apply {
            mBinding = this
        }.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        mUserViewModel = viewModelProvider(UserViewModel.Factory(HaloApp.getInstance().application))
        mUserViewModel?.editObsUserinfo?.observe(this) {
            if (it != null && it.data != null && mUploadAvatar) {
                val tag = requireArguments().getString(EntranceConsts.KEY_PARENT_TAG)
                val intent = Intent().apply {
                    putExtra(EntranceConsts.KEY_DATA, it.data.icon)
                }
                requireActivity().supportFragmentManager.findFragmentByTag(tag)
                    ?.onActivityResult(REQUEST_CODE_UPLOAD_AVATAR, Activity.RESULT_OK, intent)
                dismissAllowingStateLoss()
            }
        }
        mBinding.localUploadTv.setOnClickListener {
            NewFlatLogUtils.logChangeAvatarDialogClick("手机上传")
            checkStoragePermissionBeforeAction(
                requireContext()
            ) { startMediaStore() }
        }
        mBinding.defaultTv.setOnClickListener {
            NewFlatLogUtils.logChangeAvatarDialogClick("默认头像")
            ChooseDefaultAvatarDialog.show(requireActivity() as AppCompatActivity, tag ?: "")
        }
        mBinding.cancelBtn.setOnClickListener {
            NewFlatLogUtils.logChangeAvatarDialogClick("关闭")
            dismissAllowingStateLoss()
        }
    }

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val createDialog = super.onCreateDialog(savedInstanceState)
        createDialog.setCanceledOnTouchOutside(true)
        val window = createDialog.window
        window?.setGravity(Gravity.BOTTOM)
        window?.setWindowAnimations(R.style.community_publication_animation)
        return createDialog
    }

    override fun onStart() {
        super.onStart()
        val width = HaloApp.getInstance().application.resources.displayMetrics.widthPixels
        val height = dialog?.window?.attributes?.height ?: ViewGroup.LayoutParams.WRAP_CONTENT
        dialog?.window?.setLayout(width, height)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK && data != null) {
            when (requestCode) {
                REQUEST_MEDIA_ICON -> {
                    val selectedImage = data.data ?: return
                    val picturePath = PathUtils.getPath(requireContext(), selectedImage)
                    Utils.log("picturePath = $picturePath")
                    // 上传头像
                    val intent = UserPortraitCropImageActivity.getIntent(
                        context,
                        picturePath, 1F, "我的光环(选择头像)"
                    )
                    startActivityForResult(intent, REQUEST_CROP_ICON)
                }
                REQUEST_CROP_ICON -> {
                    if (data.extras != null) {
                        val url = data.extras!!.getString(EntranceConsts.KEY_URL)
                        mUserViewModel?.changeUserInfo(url, UserViewModel.TYPE_PORTRAIT)
                        mUploadAvatar = true
                    }
                }
                ChooseDefaultAvatarDialog.REQUEST_CODE_DEFAULT_AVATAR -> {
                    val tag = requireArguments().getString(EntranceConsts.KEY_PARENT_TAG)
                    requireActivity().supportFragmentManager.findFragmentByTag(tag)
                        ?.onActivityResult(
                            ChooseDefaultAvatarDialog.REQUEST_CODE_DEFAULT_AVATAR,
                            Activity.RESULT_OK,
                            data
                        )
                    dismissAllowingStateLoss()
                }
            }
        }
    }

    private fun startMediaStore() {
        val iconCount: String = SPUtils.getString("updateIconCount")
        if (!TextUtils.isEmpty(iconCount)) {
            val l = System.currentTimeMillis()
            val format = SimpleDateFormat("yyyyMMdd", Locale.CHINA)
            val time = format.format(Date(l))
            val json: JSONObject
            try {
                json = JSONObject(iconCount)
                val lastTime = json.getString("time")
                if (lastTime == time && json.getInt("count") >= 2) {
                    ToastUtils.toast("每天最多只能上传2次头像")
                    return
                }
            } catch (e: JSONException) {
                e.printStackTrace()
            }
        }
        val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
        try {
            startActivityForResult(intent, REQUEST_MEDIA_ICON)
        } catch (e: ActivityNotFoundException) {
            Utils.toast(requireContext(), "找不到图片选择器")
        }
    }

    override fun onDarkModeChanged() {
        BaseActivity.updateStaticView(mBinding.root, emptyList())
    }

    companion object {
        const val REQUEST_CROP_ICON = 12
        const val REQUEST_MEDIA_ICON = 13
        const val REQUEST_CODE_UPLOAD_AVATAR = 100

        fun show(activity: AppCompatActivity, parentTag: String) {
            ChangeAvatarDialog().apply {
                arguments = bundleOf(
                    EntranceConsts.KEY_PARENT_TAG to parentTag
                )
            }.show(activity.supportFragmentManager, ChangeAvatarDialog::class.java.name)
        }
    }
}