package org.yameida.worktool.utils

import android.content.Context
import android.graphics.Bitmap
import com.blankj.utilcode.util.*
import com.lzy.okgo.OkGo
import com.tencent.wework.api.IWWAPI
import com.tencent.wework.api.WWAPIFactory
import com.tencent.wework.api.model.WWMediaImage
import com.tencent.wework.api.model.WWMediaLink
import com.tencent.wework.api.model.WWMediaMiniProgram
import com.tencent.wework.api.model.WWSimpleRespMessage
import org.yameida.worktool.service.log
import java.io.ByteArrayOutputStream
import java.io.File
import java.text.SimpleDateFormat
import java.util.*


object IWWAPIUtil {

    private var iwwapi: IWWAPI? = null

    fun init(context: Context) {
        iwwapi = WWAPIFactory.createWWAPI(context)
        iwwapi?.unregisterApp()
        val result = iwwapi?.registerApp(SPUtils.getInstance().getString("weworkSchema"))
    }

    fun init(){
        iwwapi?.unregisterApp()
        val result = iwwapi?.registerApp(SPUtils.getInstance().getString("weworkSchema"))
    }

    fun sendLink(
        appId: String?,
        agentId: String?,
        thumbUrl: String?,
        webpageUrl: String?,
        title: String?,
        description: String?
    ): Boolean {
        val link = WWMediaLink()
        link.thumbUrl = thumbUrl
        link.webpageUrl = webpageUrl
        link.title = title
        link.description = description
        link.appPkg = AppUtils.getAppPackageName()
        link.appName = AppUtils.getAppName()
        link.appId = appId
        link.agentId = agentId
        return iwwapi?.sendMessage(link) ?: false
    }

    fun sendMicroProgram(
        appId: String?,
        agentId: String?,
        title: String?,
        imageUrl: String?,
        username: String?,
        path: String?,
        schema: String?,
        description: String?
    ): Boolean {
        val miniProgram = WWMediaMiniProgram()
        miniProgram.appPkg = "com.rk.worktool"
        miniProgram.appName = "企微助手-rk"
        miniProgram.appId = appId
        miniProgram.agentId = agentId
        miniProgram.schema = schema
        miniProgram.username = username //必须是应用关联的小程序，注意要有@app后缀
        miniProgram.description = description
        miniProgram.path = path
        miniProgram.title = title
        LogUtils.d("小程序: ${miniProgram.appId} ${miniProgram.agentId} ${miniProgram.username} ${miniProgram.title}")
        log("小程序: ${miniProgram.appId} ${miniProgram.agentId} ${miniProgram.username} ${miniProgram.title}")
//        val bitmap = (Utils.getApp().getDrawable(R.mipmap.ic_launcher) as BitmapDrawable).bitmap
//        val stream = ByteArrayOutputStream()
//        bitmap.compress(Bitmap.CompressFormat.JPEG, 75, stream)

//        if (imageUrl != null) {
//            miniProgram.hdImageData = imageUrl.toByteArray()
//        }

//        val miniProgram = WWMediaImage()
//        miniProgram.fileName = "006YOSmagy1hw227uisk4j30sg0sgq6t"
//        miniProgram.filePath = "https://ww3.sinaimg.cn/mw690/006YOSmagy1hw227uisk4j30sg0sgq6t.jpg"
//        miniProgram.appPkg = "com.rk.worktool"
//        miniProgram.appName = "worktool"
//        miniProgram.appId = "ww5cbd509b435e591b" //企业唯一标识。创建企业后显示在，我的企业 CorpID字段
//        miniProgram.agentId = "1000015"
        if (imageUrl != null) {
            LogUtils.i("下载开始 $imageUrl")
            val execute = OkGo.get<File>(imageUrl).execute()
            LogUtils.i("下载完成 $imageUrl")
            val body = execute.body()
            if (body != null) {
                val df = SimpleDateFormat("yyyy-MM-dd")
                val filePath = "${
                    Utils.getApp().getExternalFilesDir("mp_image_cache")
                }/${df.format(Date())}/share.png"
                val newFile = File(filePath)
                val create = FileUtils.createFileByDeleteOldFile(newFile)
                if (create && newFile.canWrite()) {
                    newFile.writeBytes(body.bytes())
                    LogUtils.i("文件存储本地成功 $filePath")
                    val bitmap = ImageUtils.bytes2Bitmap(File(filePath).readBytes())
                    val stream = ByteArrayOutputStream()
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 75, stream)
                    miniProgram.hdImageData = stream.toByteArray()
                } else {
                    LogUtils.e("文件存储本地失败 $filePath")
                }
            } else {
                LogUtils.e("文件下载失败")
            }
        }
        return iwwapi!!.sendMessage(miniProgram) { resp ->
            if (resp is WWSimpleRespMessage) {
                val rsp = resp as WWSimpleRespMessage
                var t: String? = ""
            }
        }
//        return iwwapi?.sendMessage(miniProgram) { resp ->
//            if (resp is WWSimpleRespMessage) {
//
//            }
//        } ?: false
    }

    fun sendPicture(
        path: String,
        appId: String,
        agentId: String,
        fileName: String
    ): Boolean {
        val img = WWMediaImage()
        img.fileName = fileName
        img.filePath = path
        img.appPkg = "com.rk.worktool"
        img.appName = "企微助手-rk"
        img.appId = appId //企业唯一标识。创建企业后显示在，我的企业 CorpID字段
        img.agentId = agentId
        return iwwapi?.sendMessage(img) ?: false
    }
}