package com.qmai.android.plugin

import com.android.tools.r8.internal.S
import com.google.gson.Gson
import com.google.gson.JsonObject
import okhttp3.HttpUrl
import okhttp3.MediaType
import okhttp3.MultipartBody
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 org.json.JSONException
import org.json.JSONObject

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

class PygerUploadTask extends DefaultTask {
    @OutputFile
    File file;
    @Input
    String buildType;
    @Input
    String key;
    @Input
    String flavor
    @Input
    String appName

    @Inject
    PygerUploadTask(File file, String buildType, String key, String flavor, String appName) {
        this.file = file
        this.buildType = buildType
        this.key = key
        this.flavor = flavor
        this.appName = appName
        setGroup("pyger")
    }

    @TaskAction
    public void upload() {
        println("-------执行upload")
        //https://www.pgyer.com/doc/view/api#fastUploadApp

        OkHttpClient client = new OkHttpClient.Builder()
                .callTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS)
                .connectTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .build()

        //第一步骤，获取上传的 token

        MultipartBody.Builder tokenBodyBuilder = new MultipartBody.Builder().setType(MultipartBody.FORM)

        tokenBodyBuilder.addFormDataPart("_api_key", key)
        tokenBodyBuilder.addFormDataPart("buildType", "android")
        Request tokenRequest = new Request.Builder()
                .url("https://www.pgyer.com/apiv2/app/getCOSToken")
                .post(tokenBodyBuilder.build())
                .build()
        Response responseToken = client.newCall(tokenRequest).execute()
        String tokenResult = responseToken.body().string()

               /* {
                    "code": 0,
                    "message": "",
                    "data": {
                    "params": {
                        "signature": "q-sign-algorithm=sha1&q-ak=AKIDDwRDhGT-LEU0S8GcAPKTqTzP2p1PA0JprsT9jYUp7jbXGsZ4GrSAzum-cHKSRPba&q-sign-time=1705461228;1705463088&q-key-time=1705461228;1705463088&q-header-list=&q-url-param-list=&q-signature=9cba43453b03165c5c47b95380e6740490a12009",
                        "x-cos-security-token": "EY3DDiyCwdvEGzVyabZkeVBBRAKKA7fa9b8cb9249ebdb45dbffb1649ecc02ee2DErrKqaDiE8uLO43xasJn4NRLydmPDDTXatdZse_4t_enC6BFc5f1Lr9pzZ6bDxYd11SQ6FnbnRKZf-hP3bKOFMbKggtVTwDQtO7Z0LE5NLNMfZhnA0RoFu2PXmN8KJK9mler123PwxOXUhSw1mOALy_KFCZZ7Xghfz68sOwut23OPAESRZH2IUouyIFmcm5Rull7X1UB-uP-MuKIFtqtVm5xQVvZL3UsXiPsvv53fCWX_d_o5X3lnt3gSmsGT_xTS4UvYrNRulKrWp9z6fe86shKzu5xOdi9YvVXS3zUz96JVx6TNI6kGXSnAyMHDNMPw1dkQCn-orD4JQweLzmpr82H4YWQhtD_R-SH5Ju1fE",
                        "key": "5adadedc1a29228ac68a94a04404b863.apk"
                    },
                    "key": "5adadedc1a29228ac68a94a04404b863.apk",
                    "endpoint": "https:\/\/pgy-apps-1251724549.cos.ap-guangzhou.myqcloud.com"
                }
                }*/
        println("获取token回执 result = " + tokenResult)
        JSONObject jsonObject = new JSONObject(tokenResult);
        JSONObject data = jsonObject.getJSONObject("data");
        String tokenKey = data.getString("key");
        String endpoint = data.getString("endpoint");
        String signature = data.getJSONObject("params").getString("signature");
        String x_cos_security_token = data.getJSONObject("params").getString("x-cos-security-token");

        //第二步骤，上传文件
//        key	String	(必填) 从上一步响应中得到
//        signature	String	(必填) 从上一步响应中得到
//        x-cos-security-token	String	(必填) 从上一步响应中得到
//        x-cos-meta-file-name	String	(选填) 上传的原始文件名，如 app-release.apk
//        file	File	(必填) App 文件的本地路径


        MultipartBody.Builder bodyBuilder = new MultipartBody.Builder().setType(MultipartBody.FORM)
        //add part
        bodyBuilder.addFormDataPart("key", tokenKey)
       bodyBuilder.addFormDataPart("signature", signature)
        bodyBuilder.addFormDataPart("x-cos-security-token", x_cos_security_token)
        //add file
        bodyBuilder.addFormDataPart("file", file.getName(), RequestBody
                .create(MediaType.parse("*/*"), file))

        //request

        Request request = new Request.Builder()
                .url(endpoint)
                .post(bodyBuilder.build())
                .build()
       /*                 {
                            "code": 0,
                            "message": "",
                            "data": {
                            "buildKey": "b3015954bdbd113099e1c2a44d0c6007",
                            "buildType": "2",
                            "buildIsFirst": "0",
                            "buildIsLastest": "1",
                            "buildFileKey": "b3015954bdbd113099e1c2a44d0c6007.apk",
                            "buildFileName": "",
                            "buildFileSize": "76073928",
                            "buildName": "企迈数店HD",
                            "buildVersion": "1.7.790",
                            "buildVersionNo": "202312111",
                            "buildBuildVersion": "696",
                            "buildIdentifier": "com.qmai.android.qmshopassistant",
                            "buildIcon": "a7588c47203f07a4a6d571d52a27242f",
                            "buildDescription": "",
                            "buildUpdateDescription": "",
                            "buildScreenshots": "",
                            "buildShortcutUrl": "MiQ9",
                            "buildCreated": "2024-01-17 13:47:34",
                            "buildUpdated": "2024-01-17 13:47:34",
                            "buildQRCodeURL": "https:\/\/pgyer.com\/app\/qrcodeHistory\/a1b3f3734abf368f8555d67a378c6479b6727515481c4ef11aba28a6de590d3d"
                        }
                        }*/

        try {
            println("开始上传蒲公英")
            Response response = client.newCall(request).execute()
            String result = response.body().string()
            println("上传接收返回信息: "+result+" "+response.successful)
            Thread.sleep(5000)
            println("begin check:")
            int index = 3;
            while (index>0) {
                try {
                HttpUrl.Builder urlBuilder = HttpUrl.parse("https://www.pgyer.com/apiv2/app/buildInfo").newBuilder()
                urlBuilder.addQueryParameter("_api_key", key);
                urlBuilder.addQueryParameter("buildKey", tokenKey);
                String url = urlBuilder.build().toString();
                Request checkRequest = new Request.Builder()
                        .url(url)
                        .get()
                        .build()
                Response checkResponse = client.newCall(checkRequest).execute()
                String responseText = checkResponse.body().string()
                    JSONObject jsonObjectResult = new JSONObject(responseText)
                    int code = jsonObject.getInt("code")
                    if (code==0){

                        uploadToFs(jsonObjectResult.getJSONObject("data").getString("buildShortcutUrl"),jsonObjectResult.getJSONObject("data").getString("buildQRCodeURL"),client)

                        break

                    }
                println(checkResponse.body().string())
                }catch(Exception e ){
                    print("check upload pgyer error = $e")
                }
                index--
                Thread.sleep(5000)
            }



        } catch (IOException e) {
            e.printStackTrace()
            println("-----------------upload error----------------")
            println("error: " + e.getMessage())
        } catch (Exception e) {
            println("-----------------upload error----------------")
            println("error: " + e.getMessage())

        }
    }



    void  uploadToFs(buildShortcutUrl,buildQRCodeURL,client){
        Gson gson = new Gson()

        println("downloadUrl= " + " https://www.pgyer.com/" + buildShortcutUrl)
        println("qrurl= " +buildQRCodeURL)
        //System.out.println("upload result: " + result)
        def branch = ""
        try {
            branch = getBranch()
        } catch (Exception e) {
            e.printStackTrace();
            println("getBranch error = " + e.message)
        }

        String content = "${appName.isEmpty() ? file.name : appName}: downloadurl: https://www.pgyer.com/$buildShortcutUrl\n qrurl: $buildQRCodeURL\n env: $buildType\n cpu: $flavor\n feature: ${branch}"
        println("send fs content = ${content}")
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        try {
            def fsText = new FsDetailInfoModel(content)
            def fs = new FsInfoModel(fsText)
            RequestBody requestBody = RequestBody.create(JSON, gson.toJson(fs))

            Request request2 = new Request.Builder()
                    .url("https://open.feishu.cn/open-apis/bot/v2/hook/64bff42a-a12a-4978-8456-ccabeb25858a")
                    .post(requestBody)
                    .build()
            Response response2 = client.newCall(request2).execute()
            String value = response2.body().string()
            println("upload fs response= " + value)
        } catch (JSONException e) {
            e.printStackTrace()
            println("uplaod fs error = $e")
        }

    }

    @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")
        }
        return false;
    }

    //获取当前分支
    @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
        }

    }
}
