package com.ads.cal.picturetranslate.activity;

import android.app.AlertDialog;
import android.content.ClipData;
import android.content.ClipDescription;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.UnderlineSpan;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.camera.core.ExperimentalGetImage;

import com.ads.cal.picturetranslate.LogUtils;
import com.ads.cal.picturetranslate.PictureApplication;
import com.ads.cal.picturetranslate.PictureTranslateUtils;
import com.ads.cal.picturetranslate.R;
import com.ads.cal.picturetranslate.Util;
import com.ads.cal.picturetranslate.base.BaseActivity;
import com.ads.cal.picturetranslate.bean.PictureTranslateBean;
import com.ads.cal.picturetranslate.fragment.LoadingFragment;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.mlkit.vision.common.InputImage;
import com.google.mlkit.vision.text.Text;
import com.google.mlkit.vision.text.TextRecognizer;

@ExperimentalGetImage
public class PictureTranslateResultActivity extends BaseActivity {

    private ImageView imageView;
    private TextView result_txt;
    private PictureTranslateBean pictureTranslateBean;
    private LinearLayout moreSelectLayout;
    private ImageView standardImg, chineseImg, devanagariImg, japaneseImg, koreanImg;
    private Bitmap bitmap;
    private String path;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_picture_translate_result);
        initView();
        initData();
    }

    private void initView() {
        imageView = findViewById(R.id.image);
        LinearLayout back = findViewById(R.id.back);
        back.setOnClickListener(v -> {
            if (pictureTranslateBean != null && !TextUtils.isEmpty(pictureTranslateBean.getTitle())) {
                PictureApplication.getDataBaseManager().insertData(path, pictureTranslateBean.getTitle(), System.currentTimeMillis());
            }
            finish();
        });
        result_txt = findViewById(R.id.result_txt);
        result_txt.setMaxHeight(Util.getScreenHeight(this) - 200);
        TextView more_translate = findViewById(R.id.more);
        String text = getString(R.string.app_more_select);
        SpannableString spannableString = new SpannableString(text);
        // 添加点击事件
        ClickableSpan clickableSpan = new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                if (moreSelectLayout.getVisibility() != View.VISIBLE) {
                    moreSelectLayout.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void updateDrawState(TextPaint ds) {
                super.updateDrawState(ds);
                ds.setUnderlineText(true); // 添加下划线
                ds.setColor(Color.parseColor("#3E73DA")); // 设置文字颜色
            }
        };
        spannableString.setSpan(clickableSpan, 20, text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        // 更改颜色
        ForegroundColorSpan colorSpan = new ForegroundColorSpan(Color.parseColor("#3E73DA"));
        spannableString.setSpan(colorSpan, 20, text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        // 添加下划线
        UnderlineSpan underlineSpan = new UnderlineSpan();
        spannableString.setSpan(underlineSpan, 20, text.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

        more_translate.setText(spannableString);
        more_translate.setMovementMethod(LinkMovementMethod.getInstance()); // 启用链接的点击事件
        more_translate.setHighlightColor(Color.TRANSPARENT); // 设置点击背景颜色为透明
        initSelectMoreView();
        LinearLayout share = findViewById(R.id.share);
        share.setOnClickListener(v -> {
            Intent shareIntent = new Intent(Intent.ACTION_SEND);
            shareIntent.setType("text/plain");
            shareIntent.putExtra(Intent.EXTRA_TEXT, "分享内容"); // 设置要分享的内容
            startActivity(Intent.createChooser(shareIntent, "分享到"));
        });
        LinearLayout copy = findViewById(R.id.copy);
        copy.setOnClickListener(v -> {
            // 获取剪贴板管理器
            ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
            // 创建剪贴板数据
            String textToCopy = result_txt.getText().toString();
            clipboard.setPrimaryClip(ClipData.newPlainText("text", textToCopy));

            // 提示用户已复制文本
            Toast.makeText(getApplicationContext(), getString(R.string.app_toast_copied), Toast.LENGTH_SHORT).show();
        });
    }

    private void initSelectMoreView() {
        moreSelectLayout = findViewById(R.id.more_select_layout);
        RelativeLayout standardLayout = findViewById(R.id.standard_layout);
        RelativeLayout chineseLayout = findViewById(R.id.chinese_layout);
        RelativeLayout devanagariLayout = findViewById(R.id.devanagari_layout);
        RelativeLayout japaneseLayout = findViewById(R.id.japanese_layout);
        RelativeLayout koreanLayout = findViewById(R.id.korean_layout);

        standardImg = findViewById(R.id.standard_img);
        chineseImg = findViewById(R.id.chinese_img);
        devanagariImg = findViewById(R.id.devanagari_img);
        japaneseImg = findViewById(R.id.japanese_img);
        koreanImg = findViewById(R.id.korean_img);
        moreSelectLayout.setOnClickListener(v -> {
            if (moreSelectLayout.getVisibility() != View.GONE) {
                moreSelectLayout.setVisibility(View.GONE);
            }
        });
        standardLayout.setOnClickListener(v -> setCheck(0));
        chineseLayout.setOnClickListener(v -> setCheck(1));
        devanagariLayout.setOnClickListener(v -> setCheck(2));
        japaneseLayout.setOnClickListener(v -> setCheck(3));
        koreanLayout.setOnClickListener(v -> setCheck(4));
    }

    private void setCheck(int id) {
        switch (id) {
            case 0:
                standardImg.setVisibility(View.VISIBLE);
                chineseImg.setVisibility(View.GONE);
                devanagariImg.setVisibility(View.GONE);
                japaneseImg.setVisibility(View.GONE);
                koreanImg.setVisibility(View.GONE);
                PictureTranslateUtils.init().translateStandard(InputImage.fromBitmap(bitmap, 0), new MySuccessListener(), new MyFailureListener());
                break;
            case 1:
                standardImg.setVisibility(View.GONE);
                chineseImg.setVisibility(View.VISIBLE);
                devanagariImg.setVisibility(View.GONE);
                japaneseImg.setVisibility(View.GONE);
                koreanImg.setVisibility(View.GONE);
                PictureTranslateUtils.init().translateChinese(InputImage.fromBitmap(bitmap, 0), new MySuccessListener(), new MyFailureListener());
                break;
            case 2:
                standardImg.setVisibility(View.GONE);
                chineseImg.setVisibility(View.GONE);
                devanagariImg.setVisibility(View.VISIBLE);
                japaneseImg.setVisibility(View.GONE);
                koreanImg.setVisibility(View.GONE);
                PictureTranslateUtils.init().translateDevanagari(InputImage.fromBitmap(bitmap, 0), new MySuccessListener(), new MyFailureListener());
                break;
            case 3:
                standardImg.setVisibility(View.GONE);
                chineseImg.setVisibility(View.GONE);
                devanagariImg.setVisibility(View.GONE);
                japaneseImg.setVisibility(View.VISIBLE);
                koreanImg.setVisibility(View.GONE);
                PictureTranslateUtils.init().translateJapanese(InputImage.fromBitmap(bitmap, 0), new MySuccessListener(), new MyFailureListener());
                break;
            case 4:
                standardImg.setVisibility(View.GONE);
                chineseImg.setVisibility(View.GONE);
                devanagariImg.setVisibility(View.GONE);
                japaneseImg.setVisibility(View.GONE);
                koreanImg.setVisibility(View.VISIBLE);
                PictureTranslateUtils.init().translateKorean(InputImage.fromBitmap(bitmap, 0), new MySuccessListener(), new MyFailureListener());
                break;
        }
        if (moreSelectLayout.getVisibility() != View.GONE) {
            moreSelectLayout.setVisibility(View.GONE);
        }
        showLoadingFragment(new LoadingFragment());
    }

    private void initData() {
        Intent intent = getIntent();
        if (null != intent) {
            pictureTranslateBean = (PictureTranslateBean) intent.getSerializableExtra("bean");
        }
        if (pictureTranslateBean == null) {
            return;
        }
        path = pictureTranslateBean.getImageUrl();
        bitmap = BitmapFactory.decodeFile(path);
        imageView.setImageBitmap(bitmap);
        result_txt.setText(pictureTranslateBean.getTitle());
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if (pictureTranslateBean != null && !TextUtils.isEmpty(pictureTranslateBean.getTitle())) {
            PictureApplication.getDataBaseManager().insertData(path, pictureTranslateBean.getTitle(), System.currentTimeMillis());
        }
    }


    public static void startPictureTranslateResultActivity(Context context, PictureTranslateBean bean) {
        Intent intent = new Intent(context, PictureTranslateResultActivity.class);
        intent.putExtra("bean", bean);
        context.startActivity(intent);
    }

    private class MySuccessListener implements OnSuccessListener<Text> {

        @Override
        public void onSuccess(Text text) {
            LogUtils.e("AAAAAA", text.getText());
            result_txt.setText(text.getText());
            pictureTranslateBean.setTitle(text.getText());
            PictureTranslateBean bean = new PictureTranslateBean();
            bean.setImageUrl(path);
            bean.setTitle(text.getText());
            bean.setTime(System.currentTimeMillis());
            hideLoadingFragment();

        }
    }

    private class MyFailureListener implements OnFailureListener {


        @Override
        public void onFailure(@NonNull Exception e) {
            hideLoadingFragment();
        }
    }
}
