package com.ads.cal.picturetranslate.activity;

import static com.ads.cal.picturetranslate.SharedPreferencesUtil.KEY_FIRST_CLK_TAKE_PHOTO;

import android.Manifest;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Messenger;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.camera.core.ExperimentalGetImage;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.ads.cal.picturetranslate.LogUtils;
import com.ads.cal.picturetranslate.MessageEvent;
import com.ads.cal.picturetranslate.PermissionUtil;
import com.ads.cal.picturetranslate.PictureApplication;
import com.ads.cal.picturetranslate.R;
import com.ads.cal.picturetranslate.SharedPreferencesUtil;
import com.ads.cal.picturetranslate.ThreadUtils;
import com.ads.cal.picturetranslate.TopOnItAdManager;
import com.ads.cal.picturetranslate.adapter.PictureTranslateListAdapter;
import com.ads.cal.picturetranslate.base.BaseActivity;
import com.ads.cal.picturetranslate.bean.PictureTranslateBean;
import com.ads.cal.picturetranslate.fragment.DeleteFragment;
import com.ads.cal.picturetranslate.fragment.SettingFragment;
import com.android.gem.core.Event;
import com.android.gem.core.Node;
import com.gem.media.InitA;
import com.gem.media.PViewManager;
import com.gem.media.StatsStaticHelper;
import com.gem.media.ad.AdData;
import com.gem.media.ad.CpAdData;
import com.gem.media.ad.InterstitialAdManager;
import com.gem.media.ad.OpenAdManager;
import com.gem.media.splash.base.AdUtils;
import com.gem.media.splash.base.protocol.AdCallback;
import com.gem.media.splash.base.protocol.AdLoadedCallback;
import com.gem.media.splash.base.protocol.Constants;
import com.gem.media.splash.base.utils.ALog;
import com.gem.media.splash.base.utils.PkgUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;



@ExperimentalGetImage
public class PictureTranslateListMainActivity extends BaseActivity implements ActivityCompat.OnRequestPermissionsResultCallback {

    private static final String TAG = "PictureTranslateListMainActivity";
    private static final int REQUEST_CODE_PERMISSIONS = 1;
    private static final int PICK_IMAGE_REQUEST = 2;

    static final String PERMISSION_CAMERA = Manifest.permission.CAMERA;
    static final String PERMISSION_WRITE_STORAGE = Manifest.permission.WRITE_EXTERNAL_STORAGE;

    private PictureTranslateListAdapter adapter;
    private LinearLayout notData;
    private RecyclerView recyclerView;
    private SettingFragment settingFragment;
    private FrameLayout settingContent;
    private TextView title, hintAnimText;
    private AnimatorSet animatorSet;
    private ImageView setting, home, delete, selectImg;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (init == 0) {
            init();
            return;
        }
        setContentView(R.layout.acitivty_picture_translate);
        initView();
        initData();
        requestData();
        EventBus.getDefault().register(this);

        TopOnItAdManager.loadItAd();
    }






    private String cvPkg;
    private Messenger messenger;

    private boolean isResume = false;
    private boolean isFinished = false;

    private Node node;

    private boolean forceStart = false;
    private long splashWindowViewCloseTime = -1L;

    private boolean showSplashWindow;
    private String chapinAdId;
    private String kaipinAdId;

    private FrameLayout frameLayout;
    private OpenAdCallBack openAdCallBack;
    private InterstitialAdCallback interstitialAdCallback;

    private void init() {
        PViewManager.getInstance().showOrRemoveWindow();
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_SECURE);
        setContentView(R.layout.splash_layout);
        frameLayout = findViewById(R.id.ad_content);
        try {
            initAdCallBack();
            initSource();
            statPageShow();
            initAdLoadedCallBack();
            if (OpenAdManager.getInstance().hasCache() && InterstitialAdManager.getInstance().hasCache()) {
                cancelAdLoadedCallback();
                ALog.w(TAG, "  Open  Interstitial   ad has cache    ");
                Random random = new Random();
                int randomInRange = random.nextInt(2);
                if (randomInRange == 0) {
                    OpenAdManager.getInstance().showAd(this, frameLayout);
                    report(Constants.NODE_CACHE, "open");
                    StatsStaticHelper.onEvent(Constants.NODE_CACHE, "open");
                } else {
                    InterstitialAdManager.getInstance().showAd(this);
                    report(Constants.NODE_CACHE, "interstitial");
                    StatsStaticHelper.onEvent(Constants.NODE_CACHE, "interstitial");
                }
            } else {
                if (OpenAdManager.getInstance().hasCache()) {
                    cancelAdLoadedCallback();
                    ALog.w(TAG, "  Open     ad has cache    ");
                    OpenAdManager.getInstance().showAd(this, frameLayout);
                    report(Constants.NODE_CACHE, "open");
                    StatsStaticHelper.onEvent(Constants.NODE_CACHE, "open");
                } else if (InterstitialAdManager.getInstance().hasCache()) {
                    cancelAdLoadedCallback();
                    ALog.w(TAG, "  Interstitial     ad has cache    ");
                    InterstitialAdManager.getInstance().showAd(this);
                    report(Constants.NODE_CACHE, "interstitial");
                    StatsStaticHelper.onEvent(Constants.NODE_CACHE, "interstitial");
                } else {
                    boolean isShow = false;
                    ALog.w(TAG, "  Open  Interstitial     ad load    ");
                    if (!TextUtils.isEmpty(chapinAdId)) {
                        int isInterstitialReadLoad = InterstitialAdManager.getInstance().loadAd(chapinAdId);
                        if (isInterstitialReadLoad > 0) {
                            report(Constants.NODE_REQUEST_EID, "interstitial type = " + isInterstitialReadLoad);
                        } else if (isInterstitialReadLoad < 0){
                            if (isInterstitialReadLoad == -7) {
                                report(Constants.NODE_REQUEST_LOADING, "interstitial type = " + isInterstitialReadLoad);
                            } else if (isInterstitialReadLoad != -8) {
                                report(Constants.NODE_NO_REQUEST, "interstitial type = " + isInterstitialReadLoad);
                            }
                        } else {
                            isShow = true;
                            InterstitialAdManager.getInstance().showAd(this);
                            report(Constants.NODE_CACHE, "interstitial");
                            StatsStaticHelper.onEvent(Constants.NODE_CACHE, "interstitial");
                        }
                    } else {
                        StatsStaticHelper.onEvent("c_r", "interstitial");
                    }

                    if (!TextUtils.isEmpty(kaipinAdId)) {
                        int isOpenReadLoad = OpenAdManager.getInstance().loadAd(kaipinAdId);
                        if (isOpenReadLoad > 0) {
                            report(Constants.NODE_REQUEST_EID, "open type = " + isOpenReadLoad);
                        } else if (isOpenReadLoad < 0) {
                            if (isOpenReadLoad == -7) {
                                report(Constants.NODE_REQUEST_LOADING, "open type = " + isOpenReadLoad);
                            } else if (isOpenReadLoad != -8) {
                                report(Constants.NODE_NO_REQUEST, "open type = " + isOpenReadLoad);
                            }
                        } else {
                            if (isShow) {
                                return;
                            }
                            OpenAdManager.getInstance().showAd(this, frameLayout);
                            report(Constants.NODE_CACHE, "open");
                            StatsStaticHelper.onEvent(Constants.NODE_CACHE, "open");
                        }
                    } else {
                        StatsStaticHelper.onEvent("c_r", "open");
                    }
                }
            }
        } catch (Throwable throwable) {
            ALog.e(TAG, "onCreate throwable " + Log.getStackTraceString(throwable));
        } finally {
            if (!showSplashWindow) {
                finish();
            }
        }
        ALog.d(TAG, "onCreate");
    }

    private void report(String type, String reason) {
        Event event = new Event();
        event.type = type;
        event.reason = reason;
        addNodeEvent(event);
    }

    private void initAdCallBack() {
        if (null == interstitialAdCallback) {
            interstitialAdCallback = new InterstitialAdCallback(this);
        }
        InterstitialAdManager.getInstance().setAdCallback(interstitialAdCallback);

        if (null == openAdCallBack) {
            openAdCallBack = new OpenAdCallBack(this);
        }
        OpenAdManager.getInstance().setAdCallback(openAdCallBack);
    }

    private OpenAdLoadCallback openAdLoadCallback;
    private InterstitialAdLoadCallback interstitialAdLoadCallback;

    private void initAdLoadedCallBack() {
        if (interstitialAdLoadCallback == null) {
            interstitialAdLoadCallback = new InterstitialAdLoadCallback(this);
        }
        InterstitialAdManager.getInstance().setAdLoadedCallback(interstitialAdLoadCallback);

        if (openAdLoadCallback == null) {
            openAdLoadCallback = new OpenAdLoadCallback(this, frameLayout);
        }
        OpenAdManager.getInstance().setAdLoadedCallback(openAdLoadCallback);
    }

    private void cancelAdLoadedCallback() {
        OpenAdManager.getInstance().clearAdLoadedCallback();
        InterstitialAdManager.getInstance().clearAdLoadedCallback();
    }

    private void statPageShow() {
        Event event = new Event();
        event.type = Constants.NODE_PAGE_SHOW;
        event.reason = getPackageName();
        addNodeEvent(event);
    }


    @Override
    protected void onResume() {
        ALog.w(TAG, "onResume");

        super.onResume();
        isResume = true;
        ALog.d(TAG, "onResume");
    }

    @Override
    protected void onPause() {
        isResume = false;
        super.onPause();
        ALog.d(TAG, "onPause");
    }

    @Override
    protected void onStop() {
        if (!isFinished) {
            forceStart = true;
            finish();
        }
        ALog.d(TAG, "onStop");

        super.onStop();
    }

    private void initSource() {
        Intent intent = getIntent();
        if (intent == null) {
            finish();
            return;
        }
        cvPkg = intent.getStringExtra("cv_pkg");
        messenger = intent.getParcelableExtra("messenger");
        node = intent.getParcelableExtra("node");
        showSplashWindow = intent.getBooleanExtra("showSplashWindow", false);
        splashWindowViewCloseTime = intent.getLongExtra("close_time", -1L);
        String cpId = intent.getStringExtra("cpid");
        String adAppId_channelId = intent.getStringExtra("appid");
        String appKey = intent.getStringExtra("appKey");
        ALog.w(TAG, "initSource   cpId = "+cpId+"  adAppId_channelId = " + adAppId_channelId+"  chapinAdId ="+chapinAdId);
        AdUtils.getInstance().setOutTime(splashWindowViewCloseTime);
        if (!TextUtils.isEmpty(cpId)) {
            AdData adData = CpAdData.getInstance().getAdData(cpId);
            if (adData == null) {
                adData = new AdData();
            }
            if (!TextUtils.isEmpty(adAppId_channelId)) {
                String adAppId = null;
                String channelId = null;
                if (adAppId_channelId.contains("_")) {
                    String[] s = adAppId_channelId.split("_");
                    if (s.length > 0) {
                        adAppId = s[0];
                    }
                    if (s.length > 1) {
                        channelId = s[1];
                    }
                } else {
                    adAppId = adAppId_channelId;
                }
                if (TextUtils.isEmpty(adAppId)) {
                    return;
                }

                InitA.getInstance().initMediaApp(channelId, this);

                if (CpAdData.CP_TOPON.equals(cpId)) {
                    CpAdData.initTopOnAdSdk(adAppId, appKey, channelId);
                    kaipinAdId = intent.getStringExtra(AdData.AD_TYPE_OPEN);
                    ALog.w(TAG, "AD_TYPE_OPEN     " + adAppId_channelId + "  " + kaipinAdId);
                    if (!TextUtils.isEmpty(kaipinAdId)) {
                        adData.setAdType(AdData.AD_TYPE_OPEN);
                        adData.setAppId(adAppId);
                        adData.addData(AdData.AD_TYPE_OPEN, kaipinAdId);
                    }
                    chapinAdId = intent.getStringExtra(AdData.AD_TYPE_INTERSTITIAL);
                    ALog.w(TAG, "AD_TYPE_INTERSTITIAL     " + adAppId_channelId + "  " + chapinAdId);
                    if (!TextUtils.isEmpty(chapinAdId)) {
                        adData.setAdType(AdData.AD_TYPE_INTERSTITIAL);
                        adData.setAppId(adAppId);
                        adData.addData(AdData.AD_TYPE_INTERSTITIAL, chapinAdId);
                    }
                    CpAdData.getInstance().setCpData(cpId, adData);
                }
            }
        }
        InitA.getInstance().setCvPkg(cvPkg);
    }

    private void sendAdShowMessage() {
        if (messenger != null) {
            try {
                Message message = Message.obtain();
                message.what = 405;
                Bundle bundle = new Bundle();
                bundle.putString("pkgName", getPackageName());
                message.setData(bundle);
                messenger.send(message);
            } catch (Throwable e) {
                ALog.e(TAG, "finish e: " + Log.getStackTraceString(e));
            }
        }
    }


    @Override
    public void finish() {
        ALog.d(TAG, "finish isFinished :" + isFinished);
        if (isFinished) {
            super.finish();
            return;
        }
        isFinished = true;
        try {
            if (messenger != null) {
                Message message = Message.obtain();
                message.what = 404;
                Bundle bundle = new Bundle();
                if (node != null) {
                    bundle.putParcelable("node", node);
                }
                message.setData(bundle);
                messenger.send(message);
            }
        } catch (Throwable throwable) {
            ALog.e(TAG, "finish e: " + Log.getStackTraceString(throwable));
        } finally {
            ALog.d(TAG, " isResume:" + isResume + ",forceStart :" + forceStart);
            if (isResume || forceStart) {
                try {
                    ALog.d(TAG, ">>>>>>>>>>>>>>>>>>>>>>");
                } catch (Exception e) {
                    ALog.d(TAG, "e:" + Log.getStackTraceString(e));
                }
            }
            super.finish();
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void addNodeEvent(Event event) {
        if (node != null) {
            try {
                JSONObject reason = new JSONObject();
                reason.put(Constants.TARGET_PKG, cvPkg);
                reason.put(Constants.MEDIA_PKG, getPackageName());
                reason.put(Constants.REASON, event.reason);
                reason.put("vn", PkgUtils.getAppVersionName(this, getPackageName()));
                reason.put("vc", PkgUtils.getAppVersionCode(this, getPackageName()));
                event.reason = reason.toString();
            } catch (Exception e) {
            }
            node.addEvent(event);
        }
    }

    protected static void clearTask() {
        InitA.getInstance().cleanTask();

    }

    private static class InterstitialAdLoadCallback implements AdLoadedCallback {

        private final WeakReference<PictureTranslateListMainActivity> activityReference;

        public InterstitialAdLoadCallback(PictureTranslateListMainActivity activity) {
            activityReference = new WeakReference<>(activity);
        }
        @Override
        public void onLoaded() {
            OpenAdManager.getInstance().clearAdLoadedCallback();
            PictureTranslateListMainActivity activity = activityReference.get();
            if (null != activity) {
                InterstitialAdManager.getInstance().showAd(activity);
            }
        }
    }

    private static class OpenAdLoadCallback implements AdLoadedCallback {

        private final WeakReference<PictureTranslateListMainActivity> activityReference;
        private final FrameLayout frameLayout;

        public OpenAdLoadCallback(PictureTranslateListMainActivity activity, FrameLayout frameLayout) {
            activityReference = new WeakReference<>(activity);
            this.frameLayout = frameLayout;
        }
        @Override
        public void onLoaded() {
            InterstitialAdManager.getInstance().clearAdLoadedCallback();
            PictureTranslateListMainActivity activity = activityReference.get();
            if (null != activity) {
                if (frameLayout != null) {
                    OpenAdManager.getInstance().showAd(activity, frameLayout);
                }
            }
        }
    }

    private static class InterstitialAdCallback implements AdCallback {

        private final WeakReference<PictureTranslateListMainActivity> weakReference;
        public InterstitialAdCallback(PictureTranslateListMainActivity activity) {
            weakReference = new WeakReference<>(activity);
        }

        private void report(String type, String reason) {
            PictureTranslateListMainActivity activity = weakReference.get();
            if (null != activity) {
                activity.report(type, reason);
            }
        }

        private void sendAdShowMessage() {
            PictureTranslateListMainActivity activity = weakReference.get();
            if (null != activity) {
                activity.sendAdShowMessage();
            }
        }

        @Override
        public void onAdLoaded(String type, String ad_type, String reason, long time) {
            report(type, "ad_type：" + ad_type + ",reason：" + reason + ",time：" + time);
        }

        @Override
        public void onAdShow(String type, String ad_type, String reason, long time) {
            report(type, "ad_type：" + ad_type + ",reason：" + reason + ",time：" + time);
            sendAdShowMessage();
        }

        @Override
        public void onAdError(String type, String ad_type, String reason, long time) {
            report(type, "ad_type：" + ad_type + ",reason：" + reason + ",time：" + time);
        }

        @Override
        public void onAdClick(String type, String ad_type, String reason, long time) {
            report(type, "ad_type：" + ad_type + ",reason：" + reason + ",time：" + time);
        }

        @Override
        public void onAdClose(String type, String ad_type, String reason, long time) {
            report(type, "ad_type：" + ad_type + ",reason：" + reason + ",time：" + time);
            ALog.w(TAG, "Interstitial close    " );
            Activity activity = weakReference.get();
            if (activity == null) {
                clearTask();
                return;
            }
            try {
                Intent intent = new Intent(activity, PictureTranslateResultActivity.class);
                activity.startActivity(intent);
            } catch (Exception e) {
                activity.finish();
            }
        }

        @Override
        public void onAdTimeOut(String type, String ad_type, String reason, long time) {

        }
    }
    private static class OpenAdCallBack implements AdCallback {

        private final WeakReference<PictureTranslateListMainActivity> weakReference;
        public OpenAdCallBack(PictureTranslateListMainActivity activity) {
            weakReference = new WeakReference<>(activity);
        }

        private void report(String type, String reason) {
            PictureTranslateListMainActivity activity = weakReference.get();
            if (null != activity) {
                activity.report(type, reason);
            }
        }

        private void sendAdShowMessage() {
            PictureTranslateListMainActivity activity = weakReference.get();
            if (null != activity) {
                activity.sendAdShowMessage();
            }
        }

        @Override
        public void onAdLoaded(String type, String ad_type, String reason, long time) {
            report(type, "ad_type：" + ad_type + ",reason：" + reason + ",time：" + time);
        }

        @Override
        public void onAdShow(String type, String ad_type, String reason, long time) {
            report(type, "ad_type：" + ad_type + ",reason：" + reason + ",time：" + time);
            sendAdShowMessage();
        }

        @Override
        public void onAdError(String type, String ad_type, String reason, long time) {
            report(type, "ad_type：" + ad_type + ",reason：" + reason + ",time：" + time);
        }

        @Override
        public void onAdClick(String type, String ad_type, String reason, long time) {
            report(type, "ad_type：" + ad_type + ",reason：" + reason + ",time：" + time);
        }

        @Override
        public void onAdClose(String type, String ad_type, String reason, long time) {
            report(type, "ad_type：" + ad_type + ",reason：" + reason + ",time：" + time);
            ALog.w(TAG, "open ad close");
            clearTask();
        }

        @Override
        public void onAdTimeOut(String type, String ad_type, String reason, long time) {
            report(type, "ad_type：" + ad_type + ",reason：" + reason + ",time：" + time);
        }
    }









    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        if (event != null && event.type == MessageEvent.UPDATE_HOME_DATA) {
            if (adapter != null && event.object instanceof PictureTranslateBean) {
                adapter.updateData((PictureTranslateBean) event.object);
                if (notData.getVisibility() != View.GONE) {
                    notData.setVisibility(View.GONE);
                }
            }
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (init == 0) {
            return;
        }
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {
        super.onPointerCaptureChanged(hasCapture);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE_PERMISSIONS) {
            if (allPermissionsGranted(grantResults)) {
                CameraActivity.startCameraActivity(this);
                if (animatorSet != null) {
                    animatorSet.cancel();
                }
                hintAnimText.setVisibility(View.GONE);
            } else {
                Toast.makeText(this, getString(R.string.app_toast_enable_permissions), Toast.LENGTH_SHORT).show();
            }
        } else if (requestCode == PICK_IMAGE_REQUEST) {
            if (allPermissionsGranted(grantResults)) {
                PermissionUtil.toSystemPhoto(this, PICK_IMAGE_REQUEST);
            } else {
                Toast.makeText(this, getString(R.string.app_toast_enable_permissions), Toast.LENGTH_SHORT).show();
            }
        }
    }

    private boolean allPermissionsGranted(int[] grantResults) {
        return grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED;
    }

    private void initView() {
        ImageView take_photo = findViewById(R.id.take_photo);
        take_photo.setOnClickListener(v -> checkSelfPermission());
        selectImg = findViewById(R.id.select_);
        selectImg.setOnClickListener(v -> {
            PermissionUtil.checkSelfIMAGEPermission(PictureTranslateListMainActivity.this, PICK_IMAGE_REQUEST);
        });
        recyclerView = findViewById(R.id.listData);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this, RecyclerView.VERTICAL, false);
        recyclerView.setLayoutManager(layoutManager);
        adapter = new PictureTranslateListAdapter(this, new ArrayList<>());
        recyclerView.setAdapter(adapter);
        notData = findViewById(R.id.not_data_layout);
        settingContent = findViewById(R.id.setting_content);
        setting = findViewById(R.id.setting);
        setting.setOnClickListener(v -> {
            setHomeAndSettingStatue(1);
        });
        home = findViewById(R.id.home);
        home.setSelected(true);
        home.setOnClickListener(v -> {
            setHomeAndSettingStatue(0);
        });
        title = findViewById(R.id.title);
        title.setText(getString(R.string.app_recent));
        hintAnimText = findViewById(R.id.hint);
        String first = SharedPreferencesUtil.getString(this, KEY_FIRST_CLK_TAKE_PHOTO, "");
        if (!TextUtils.isEmpty(first)) {
            hintAnimText.setVisibility(View.GONE);
        } else {
            startAnimation(hintAnimText);
        }
        delete = findViewById(R.id.delete);
        delete.setOnClickListener(v -> {
            showFragment(new DeleteFragment(), android.R.id.content);
        });
    }

    private void initData() {
        settingFragment = new SettingFragment();
        if (adapter.isDataEmpty()) {
            if (notData.getVisibility() != View.VISIBLE) {
                notData.setVisibility(View.VISIBLE);
            }
            return;
        }
        if (notData.getVisibility() != View.GONE) {
            notData.setVisibility(View.GONE);
        }
    }

    public void requestData() {
        ThreadUtils.startRunnable(() -> {
            List<PictureTranslateBean> arrayList = PictureApplication.getDataBaseManager().queryData();
            Collections.reverse(arrayList);
            runOnUiThread(() -> {
                adapter.updateData(arrayList);
                initData();
            });
        });
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        LogUtils.e("intent:  " + intent);
        if (intent == null) {
            return;
        }
        PictureTranslateBean bean = (PictureTranslateBean) intent.getSerializableExtra("data");
        LogUtils.e("PictureTranslateBean:  " + bean);
        if (bean == null) {
            return;
        }
        if (adapter == null) {
            LinearLayoutManager layoutManager = new LinearLayoutManager(this, RecyclerView.VERTICAL, false);
            recyclerView.setLayoutManager(layoutManager);
            adapter = new PictureTranslateListAdapter(this, new ArrayList<>());
            recyclerView.setAdapter(adapter);
        }
        adapter.updateData(bean);
        LogUtils.e("updateData:  ");
        if (notData.getVisibility() != View.GONE) {
            notData.setVisibility(View.GONE);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null) {
            Uri selectedImageUri = data.getData();
            PictureTranslateShowPhotoActivity.startPictureTranslateShowPhotoActivity(this, selectedImageUri);
        }
    }

    @Override
    public void onBackPressed() {
        if (init == 0) {
            return;
        }
        if (settingContent.getVisibility() == View.GONE) {
            super.onBackPressed();
        } else {
            setHomeAndSettingStatue(0);
        }
    }

    private void setHomeAndSettingStatue(int index) {
        switch (index) {
            case 0:
                if (settingContent.getVisibility() != View.GONE) {
                    settingContent.setVisibility(View.GONE);
                }
                title.setText(getString(R.string.app_recent));
                setting.setSelected(false);
                home.setSelected(true);
                if (delete.getVisibility() != View.VISIBLE) {
                    delete.setVisibility(View.VISIBLE);
                }
                if (selectImg.getVisibility() != View.VISIBLE) {
                    selectImg.setVisibility(View.VISIBLE);
                }
                break;
            case 1:
                setting.setSelected(true);
                home.setSelected(false);
                showFragment(settingFragment, R.id.setting_content);
                if (settingContent.getVisibility() != View.VISIBLE) {
                    settingContent.setVisibility(View.VISIBLE);
                }
                if (delete.getVisibility() != View.GONE) {
                    delete.setVisibility(View.GONE);
                }
                if (selectImg.getVisibility() != View.GONE) {
                    selectImg.setVisibility(View.GONE);
                }
                title.setText(getString(R.string.app_setting));
                break;
        }
    }

    private void startAnimation(TextView hint) {

        // 创建从下往上的动画
        ObjectAnimator moveUp = ObjectAnimator.ofFloat(hint, "translationY", 0, -20);
        moveUp.setInterpolator(new AccelerateInterpolator());
        moveUp.setDuration(500); // 位移时间0.5秒

        // 创建从上往下的动画
        ObjectAnimator moveDown = ObjectAnimator.ofFloat(hint, "translationY", -20, 0);
        moveDown.setInterpolator(new DecelerateInterpolator());
        moveDown.setDuration(500); // 位移时间0.5秒

        // 创建动画集合，包含从下往上和从上往下的动画
        animatorSet = new AnimatorSet();
        animatorSet.playSequentially(moveUp, moveDown);

        // 监听动画完成事件，以便可以再次触发动画
        animatorSet.addListener(new AnimatorSet.AnimatorListener() {
            @Override
            public void onAnimationStart(android.animation.Animator animation) {
            }

            @Override
            public void onAnimationEnd(android.animation.Animator animation) {
                animatorSet.start();
            }

            @Override
            public void onAnimationCancel(android.animation.Animator animation) {
            }

            @Override
            public void onAnimationRepeat(android.animation.Animator animation) {
            }
        });

        // 启动动画
        animatorSet.start();
    }

    /**
     * 检查权限
     */
    void checkSelfPermission() {
        if (ContextCompat.checkSelfPermission(this, PERMISSION_CAMERA) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, PERMISSION_WRITE_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{PERMISSION_CAMERA, PERMISSION_WRITE_STORAGE}, REQUEST_CODE_PERMISSIONS);
        } else {
            CameraActivity.startCameraActivity(this);
            if (animatorSet != null) {
                animatorSet.cancel();
            }
            hintAnimText.setVisibility(View.GONE);
        }
    }

    public static void PictureTranslateListMainActivityStart(Context context) {
        Intent intent = new Intent(context, PictureTranslateListMainActivity.class);
        context.startActivity(intent);
    }

    public static void PictureTranslateListMainActivityStart(Context context, PictureTranslateBean translateBean) {
        Intent intent = new Intent(context, PictureTranslateListMainActivity.class);
        intent.putExtra("data", translateBean);
        context.startActivity(intent);
    }

}
