package com.clx.account_center

import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.database.Cursor
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import androidx.annotation.NonNull
import androidx.annotation.RequiresApi
import androidx.core.content.ContextCompat.startActivity
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import java.io.File


/** AccountCenterPlugin */
class AccountCenterPlugin : FlutterPlugin, MethodCallHandler {
    /// The MethodChannel that will the communication between Flutter and native Android
    ///
    /// This local reference serves to register the plugin with the Flutter Engine and unregister it
    /// when the Flutter Engine is detached from the Activity
    private lateinit var channel: MethodChannel
    private var channel1: MethodChannel? = null

    override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
        channel = MethodChannel(flutterPluginBinding.binaryMessenger, "account_center")
        channel.setMethodCallHandler(this)
        setupChannel(flutterPluginBinding.binaryMessenger, flutterPluginBinding.applicationContext)
    }


    override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {
        if (call.method == "startWebView") {

            result.success("Android ${android.os.Build.VERSION.RELEASE}")
        } else {
            result.notImplemented()
        }
    }

    override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
        channel.setMethodCallHandler(null)
    }

    private fun setupChannel(messenger: BinaryMessenger, context: Context) {
        channel = MethodChannel(messenger,"account_center")
        channel.setMethodCallHandler { call, result ->
            when (call.method) {
                "startWebView" -> {
                    val url = call.argument<String>("url")
                    val intent = Intent(context, H5Activity::class.java)
                    intent.putExtra("url",url)
                    intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
                    startActivity(context,
                        intent, Bundle())
                }
                else -> {}
            }
        }
        setChannel1(messenger, context)
    }

    private fun setChannel1(
        messenger: BinaryMessenger,
        context: Context
    ) {
        channel1 = MethodChannel(messenger, "clx_file_manage")
        channel1?.setMethodCallHandler { call, result ->
            when (call.method) {
                "copy_to_public" -> {
                    val privatePath = call.argument<String>("private_path")
                    val title = call.argument<String>("title")
                    println("privatePath:$privatePath")
                    if (privatePath == null) {
                        result.error("下载失败", "文件不存在", null)
                        return@setMethodCallHandler
                    }
                    val privateFile = File(privatePath)
                    if (privateFile.exists()) {
                        val fileName =
                            title + System.currentTimeMillis().toString() + privatePath.substring(
                                privatePath.lastIndexOf("/") + 1
                            )
                        val publicPath =
                            Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).absolutePath
                        try {
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                                val insertFileIntoMediaStore =
                                    insertFileIntoMediaStore(fileName, context, publicPath)
                                        ?: throw Exception("文件插入失败")
                                val openOutputStream =
                                    context.contentResolver.openOutputStream(
                                        insertFileIntoMediaStore,
                                        "rw"
                                    ) ?: throw Exception("文件插入失败")
                                FileUtil.copyFileToOutStream(privateFile, openOutputStream)

//                                val intent = Intent("android.intent.action.VIEW")
//                                intent.addCategory("android.intent.category.DEFAULT")
//                                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
//                                intent.setDataAndType(
//                                    insertFileIntoMediaStore,
//                                    getMIMEType(fileName)
//                                )
//                                context.startActivity(intent)
                                result.success("")
                            } else {
                                FileUtil.copyFile(privateFile, File("$publicPath/$fileName"))
                                result.success("$publicPath/$fileName")
                            }
                        } catch (e: Exception) {
                            result.error("下载失败", "文件拷贝失败", null)
                        }
                    } else {
                        result.error("下载失败", "文件不存在", null);
                    }
                }
                else -> {}
            }
        }
    }

    /**
     * 保存文件到公共目录
     * @param imageName 文件名称
     */
    @RequiresApi(Build.VERSION_CODES.Q)
    fun insertFileIntoMediaStore(fileName: String, context: Context, publicPath: String): Uri? {
        var insertUri: Uri? = null
        val resolver = context.contentResolver
        //设置文件参数到ContentValues中
        val values = ContentValues()
        //设置文件名
        values.put(MediaStore.Downloads.DISPLAY_NAME, fileName)
        //下载路径（用于确定文件唯一性）
        values.put(MediaStore.Downloads.DOWNLOAD_URI, publicPath)
        //EXTERNAL_CONTENT_URI代表外部存储器

        val external = MediaStore.Downloads.EXTERNAL_CONTENT_URI
        //insertUri表示文件保存的uri路径
        values.put(MediaStore.Downloads.RELATIVE_PATH, "Download")
        insertUri = resolver.insert(external, values)
        return insertUri
    }

    /**
     * 通过taskTag称查询文件
     */
    @RequiresApi(Build.VERSION_CODES.Q)
    private fun queryDownloadFileByTaskKey(context: Context,taskKey: String): Cursor? {
        val external = MediaStore.Downloads.EXTERNAL_CONTENT_URI
        val selection = MediaStore.Downloads.DOWNLOAD_URI + "=?"
        val selections = arrayOf(taskKey)
        return context.contentResolver.query(
            external,
            null,
            selection,
            selections,
            null
        )?.apply { moveToFirst() }
    }

    /**
     * 根据文件后缀名获得对应的MIME类型。
     */
    private fun getMIMEType( fileName: String): String? {
        var type = "*/*"
        val fName: String = fileName
        //获取后缀名前的分隔符"."在fName中的位置。
        val dotIndex: Int = fName.lastIndexOf(".")
        if (dotIndex < 0) {
            return type
        }
        /* 获取文件的后缀名 */
        val end: String = fName.substring(dotIndex).lowercase()
        if (end.equals("")) return type
        //在MIME和文件类型的匹配表中找到对应的MIME类型。
        for (strings in MIME_MapTable) {
            if (end.equals(strings[0])) type = strings[1]
        }
        return type
    }


    private val MIME_MapTable = arrayOf(
        arrayOf(".3gp", "video/3gpp"),
        arrayOf(".apk", "application/vnd.android.package-archive"),
        arrayOf(".asf", "video/x-ms-asf"),
        arrayOf(".avi", "video/x-msvideo"),
        arrayOf(".bin", "application/octet-stream"),
        arrayOf(".bmp", "image/bmp"),
        arrayOf(".c", "text/plain"),
        arrayOf(".class", "application/octet-stream"),
        arrayOf(".conf", "text/plain"),
        arrayOf(".cpp", "text/plain"),
        arrayOf(".doc", "application/msword"),
        arrayOf(".docx", "application/msword"),
        arrayOf(".exe", "application/octet-stream"),
        arrayOf(".gif", "image/gif"),
        arrayOf(".gtar", "application/x-gtar"),
        arrayOf(".gz", "application/x-gzip"),
        arrayOf(".h", "text/plain"),
        arrayOf(".htm", "text/html"),
        arrayOf(".html", "text/html"),
        arrayOf(".jar", "application/java-archive"),
        arrayOf(".java", "text/plain"),
        arrayOf(".jpeg", "image/jpeg"),
        arrayOf(".JPEG", "image/jpeg"),
        arrayOf(".jpg", "image/jpeg"),
        arrayOf(".js", "application/x-javascript"),
        arrayOf(".log", "text/plain"),
        arrayOf(".m3u", "audio/x-mpegurl"),
        arrayOf(".m4a", "audio/mp4a-latm"),
        arrayOf(".m4b", "audio/mp4a-latm"),
        arrayOf(".m4p", "audio/mp4a-latm"),
        arrayOf(".m4u", "video/vnd.mpegurl"),
        arrayOf(".m4v", "video/x-m4v"),
        arrayOf(".mov", "video/quicktime"),
        arrayOf(".mp2", "audio/x-mpeg"),
        arrayOf(".mp3", "audio/x-mpeg"),
        arrayOf(".mp4", "video/mp4"),
        arrayOf(".mpc", "application/vnd.mpohun.certificate"),
        arrayOf(".mpe", "video/mpeg"),
        arrayOf(".mpeg", "video/mpeg"),
        arrayOf(".mpg", "video/mpeg"),
        arrayOf(".mpg4", "video/mp4"),
        arrayOf(".mpga", "audio/mpeg"),
        arrayOf(".msg", "application/vnd.ms-outlook"),
        arrayOf(".ogg", "audio/ogg"),
        arrayOf(".pdf", "application/pdf"),
        arrayOf(".png", "image/png"),
        arrayOf(".pps", "application/vnd.ms-powerpoint"),
        arrayOf(".ppt", "application/vnd.ms-powerpoint"),
        arrayOf(".pptx", "application/vnd.ms-powerpoint"),
        arrayOf(".prop", "text/plain"),
        arrayOf(".rar", "application/x-rar-compressed"),
        arrayOf(".rc", "text/plain"),
        arrayOf(".rmvb", "audio/x-pn-realaudio"),
        arrayOf(".rtf", "application/rtf"),
        arrayOf(".sh", "text/plain"),
        arrayOf(".tar", "application/x-tar"),
        arrayOf(".tgz", "application/x-compressed"),
        arrayOf(".txt", "text/plain"),
        arrayOf(".wav", "audio/x-wav"),
        arrayOf(".wma", "audio/x-ms-wma"),
        arrayOf(".wmv", "audio/x-ms-wmv"),
        arrayOf(".wps", "application/vnd.ms-works"),
        arrayOf(".xml", "text/plain"),
        arrayOf(".z", "application/x-compress"),
        arrayOf(".zip", "application/zip"),
        arrayOf(".xls", "application/vnd.ms-excel"),
        arrayOf(".xlsx", "application/zip"),
        arrayOf(".xls", "application/vnd.ms-excel"),
        arrayOf(".xlsx", "application/vnd.ms-excel"),
        arrayOf("", "*/*")
    )



}
