package com.zswc.creativity.utils

import android.Manifest
import android.annotation.SuppressLint
import android.app.Activity
import android.content.*
import android.graphics.Bitmap
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import android.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.*
import androidx.appcompat.widget.AppCompatImageView
import coil.load
import coil.transform.RoundedCornersTransformation
import com.qmuiteam.qmui.kotlin.onClick
import com.qmuiteam.qmui.layout.QMUIFrameLayout
import com.qmuiteam.qmui.skin.QMUISkinValueBuilder
import com.qmuiteam.qmui.util.QMUIDisplayHelper
import com.qmuiteam.qmui.widget.QMUIRadiusImageView
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog
import com.qmuiteam.qmui.widget.popup.QMUIPopup
import com.qmuiteam.qmui.widget.popup.QMUIPopups
import com.yanzhenjie.permission.Action
import com.yanzhenjie.permission.AndPermission
import com.yanzhenjie.permission.FileProvider
import com.ysnows.base.utils.UiUtils
import com.zhy.http.okhttp.OkHttpUtils
import com.zhy.http.okhttp.callback.FileCallBack
import com.zswc.creativity.BuildConfig
import com.zswc.creativity.R
import okhttp3.Call
import java.io.File
import java.io.FileNotFoundException
import java.util.*


/**
 * 分享-网络地址url的分享
 *Created by shihuiyun
 *on 2020/9/21
 */
object PopuShareWxUtils {

    var chose = 1
    private const val title = "分享"
    var tipDialog: QMUITipDialog? = null
    private var downimg: String? = null
    private val uriArrayList = ArrayList<Uri>() //下载到本地的图片的集合
    var cr: ContentResolver? = null
    fun show(context: Context, url: String, view: View, contentResolver: ContentResolver) {
        cr = contentResolver
        var mNormalPopup = QMUIPopups.fullScreenPopup(context)
        val builder: QMUISkinValueBuilder = QMUISkinValueBuilder.acquire()
        val frameLayout = QMUIFrameLayout(context)
        //自定义布局
        val layoutInflater = context?.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
        var layout = layoutInflater.inflate(R.layout.item_wx_share, null)

        val img: AppCompatImageView = layout.findViewById(R.id.img)
        val llShareOne: LinearLayout = layout.findViewById(R.id.ll_share_one)
        val llWx: LinearLayout = layout.findViewById(R.id.ll_wx)
        val ivShareThree: ImageView = layout.findViewById(R.id.iv_share_three)
        val llSave: LinearLayout = layout.findViewById(R.id.ll_save)
        val llLink: LinearLayout = layout.findViewById(R.id.ll_link)
        val tvClose: TextView = layout.findViewById(R.id.tv_close)


        val params = img.layoutParams

        val display = (context as Activity).windowManager.defaultDisplay
        val screenWidth = display.width
        params.width = screenWidth - UiUtils.dp2Px(context, 60f)
        //params.height = (((screenWidth - UiUtils.dp2Px(context, 60f)) * 1.6).toInt())
        params.height=screenWidth - UiUtils.dp2Px(context, 60f)

        img.layoutParams = params

        img.load(url){
            transformations(RoundedCornersTransformation(15f))
            placeholder(R.drawable.bg_need_error)
            error(R.drawable.bg_need_error)
        }


        llShareOne.onClick {
            //分享给好友
            chose = 1
            setShareImages(context, url)
            mNormalPopup.dismiss()


        }
        llLink.onClick {
            //复制图片链接到粘贴板

            val cm: ClipboardManager? = context?.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager?
            val mClipData = ClipData.newPlainText("Label", url)
            cm?.setPrimaryClip(mClipData)
            Toast.makeText(context, "文字已复制到粘贴板", Toast.LENGTH_SHORT).show()
            mNormalPopup.dismiss()
        }

        llWx.onClick {

            //分享给朋友圈
            chose = 2
            setShareImages(context, url)
            mNormalPopup.dismiss()

        }
        ivShareThree.onClick {
            //分享到QQ
            // toShareQQ(context,url)
            chose = 3
            setShareImages(context, url)
            mNormalPopup.dismiss()
        }

        tvClose.onClick {
            mNormalPopup.dismiss()
        }

        llSave.onClick {

            //保存图片到本地
            saveImageToGallery(context, url)

            mNormalPopup.dismiss()
        }


        builder.release();

        val size = QMUIDisplayHelper.getScreenWidth(context)


        val lp: FrameLayout.LayoutParams = FrameLayout.LayoutParams(size,
                FrameLayout.LayoutParams.WRAP_CONTENT)
        frameLayout.addView(layout, lp)

        mNormalPopup.addView(frameLayout)
        mNormalPopup.onDismiss() {
        }

        mNormalPopup.dismissIfOutsideTouch(false)
        mNormalPopup.animStyle(QMUIPopup.ANIM_GROW_FROM_CENTER)
        mNormalPopup.show(view)


    }


    /**
     * 保存到系统相册
     */
    @SuppressLint("WrongConstant")
    fun saveImageToGallery(context: Context, url: String) {
        AndPermission.with(context)
                .runtime()
                .permission(Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.CAMERA
                )
                .onGranted(Action<List<String?>?>

                {
                    setSaveImg(context, url)
                }
                ).start()
    }

    fun setSaveImg(context: Context, url: String) {

        var tipDialog = QMUITipDialog.Builder(context)
                .setIconType(QMUITipDialog.Builder.ICON_TYPE_LOADING)
                .setTipWord("正在保存图片...")
                .create()


        Thread(Runnable {
            val bitmap: Bitmap = SaveLocalUtils.returnBitMap(url)
            SaveLocalUtils.saveBitmap(context, bitmap, "loc" + System.currentTimeMillis() + ".png")
            //                SaveLocalUtils.saveBmp2Gallery(
//                        getContext(), bitmap,
//                        "loc" + System.currentTimeMillis());
            (context as Activity).runOnUiThread {
                tipDialog!!.dismiss()
                Toast.makeText(context, "图片已保存在手机相册下！", Toast.LENGTH_LONG).show()
                //Toasts.toast(context, "图片已保存在相册CANDYIMG文件夹下！");

            }
        }).start()
    }


    fun setShareImages(context: Context, url: String) {
        tipDialog = QMUITipDialog.Builder(context)
                .setIconType(QMUITipDialog.Builder.ICON_TYPE_LOADING)
                .setTipWord("正在保存图片...")
                .create()


        //下载图片
        startDownImg(url, context)

    }

    /**
     * @param photoPathL 下载图片
     */
    private fun startDownImg(photoPathL: String, con: Context) {

        //先下载图片
        try {
            okHttpSaveImg(photoPathL, 1, con)

        } catch (e: Exception) {
            Log.e("-shy-", "e=: " + e);
        }

    }

    private fun okHttpSaveImg(imgUrl: String, position: Int, con: Context?) {


        val filePath: String = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            con!!.filesDir.absolutePath
        } else {
            getSDPath() + "/revoeye/"
        }
        if (con == null) {
            // Toasts.toast(con, con.getString(R.string.action_share)+con.getString(R.string.fail)+con.getString(R.string.the_comma)+con.getString(R.string.please_share_it_later));
            return
        }
        OkHttpUtils
                .get()
                .url(imgUrl)
                .build() //
                .execute(object : FileCallBack(filePath, System.currentTimeMillis().toString() + "creativity.jpg" //
                ) {
                    override fun onError(call: Call, e: Exception, id: Int) {
                        if (con != null) {
                        }
                    }

                    override fun onResponse(response: File, id: Int) {
                        if (con != null) {
                            if (response != null) {
                                var mUri: Uri? = null
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                                    /**Android 7.0以上的方式 */
                                    if (con != null) {
                                        try {
                                            var url = insertImageToSystem(con, response.absolutePath)
                                            if (!TextUtils.isEmpty(url)) {
                                                mUri = Uri.parse(url)
                                            }
                                        } catch (e: java.lang.Exception) {

                                        }

                                    } else {
                                        return
                                    }

                                } else {
                                    mUri = Uri.fromFile(response)
                                }
                                if (mUri == null) {
                                    return
                                }
                                //uriArrayList.add(mUri);
                                downimg = mUri.toString()
                                if (uriArrayList.size > 0) {
                                    uriArrayList.clear()
                                }
                                uriArrayList.add(Uri.parse(downimg))
                                if (con != null) {
                                    share(con)
                                }
                            }
                        }
                    }
                })
    }


    private fun share(context: Context) {


        tipDialog!!.dismiss()

        if (chose == 1) { //微信好友
            val uriToImage = Uri.parse(downimg)

            //图片
            val shareIntent = Intent()
            //发送图片到朋友圈
            //ComponentName comp = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareToTimeLineUI");
            //发送图片给好友。
            val comp = ComponentName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareImgUI")
            shareIntent.component = comp
            shareIntent.action = Intent.ACTION_SEND
            shareIntent.putExtra(Intent.EXTRA_STREAM, uriToImage)
            shareIntent.type = "image/jpeg"
            context.startActivity(Intent.createChooser(shareIntent, title))


        }
        if (chose == 2) { //微信朋友圈
            val componentName = ComponentName("com.tencent.mm",
                    "com.tencent.mm.ui.tools.ShareToTimeLineUI")
            var intent = Intent()
            intent.component = componentName
            intent.type = "image/*"
            if (uriArrayList.size > 1) {
                intent.action = Intent.ACTION_SEND_MULTIPLE
                intent.putExtra(Intent.EXTRA_STREAM, uriArrayList) //图片数据（支持本地图片的Uri形式）
            } else if (uriArrayList.size == 1) {
                intent.action = Intent.ACTION_SEND
                intent.putExtra(Intent.EXTRA_STREAM, uriArrayList[0]) //图片数据（支持本地图片的Uri形式）
            }
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION
                    or Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
            intent.putExtra("Kdescription", title)
            intent.putExtra(Intent.EXTRA_TEXT, title) //正常使用的文字

            context.startActivity(intent)


        }
        if (chose == 3) {//qq好友
            //todo:分享失败
            try {
//                var fileUri: Uri? =null
//                if (Build.VERSION.SDK_INT >= 24) {
//                    fileUri = getUriForFile24(context, downimg)
//                } else {
//                    fileUri = Uri.fromFile(File(downimg))
//                }
                var fileUri: Uri? = null
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {

                    fileUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".fileProvider", File(downimg))

                } else {
                    fileUri = Uri.fromFile(File(downimg))
                }

                val intent = Intent()
                val comp = ComponentName("com.tencent.mobileqq", "com.tencent.mobileqq.activity.JumpActivity")
                intent.component = comp

                intent.action = Intent.ACTION_SEND
                intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
                intent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
                intent.putExtra(Intent.EXTRA_STREAM, fileUri)
                intent.type = "image/*" //分享文件
                context.startActivity(Intent.createChooser(intent, "分享"))
            } catch (e: java.lang.Exception) {
                Log.e("-shy-", "e=: $e")
                Toast.makeText(context, "分享图片到QQ失败", Toast.LENGTH_SHORT).show()
//            ContextUtil.getInstance().showToastMsg("分享图片到**失败");
            }


        }
    }


    fun toShareQQ(context: Context, url: String) {

        try {

            val bitmap: Bitmap = SaveLocalUtils.returnBitMap(url)
            val intent = Intent()
            val comp = ComponentName("com.tencent.mobileqq", "com.tencent.mobileqq.activity.JumpActivity")
            intent.component = comp

            intent.action = Intent.ACTION_SEND
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            // intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(File(path)))
            intent.type = "image/*" //分享文件

            context.startActivity(Intent.createChooser(intent, "分享"))
        } catch (e: java.lang.Exception) {
            Toast.makeText(context, "分享图片到QQ失败", Toast.LENGTH_SHORT).show()
//            ContextUtil.getInstance().showToastMsg("分享图片到**失败");
        }

    }


    private fun insertImageToSystem(context: Context, imagePath: String): String? {
        var url: String? = ""
        try {

            // url = MediaStore.Images.Media.insertImage(context.getContentResolver(), imagePath, SHARE_PIC_NAME, "你对图片的描述");
            url = MediaStore.Images.Media.insertImage(context.contentResolver, imagePath, "IMG" + Calendar.getInstance().time, null)

            // url = MediaStore.Images.Media.insertImage(context.contentResolver, imagePath, SHARE_PIC_NAME, "你对图片的描述")
        } catch (e: FileNotFoundException) {
            e.printStackTrace()
            Log.e("shy", "Exception1=$e")
        }
        return url
    }

    fun getSDPath(): String? {
        var sdDir: File? = null
        val sdCardExist = Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED //判断sd卡是否存在
        if (sdCardExist) {
            sdDir = Environment.getExternalStorageDirectory() //获取跟目录
        }
        return sdDir.toString()
    }


}
