package com.xty.common

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Rect
import com.hjq.toast.ToastUtils
import com.tencent.mm.opensdk.modelmsg.*
import com.xty.common.app.MyApp
import java.io.ByteArrayOutputStream
import java.nio.ByteBuffer


/**
 * 微信相关操作
 *
 * https://developers.weixin.qq.com/doc/oplatform/Mobile_App/Share_and_Favorites/Android.html
 */
class WxUtils {
    companion object {

        private fun isInstall(): Boolean {
            return MyApp.instance!!.api!!.isWXAppInstalled
        }

        /**
         * 微信登陆
         */
        fun signInWx() {
            if (!isInstall()) {
                ToastUtils.show("您的设备未安装微信客户端")
            } else {
                var req = SendAuth.Req();
                req.scope = "snsapi_userinfo";
                req.state = "wechat_sdk_demo_test";
                MyApp.instance!!.api!!.sendReq(req);
            }

        }

        /**
         * 分享  文字
         */
        fun shareCircle(text: String) {
            if (!isInstall()) {
                ToastUtils.show("您的设备未安装微信客户端")
                return
            }
            SendMessageToWX.Req.WXSceneTimeline
            //初始化一个 WXTextObject 对象，填写分享的文本内容
            //初始化一个 WXTextObject 对象，填写分享的文本内容
            val textObj = WXTextObject()
            textObj.text = "$text"
            //用 WXTextObject 对象初始化一个 WXMediaMessage 对象

            //用 WXTextObject 对象初始化一个 WXMediaMessage 对象
            val msg = WXMediaMessage()
            msg.mediaObject = textObj
            msg.description = "描述"

            val req = SendMessageToWX.Req()
            req.transaction = "text 文本"
            req.message = msg
            req.scene = SendMessageToWX.Req.WXSceneSession
            //调用api接口，发送数据到微信
            MyApp.instance!!.api!!.sendReq(req)

        }
        //网页分享
        fun shareWebPage(title:String,subTitle:String,context: Context,url:String){
            var webPage=WXWebpageObject()
            webPage.webpageUrl=url
            //描述
            var msg=WXMediaMessage(webPage)
            msg.title=title
            msg.description=subTitle
            var bmp=BitmapFactory.decodeResource(context.resources,R.mipmap.ic_share_logo)
            //设置缩略图
            val thumbBmp = Bitmap.createScaledBitmap(bmp, bmp.width, bmp.height, true)

            val bytes: Int = thumbBmp.getByteCount()
            val buf = ByteBuffer.allocate(bytes)
            thumbBmp.copyPixelsToBuffer(buf)
            val byteArray: ByteArray = buf.array()
            var byte=bmpToByteArray(thumbBmp,true)
            LogUtils.d("微信分享缩略图大小：：${byte!!.size}")

            msg.thumbData =byte
            //构造req
            var req=SendMessageToWX.Req()
            req.transaction="webPage"
            req.message=msg
            req.scene = SendMessageToWX.Req.WXSceneSession
            MyApp.instance!!.api!!.sendReq(req);
        }

        fun shareWebPageForCircle(title:String,subTitle:String,context: Context,url:String){
            var webPage=WXWebpageObject()
            webPage.webpageUrl=url
            //描述
            var msg=WXMediaMessage(webPage)
            msg.title=title
            msg.description=subTitle
            var bmp=BitmapFactory.decodeResource(context.resources,R.mipmap.ic_share_logo)
            //设置缩略图
            val thumbBmp = Bitmap.createScaledBitmap(bmp, bmp.width, bmp.height, true)

            val bytes: Int = thumbBmp.getByteCount()
            val buf = ByteBuffer.allocate(bytes)
            thumbBmp.copyPixelsToBuffer(buf)
            val byteArray: ByteArray = buf.array()
            var byte=bmpToByteArray(thumbBmp,true)
            LogUtils.d("微信分享缩略图大小：：${byte!!.size}")

            msg.thumbData =byte
            //构造req
            var req=SendMessageToWX.Req()
            req.transaction="webPage"
            req.message=msg
            req.scene = SendMessageToWX.Req.WXSceneTimeline
            MyApp.instance!!.api!!.sendReq(req);
        }

        /**
         * 分享图片
         */
        fun shareBitmap( context: Context,bitmap: Bitmap) {
            if (!isInstall()) {
                ToastUtils.show("您的设备未安装微信客户端")
                return
            }
            //val bmp = BitmapFactory.decodeResource(getResources(), R.drawable.send_img)

            //初始化 WXImageObject 和 WXMediaMessage 对象
            val imgObj = WXImageObject(bitmap)
            val msg = WXMediaMessage()
            msg.mediaObject = imgObj

            val bmp = BitmapFactory.decodeResource(context.resources,  R.mipmap.ic_logo)


            //设置缩略图
            val thumbBmp = Bitmap.createScaledBitmap(bmp, bmp.width, bmp.height, true)

            val bytes: Int = thumbBmp.getByteCount()
            val buf = ByteBuffer.allocate(bytes)
            thumbBmp.copyPixelsToBuffer(buf)
            val byteArray: ByteArray = buf.array()
            var byte=bmpToByteArray(thumbBmp,true)
            LogUtils.d("微信分享缩略图大小：：${byte!!.size}")

            msg.thumbData =byte
            thumbBmp.recycle()
            //构造一个Req
            val req = SendMessageToWX.Req()
            req.transaction ="${System.currentTimeMillis()}_img"
            req.message = msg
           // req.scene = SendMessageToWX.Req.WXSceneSession
            req.scene = SendMessageToWX.Req.WXSceneSession
            //调用api接口，发送数据到微信
            MyApp.instance!!.api!!.sendReq(req)
        }


        fun shareBitmapTwo( context: Context,bitmap: Bitmap) {
            if (!isInstall()) {
                ToastUtils.show("您的设备未安装微信客户端")
                return
            }
            //val bmp = BitmapFactory.decodeResource(getResources(), R.drawable.send_img)

            //初始化 WXImageObject 和 WXMediaMessage 对象
            val imgObj = WXImageObject(bitmap)
            val msg = WXMediaMessage()
            msg.mediaObject = imgObj

            val bmp = BitmapFactory.decodeResource(context.resources,  R.mipmap.ic_logo)


            //设置缩略图
            val thumbBmp = Bitmap.createScaledBitmap(bitmap, bitmap.width, bitmap.height, true)

            val bytes: Int = thumbBmp.getByteCount()
            val buf = ByteBuffer.allocate(bytes)
            thumbBmp.copyPixelsToBuffer(buf)
            val byteArray: ByteArray = buf.array()
            var byte=bmpToByteArray(thumbBmp,true)
            LogUtils.d("微信分享缩略图大小：：${byte!!.size}")

            msg.thumbData =byte
            thumbBmp.recycle()
            //构造一个Req
            val req = SendMessageToWX.Req()
            req.transaction ="${System.currentTimeMillis()}_img"
            req.message = msg
            // req.scene = SendMessageToWX.Req.WXSceneSession
            req.scene = SendMessageToWX.Req.WXSceneSession
            //调用api接口，发送数据到微信
            MyApp.instance!!.api!!.sendReq(req)
        }
        fun shareBitmapForCircle( context: Context,bitmap: Bitmap) {
            if (!isInstall()) {
                ToastUtils.show("您的设备未安装微信客户端")
                return
            }
            //val bmp = BitmapFactory.decodeResource(getResources(), R.drawable.send_img)

            //初始化 WXImageObject 和 WXMediaMessage 对象
            val imgObj = WXImageObject(bitmap)
            val msg = WXMediaMessage()
            msg.mediaObject = imgObj

            val bmp = BitmapFactory.decodeResource(context.resources,  R.mipmap.ic_logo)


            //设置缩略图
            val thumbBmp = Bitmap.createScaledBitmap(bmp, bmp.width, bmp.height, true)

            val bytes: Int = thumbBmp.getByteCount()
            val buf = ByteBuffer.allocate(bytes)
            thumbBmp.copyPixelsToBuffer(buf)
            val byteArray: ByteArray = buf.array()
            var byte=bmpToByteArray(thumbBmp,true)
            LogUtils.d("微信分享缩略图大小：：${byte!!.size}")

            msg.thumbData =byte
            thumbBmp.recycle()
            //构造一个Req
            val req = SendMessageToWX.Req()
            req.transaction ="${System.currentTimeMillis()}_img"
            req.message = msg
            // req.scene = SendMessageToWX.Req.WXSceneSession
            req.scene = SendMessageToWX.Req.WXSceneTimeline
            //调用api接口，发送数据到微信
            MyApp.instance!!.api!!.sendReq(req)
        }

        private fun bmpToByteArray(bmp: Bitmap, needRecycle: Boolean): ByteArray? {
            var i: Int
            var j: Int
            if (bmp.height > bmp.width) {
                i = bmp.width
                j = bmp.width
            } else {
                i = bmp.height
                j = bmp.height
            }
            val localBitmap = Bitmap.createBitmap(i, j, Bitmap.Config.RGB_565)
            val localCanvas = Canvas(localBitmap)
            while (true) {
                localCanvas.drawBitmap(bmp, Rect(0, 0, i, j), Rect(0, 0, i, j), null)
                if (needRecycle) bmp.recycle()
                val localByteArrayOutputStream = ByteArrayOutputStream()
                localBitmap.compress(
                    Bitmap.CompressFormat.JPEG, 40,
                    localByteArrayOutputStream
                )
                localBitmap.recycle()
                val arrayOfByte = localByteArrayOutputStream.toByteArray()
                try {
                    localByteArrayOutputStream.close()
                    return arrayOfByte
                } catch (e: Exception) {
                    //F.out(e);
                }
                i = bmp.height
                j = bmp.height
            }
        }

    }



}