package com.qmai.android.plugin


import com.aliyun.oss.OSS
import com.aliyun.oss.OSSClientBuilder
import com.aliyun.oss.model.PutObjectRequest
import com.android.tools.r8.internal.S
import com.google.gson.Gson
import okhttp3.MediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody
import okhttp3.Response
import org.gradle.api.DefaultTask
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.OutputFile
import org.gradle.api.tasks.TaskAction

import javax.inject.Inject
import java.util.concurrent.TimeUnit

class OssUploadTask extends DefaultTask {
    @OutputFile
    File file;
    @Input
    String ossPath = "appfile/demo/"
    @Input
    String buildType
    @Input
    String flavor
    @Input
    String appName

    @Inject
    OssUploadTask(File file, String ossPath, buildType, flavor, appName) {
        this.file = file
        this.ossPath = ossPath
        this.buildType = buildType
        this.flavor = flavor
        this.appName = appName
        setGroup("oss")

    }

    @TaskAction
    void upload() {
        OssParamsBean ossParamsBean = getOssInfo()
        println("-----------开始上传了 ")
        def fileName = file.getName()
        // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1（杭州）为例，Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
        String endpoint = ossParamsBean.app_oss_endpoint
// 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = ossParamsBean.app_oss_accessKeyId
        String accessKeySecret = ossParamsBean.app_oss_accessKeySecret

// 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret)

// 创建PutObjectRequest对象。
// 依次填写Bucket名称（例如examplebucket）、Object完整路径（例如exampledir/exampleobject.txt）和本地文件的完整路径。Object完整路径中不能包含Bucket名称。
// 如果未指定本地路径，则默认从示例程序所属项目对应本地路径中上传文件。
// 如果需要上传时设置存储类型和访问权限，请参考以下示例代码。
// ObjectMetadata metadata = new ObjectMetadata();
// metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
// metadata.setObjectAcl(CannedAccessControlList.Private);
// putObjectRequest.setMetadata(metadata);

        String ossPath = ossParamsBean.app_oss_path
        String bucketName = ossParamsBean.app_oss_bucketName
// 上传文件。
        try {
            println("file name= " + file.name)
            println("file path= " + file.absolutePath + " " + file.getCanonicalPath())
            // println("begin upload " + file.exists())
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, ossPath + fileName, file)
            ossClient.putObject(putObjectRequest)
            println("--------------------------------------------------------------------------")
            println("---------" + fileName + "--------上传完成")
            println("下载地址为:  " + "https://files.qmai.cn/" + ossPath + fileName)
            println("--------------------------------------------------------------------------")
        } catch (Exception e) {
            println("上传失败: " + e.getMessage() + "E" + e)
        }
// 关闭OSSClient。
        ossClient.shutdown()
        //钉钉通知
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        def gson = new Gson()
        //https://cli.im/api/qrcode/code?text
        def downloadUrl = "https://files.qmai.cn/$ossPath$fileName"
        def qrDownloadUrl = "https://cli.im/api/qrcode/code?text=${downloadUrl}"
        def content = "${appName.isEmpty() ? file.name : appName}: " +
                "OSS下载地址为: https://files.qmai.cn/$ossPath$fileName\n" +
                "二维码地址:$qrDownloadUrl\n" +
                "当前环境: $buildType\n" +
                "目标cpu: $flavor\n" +
                "是否加固: ${getJiagu()}\n" +
                "当前分支: ${getBranch()}"
        def dingDingdetail = new FsDetailInfoModel(content)
        def dingdingInfo = new FsInfoModel(dingDingdetail)
        RequestBody requestBody = RequestBody.create(JSON, gson.toJson(dingdingInfo))
        OkHttpClient client = new OkHttpClient.Builder()
                .callTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .connectTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .build()
        Request request2 = new Request.Builder()
                .url("https://open.feishu.cn/open-apis/bot/v2/hook/64bff42a-a12a-4978-8456-ccabeb25858a")
                .post(requestBody)
                .build()
        try {
            Response response2 = client.newCall(request2).execute()
            String value = response2.body().string()
            println("send fs response = " + value)

        } catch (Exception e) {
            println("send fs error = " + e.message)

        }
    }
    @Input
    String getJiagu() {
        Map<String, String> map = System.getenv()
        if (map == null) {
            return "no"
        }
        String str = map.get("jiagu")
        if (str == null) {
            return "no"
        } else {
            return str
        }
    }

    @Input
    boolean isInJenkins() {
        Map<String, String> map = System.getenv()
        if (map == null) {
            return false
        }
        String str = map.get("Path")
        if (str != null) {
            //it's windows
            return false
        } else {
            str = ""
            Iterator it = map.iterator()
            while (it.hasNext()) {
                str += it.next()
            }
            return str.contains("jenkins")
        }
    }

    //获取当前分支
    @Input
    String getBranch() {
        if (isInJenkins()) {
            return System.getenv().GIT_BRANCH
        } else {
            def byteOut = new ByteArrayOutputStream()
            project.exec {
                it.commandLine("git", "rev-parse", "--abbrev-ref", "HEAD")
                it.standardOutput = byteOut
            }
            def response = new String(byteOut.toByteArray())
            return response
        }

        return ""
    }

    @Input
    OssParamsBean getOssInfo() {
        OssParamsBean ossParamsBean = new OssParamsBean()
        Map<String, String> params = System.getenv()
        ossParamsBean.app_oss_endpoint = params.get("app_oss_endpoint")
        ossParamsBean.app_oss_accessKeyId = params.get("app_oss_accessKeyId")
        ossParamsBean.app_oss_accessKeySecret = params.get("app_oss_accessKeySecret")
        ossParamsBean.app_oss_path = params.get("app_oss_path")
        ossParamsBean.app_oss_bucketName = params.get("app_oss_bucketName")
        return ossParamsBean
    }
}
