package com.youdao.zhiyun.compositiondemo

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.provider.OpenableColumns
import android.util.Base64
import android.util.Log
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import androidx.lifecycle.lifecycleScope
import com.youdao.compositioncorrection.CompositionCorrection
import com.youdao.compositioncorrection.CorrectListener
import com.youdao.zhiyun.compositiondemo.databinding.ActivityEnglishImageBinding
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.ByteArrayOutputStream
import java.io.Serializable

class EnglishImageActivity : AppCompatActivity() {
    val TAG ="EnglishImageActivity"
    private val MAX_SIZE = 1.5f * 1024 * 1024
    private lateinit var binding: ActivityEnglishImageBinding
    private  var imageBase64:String =""
    val grades = arrayOf(
        "默认",
        "小学",
        "高中",
        "四级",
        "六级",
        "考研",
        "托福",
        "GRE",
        "雅思"
    )
    private  var grade =""
    val gradeMap = mapOf(
        "默认" to "default",
        "小学" to "elementary",
        "高中" to "high",
        "四级" to "cet4",
        "六级" to "cet6",
        "考研" to "graduate",
        "托福" to "toefl",
        "GRE" to "gre",
        "雅思" to "ielts",
    )
    @SuppressLint("Range")
    val getImage =   registerForActivityResult(ActivityResultContracts.GetContent()){ fullPhotoUri ->
        fullPhotoUri?.let {
            Log.d(TAG, "onActivityResult: fullPhotoUri: ${fullPhotoUri.path} ")
            val cursor = contentResolver.query(it, null, null, null, null)
            cursor?.let {
                if (it.moveToFirst()) {
                    it.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME))
                    val fileSize =  it.getString(cursor.getColumnIndex(OpenableColumns.SIZE)).toLong()
                    Log.e(TAG, "fileSize: $fileSize")
                    if (fileSize > MAX_SIZE ){
                        Toast.makeText(this@EnglishImageActivity, "图片不可以超过1.5M", Toast.LENGTH_SHORT).show()
                        return@registerForActivityResult
                    }

                }
            }


            val  thumbnail = BitmapFactory.decodeStream(contentResolver.openInputStream(fullPhotoUri))
            binding.imageCorrect.setImageBitmap(thumbnail)
            lifecycleScope.launch(Dispatchers.IO) {
                val baos = ByteArrayOutputStream()
                val quality = 100
                thumbnail.compress(Bitmap.CompressFormat.JPEG, quality, baos)
                val datas = baos.toByteArray()
                imageBase64 = Base64.encodeToString(datas, 2)
                Log.e(TAG, "onActivityResult: imageBase64:${imageBase64.length}")
                withContext(Dispatchers.Main){
                binding.button3.isEnabled = true
                }
            }
        }

    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityEnglishImageBinding.inflate(layoutInflater)
        setContentView(binding.root)
        initGradeSpSpinner()

    }

    private fun initGradeSpSpinner() {
        binding.spGrade.apply {
            prompt = "请选择作文等级"
            adapter = ArrayAdapter<String>(this@EnglishImageActivity, R.layout.item_grade, grades)
            setSelection(0)
            grade = gradeMap[grades[0]].toString()
            onItemSelectedListener = object : AdapterView.OnItemSelectedListener{
                override fun onItemSelected(p0: AdapterView<*>?, p1: View?, position: Int, p3: Long) {
                    Toast.makeText(this@EnglishImageActivity, "${grades[position]}", Toast.LENGTH_SHORT).show()
                    grade = gradeMap[grades[position]].toString()
                    Log.d("EnglishImageActivity", "onItemSelected:$grade ")
                }

                override fun onNothingSelected(p0: AdapterView<*>?) {
                }

            }
        }

    }
    fun correct(view: View) {


        val title = if ( binding.etTitle.text.toString().isEmpty() )null else binding.etTitle.text.toString()
        val modelContent = if ( binding.etModelContent.text.toString().isEmpty() )null else binding.etModelContent.text.toString()
        val goodExpression = if ( binding.etGoodExpression.text.toString().isEmpty() )null else binding.etGoodExpression.text.toString()
        val limitedWords = if ( binding.etLimitedWords.text.toString().isEmpty() )null else binding.etLimitedWords.text.toString()
//        CompositionCorrectioner.correctionEnglishText(input = EN_TEXT_TEST_DATA,
        CompositionCorrection.correctionEnglishImage(
            input =imageBase64,
            listener= object : CorrectListener {
                override fun onError(errorCode: Int?, msg: String?, requestId: String?) {
                    Log.e(TAG, "onError:  errorCode:$errorCode,msg:$msg,requestId:$requestId", )
                }

                override fun onResult(result: Serializable, requestId: String) {
                    runOnUiThread {
                        startActivity(Intent(this@EnglishImageActivity,CorrectResultActivity::class.java).apply {
                            putExtra("result",result )
                            putExtra("type","en_image")
                        })
                    }
                }

            },
            grade = grade,
            title = title,
            modelContent = modelContent,
            goodExpression= goodExpression,
            needTypo = binding.cbNeedTypo.isChecked,
            limitedWords =limitedWords,
            isNeedSynonyms=binding.cbIsNeedSynonyms.isChecked,
            isNeedAdvanced = binding.cbIsAdvanced.isChecked
        )
        binding.button3.isEnabled =false
        lifecycleScope.launch{
//            CompositionCorrectioner.Companion.correction(input = imageBase64, type = CORRECT_TYPE_IMAGE) //默认英文图片
             withContext(Dispatchers.Main){
                binding.tvResult.text ="sfhd"
                binding.button3.isEnabled =true
            }
        }
    }

    fun chooseImage(view: View) {
        getImage.launch("image/*")
    }
}