package com.abbidot.tracker.ui.activity.data

import android.content.Intent
import android.graphics.Bitmap
import android.view.View
import androidx.activity.viewModels
import androidx.core.content.ContextCompat
import coil.load
import com.abbidot.baselibrary.constant.ResultCode
import com.abbidot.baselibrary.util.LogUtil
import com.abbidot.baselibrary.util.Utils
import com.abbidot.tracker.BuildConfig
import com.abbidot.tracker.R
import com.abbidot.tracker.base.BaseActivity
import com.abbidot.tracker.bean.ActiveTimeBean
import com.abbidot.tracker.bean.PetBean
import com.abbidot.tracker.constant.ConstantString
import com.abbidot.tracker.databinding.ActivitySharePetActivityBinding
import com.abbidot.tracker.util.FileUtil
import com.abbidot.tracker.util.ImageUtil
import com.abbidot.tracker.util.Util
import com.abbidot.tracker.util.ViewUtil
import com.abbidot.tracker.vm.TakePhotoAndCompressViewModel
import com.huantansheng.easyphotos.EasyPhotos
import com.huantansheng.easyphotos.models.album.entity.Photo
import com.huantansheng.easyphotos.utils.bitmap.BitmapUtils
import com.huantansheng.easyphotos.utils.bitmap.SaveBitmapCallBack
import com.huantansheng.easyphotos.utils.uri.UriUtils
import com.qmuiteam.qmui.widget.dialog.QMUIBottomSheet
import java.io.File
import java.io.IOException


class SharePetActivityActivity :
    BaseActivity<ActivitySharePetActivityBinding>(ActivitySharePetActivityBinding::inflate) {

    private val mTakePhotoAndCompressViewModel: TakePhotoAndCompressViewModel by viewModels()

//    private lateinit var mFacebookShareDialog: ShareDialog
//    private lateinit var mFacebookCallbackManager: CallbackManager

    override fun getTopBar() = mViewBinding.ilSharePetActivityTopBar.titleTopBar

    override fun initData() {
        super.initData()
        setLeftBackImage(R.drawable.icon_white_back_svg)
        if (null == mRightTextButton) {
            mRightTextButton = addRightTextButton(R.string.txt_share)
        }

        mViewBinding.apply {

            intent.extras?.apply {
                Util.getParcelableAdaptive(intent, ConstantString.Pet, PetBean::class.java)?.let {
                    ViewUtil.instance.setPetTypeHead(
                        ilSharePetActivityPetHead.appHeadImage, it.imgurl, it.petType
                    )
                    tvSharePetActivityPetName.text = it.petName
                }
                Util.getParcelableAdaptive(
                    intent, ConstantString.HistoryDataBean, ActiveTimeBean::class.java
                )?.let {
                    tvSharePetActivityTime.text = Utils.stringToDate(
                        it.dayTime, Utils.DATE_FORMAT_PATTERN_CN, Utils.DATE_FORMAT_PATTERN_EN7
                    )
                    ViewUtil.instance.viewNumberValueAnimator(
                        ilSharePetActivityActivityTime.tvSportDataContent, 0, it.activeTime / 60
                    )
                    ViewUtil.instance.viewNumberValueAnimator(
                        ilSharePetActivityActivityCalories.tvSportDataContent, 0, it.calories
                    )
                }
            }

            val colorBg = ContextCompat.getColor(mContext, R.color.transparent)
            ilSharePetActivityActivityTime.let {
                it.root.setBackgroundColor(colorBg)
                it.tvSportDataUnit.setText(R.string.txt_min)
                it.tvSportDataTitle.setText(R.string.txt_activity_time)
                it.ivSportDataType.setImageResource(R.drawable.icon_active_time)
            }
            ilSharePetActivityActivityCalories.let {
                it.root.setBackgroundColor(colorBg)
                it.tvSportDataUnit.setText(R.string.txt_calorie_unit)
                it.tvSportDataTitle.setText(R.string.data_active_calories)
                it.ivSportDataType.setImageResource(R.drawable.icon_calories)
            }
            setOnClickListenerViews(mRightTextButton, ivSharePetActivityChangePhotoBtn)
        }

//        mFacebookCallbackManager = CallbackManager.Factory.create()
//        mFacebookShareDialog = ShareDialog(mActivity)
//        mFacebookShareDialog.registerCallback(
//            mFacebookCallbackManager, object : FacebookCallback<Sharer.Result> {
//                override fun onCancel() {
//                    LogUtil.e("1111")
//                    showToast(R.string.txt_cancel)
//                }
//
//                override fun onError(error: FacebookException) {
//                    LogUtil.e("2222,${error.message}")
//                    showToast("onError,${error.message}")
//                }
//
//                override fun onSuccess(result: Sharer.Result) {
//                    LogUtil.e("3333,$result")
//                    showToast(R.string.txt_successful)
//                }
//            }, ResultCode.ResultCode_2
//        )

        //先设置文件fileProvider
        EasyPhotos.createCamera(this@SharePetActivityActivity, false)
            .setFileProviderAuthority(FileUtil.FILE_PROVIDER)

        mTakePhotoAndCompressViewModel.registerCropImageActivityResult(this, 3, 4)
    }

    override fun liveDataObserve() {
        mTakePhotoAndCompressViewModel.mPhotoPathLiveData.observe(this) {
            if (it.size > 0) {
                mViewBinding.ivSharePetActivityPhoto.load(it[0])
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (RESULT_OK == resultCode) {
            //相机或相册回调
            if (requestCode == ResultCode.ResultCode_1 && null != data) {
                //返回对象集合：如果你需要了解图片的宽、高、大小、用户是否选中原图选项等信息，可以用这个
                val resultPhotos: ArrayList<Photo> =
                    data.getParcelableArrayListExtra(EasyPhotos.RESULT_PHOTOS)!!
                //返回图片地址集合时如果你需要知道用户选择图片时是否选择了原图选项，用如下方法获取
//                data.getBooleanExtra(EasyPhotos.RESULT_SELECTED_ORIGINAL, false)
                mTakePhotoAndCompressViewModel.goCropAndCompressImage(resultPhotos)
            } else if (requestCode == ResultCode.ResultCode_2) {
//                mFacebookCallbackManager.onActivityResult(requestCode, resultCode, data)
            }
        }
    }

    private fun getBitmap(bitmapCallback: (Bitmap) -> Unit) {
        mViewBinding.apply {
            ivSharePetActivityChangePhotoBtn.visibility = View.GONE
            ivSharePetActivityChangePhotoBtn.postDelayed({
                ImageUtil.viewToBitmap(rlSharePetActivityInfoLayout) { bitmap ->
                    bitmapCallback.invoke(bitmap)
                    ivSharePetActivityChangePhotoBtn.visibility = View.VISIBLE
                }
            }, 300)
        }
    }

    /**
     * 保存图片到本地
     */
    private fun saveToPhoto() {
        getBitmap { bitmap ->
            val dir = FileUtil.getDiskCacheDirectory(mContext, FileUtil.SHARE_DIRECTORY_NAME)
            BitmapUtils.saveBitmapToDir(this,
                dir.path,
                FileUtil.SHARE_DIRECTORY_NAME,
                bitmap,
                true,
                object : SaveBitmapCallBack {
                    override fun onSuccess(file: File) {
                        LogUtil.e("onSuccess,${file.path}")
                        showToast(R.string.txt_save_successful)
                        EasyPhotos.recycle(bitmap)
                    }

                    override fun onIOFailed(exception: IOException) {
                        LogUtil.e("onIOFailed,${exception.message}")
                        showToast(R.string.txt_fail)
                        EasyPhotos.recycle(bitmap)
                    }

                    override fun onCreateDirFailed() {
                        LogUtil.e("onCreateDirFailed")
                        showToast(R.string.txt_fail)
                        EasyPhotos.recycle(bitmap)
                    }
                })
        }
    }

    /**
     * Facebook分享
     */
//    private fun shareToFacebook() {
//        getBitmap { bitmap ->
//            val photo = SharePhoto.Builder().setBitmap(bitmap).build()
//            val content = SharePhotoContent.Builder().addPhoto(photo).build()
//            mFacebookShareDialog.show(content)
//        }
//    }

    private fun showShareMenu() {
        QMUIBottomSheet.BottomGridSheetBuilder(mContext).apply {
            addItem(
                R.drawable.ico_save_to_phone,
                "保存到本地",
                0,
                QMUIBottomSheet.BottomGridSheetBuilder.SECOND_LINE
            ).addItem(
                R.drawable.ico_save_to_facebook,
                "Facebook",
                1,
                QMUIBottomSheet.BottomGridSheetBuilder.SECOND_LINE
            ).setAddCancelBtn(true).setOnSheetItemClickListener { dialog, itemView ->
                dialog.dismiss()
                when (itemView.tag as Int) {
                    0 -> saveToPhoto()
//                    1 -> shareToFacebook()
                }
            }.build().show()
        }
    }


    /**
     * 创建分享的隐示意图
     */
    private fun createShareIntent(file: File) {
        // Create the new Intent using the 'Send' action.
        val shareIntent = Intent(Intent.ACTION_SEND)
        // Set the MIME type
        shareIntent.type = "image/*"
        // Create the URI from the media
        val uri = UriUtils.getUri(mContext, file)
        // Add the URI to the Intent.
        shareIntent.putExtra(Intent.EXTRA_STREAM, uri)
        //设置分享牌信为Instagram Story
//        share.setPackage("com.instagram.android")//使用 Instagram 的包名

        // Broadcast the Intent.
        startActivity(Intent.createChooser(shareIntent, "Share to"))
    }


    private fun shareImage() {
        getBitmap { bitmap ->
            val dir = FileUtil.getDiskCacheDirectory(mContext, FileUtil.SHARE_DIRECTORY_NAME)
            BitmapUtils.saveBitmapToDir(this,
                dir.path,
                FileUtil.SHARE_DIRECTORY_NAME,
                bitmap,
                false,
                object : SaveBitmapCallBack {
                    override fun onSuccess(file: File) {
                        LogUtil.e("onSuccess,${file.path}")
                        createShareIntent(file)
                        EasyPhotos.recycle(bitmap)
                    }

                    override fun onIOFailed(exception: IOException) {
                        LogUtil.e("onIOFailed,${exception.message}")
                        showToast(R.string.txt_fail)
                        EasyPhotos.recycle(bitmap)
                    }

                    override fun onCreateDirFailed() {
                        LogUtil.e("onCreateDirFailed")
                        showToast(R.string.txt_fail)
                        EasyPhotos.recycle(bitmap)
                    }
                })
        }
    }


    override fun onClick(v: View?) {
        mViewBinding.apply {
            when (v!!) {
                ivSharePetActivityChangePhotoBtn -> ViewUtil.instance.goSelectPhoto(
                    this@SharePetActivityActivity, ResultCode.ResultCode_1
                )

                mRightTextButton -> shareImage()
            }
        }
    }
}