package com.halo.assistant.fragment.user

import android.content.ActivityNotFoundException
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.text.TextUtils
import android.view.View
import androidx.core.widget.doOnTextChanged
import androidx.fragment.app.viewModels
import com.gh.gamecenter.common.base.fragment.WaitingDialogFragment
import com.gh.common.util.*
import com.gh.gamecenter.R
import com.gh.gamecenter.common.constant.EntranceConsts
import com.gh.gamecenter.core.utils.EmptyCallback
import com.gh.gamecenter.common.utils.PermissionHelper
import com.gh.gamecenter.core.utils.ToastUtils
import com.gh.gamecenter.common.utils.enlargeTouchArea
import com.gh.gamecenter.common.utils.ImageUtils
import com.gh.gamecenter.databinding.FragmentManuallyRealNameBinding
import com.gh.gamecenter.login.entity.IdCardEntity
import com.gh.gamecenter.common.base.fragment.ToolbarFragment
import com.gh.gamecenter.common.utils.UploadImageUtils
import com.squareup.picasso.MemoryPolicy
import io.reactivex.disposables.Disposable

class ManuallyRealNameFragment : ToolbarFragment() {

    private var mDialog: WaitingDialogFragment? = null
    private var mDisposable: Disposable? = null

    private val mViewModel: ManuallyRealNameViewModel by viewModels()

    private val mBinding: FragmentManuallyRealNameBinding by lazy {
        FragmentManuallyRealNameBinding.inflate(layoutInflater)
    }

    override fun getLayoutId(): Int = 0
    override fun getInflatedLayout(): View = mBinding.root

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mViewModel.getCertificationReview()
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        mBinding.toolbar.normalTitle.text = "人工审核"
        mBinding.toolbar.normalToolbar.setNavigationOnClickListener { requireActivity().finish() }


        mViewModel.reviewLiveData.observe(viewLifecycleOwner) {
            if (it) {
                showSuccessView()
            } else {
                initView()
            }
        }

        mViewModel.resultLiveData.observe(viewLifecycleOwner) {
            if (it) showSuccessView()
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (data == null) return
        if (requestCode == REQUEST_IMAGE) {
            val selectedImage = data.data ?: return
            val filePathColumn = arrayOf(MediaStore.Images.Media.DATA)

            try {
                val cursor = requireContext().contentResolver.query(
                    selectedImage,
                    filePathColumn,
                    null,
                    null,
                    null
                ) ?: return

                cursor.moveToFirst()

                val columnIndex = cursor.getColumnIndex(filePathColumn[0])
                val picturePath = cursor.getString(columnIndex)
                cursor.close()

                uploadPicture(selectedImage, picturePath)
            } catch (e: Exception) {
                ToastUtils.showToast(e.localizedMessage ?: "")
            }
        }
    }

    private fun initView() {
        mBinding.imageIv.setOnClickListener {
            PermissionHelper.checkStoragePermissionBeforeAction(
                requireContext(),
                object : EmptyCallback {
                    override fun onCallback() {
                        selectImage()
                    }
                })
        }

        mBinding.clearIv.setOnClickListener {
            removeUploadedImage()
            updateSubmitBtn()
        }

        mBinding.nameEt.setText(arguments?.getString(EntranceConsts.KEY_NAME) ?: "")
        mBinding.idCardEt.setText(arguments?.getString(EntranceConsts.KEY_ID) ?: "")

        mBinding.nameEt.setSelection(mBinding.nameEt.text.length)
        mBinding.idCardEt.setSelection(mBinding.idCardEt.text.length)

        mBinding.nameEt.doOnTextChanged { _, _, _, _ ->
            updateSubmitBtn()
        }

        mBinding.idCardEt.doOnTextChanged { _, _, _, _ ->
            updateSubmitBtn()
        }

        mBinding.clearIv.visibility = View.GONE
        mBinding.contactTv.visibility = View.VISIBLE
        mBinding.contactTv.enlargeTouchArea()
        mBinding.contactTv.setOnClickListener {
            DirectUtils.directToQqConversation(it.context, RealNameInfoFragment.CONTACT_QQ)
        }
    }

    private fun updateSubmitBtn() {
        val validationPair =
            isInputValid(mBinding.nameEt.text.toString(), mBinding.idCardEt.text.toString())

        mBinding.submitBtn.isEnabled = validationPair.first
        if (validationPair.first) {
            mBinding.submitBtn.alpha = 1F
            mBinding.submitBtn.setOnClickListener {
                val idCardEntity = IdCardEntity(
                    id = mBinding.idCardEt.text.toString(),
                    name = mBinding.nameEt.text.toString(),
                    idPhoto = mViewModel.remoteImageUrl
                )

                mViewModel.postCertificationReview(idCardEntity)
            }
        } else {
            mBinding.submitBtn.alpha = 0.4F
        }
    }

    private fun selectImage() {
        try {
            val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
            startActivityForResult(intent, REQUEST_IMAGE)
        } catch (e: ActivityNotFoundException) {
            // https://stackoverflow.com/questions/45707678
            val getIntent = Intent(Intent.ACTION_GET_CONTENT)
            getIntent.type = "image/*"

            val pickIntent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
            pickIntent.type = "image/*"

            val chooserIntent = Intent.createChooser(getIntent, "Select Image")
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, arrayOf(pickIntent))

            startActivityForResult(chooserIntent, REQUEST_IMAGE)
        }
    }

    private fun removeUploadedImage() {
        mViewModel.remoteImageUrl = null
        mBinding.imageIv.setImageResource(R.drawable.bg_manually_real_name_image_placeholder)
    }

    //上传图片
    private fun uploadPicture(internalImageUri: Uri, filePath: String) {
        if (TextUtils.isEmpty(filePath)) return

        mDialog = WaitingDialogFragment.newInstance("上传图片中")
        mDialog?.show(childFragmentManager, "loading")

        mDisposable = UploadImageUtils.uploadImage(
            UploadImageUtils.UploadType.id_photo,
            filePath,
            object : UploadImageUtils.OnUploadImageListener {
                override fun onSuccess(imageUrl: String) {
                    if (!isAdded) return

                    mDialog?.dismissAllowingStateLoss()
                    mViewModel.remoteImageUrl = imageUrl

                    mBinding.clearIv.visibility = View.VISIBLE
                    ImageUtils.picasso.load(internalImageUri).memoryPolicy(MemoryPolicy.NO_STORE).into(mBinding.imageIv)
                    updateSubmitBtn()
                }

                override fun onError(e: Throwable?) {
                    mDialog?.dismissAllowingStateLoss()
                    ToastUtils.toast("图片上传失败 ${e?.localizedMessage}")
                }

                override fun onProgress(total: Long, progress: Long) {
                    // do nothing
                }
            })
    }

    private fun showSuccessView() {
        mBinding.successContainer.visibility = View.VISIBLE
    }

    private fun isInputValid(name: String, idCard: String): Pair<Boolean, String> {
        if (TextUtils.isEmpty(name)) {
            return Pair(false, "请输入姓名")
        }

        if (TextUtils.isEmpty(idCard)) {
            return Pair(false, "请输入证件号码")
        }

        if (mViewModel.remoteImageUrl == null) {
            return Pair(false, "请上传证件照")
        }

        return Pair(true, "")
    }

    companion object {
        const val REQUEST_IMAGE = 101
    }

}