package com.sobot.widget.ui.base;

import android.Manifest;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.hardware.Camera;
import android.os.Build;
import android.os.Bundle;
import android.os.LocaleList;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.FragmentActivity;
import androidx.core.content.ContextCompat;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.sobot.utils.SobotSharedPreferencesUtil;
import com.sobot.utils.SobotSystemUtils;
import com.sobot.widget.R;
import com.sobot.widget.SobotWidgetApi;
import com.sobot.widget.ui.SobotBaseConstant;
import com.sobot.widget.ui.SobotMarkConfig;
import com.sobot.widget.ui.image.SobotRCImageView;
import com.sobot.widget.ui.notchlib.SobotINotchScreen;
import com.sobot.widget.ui.notchlib.SobotNotchScreenManager;
import com.sobot.widget.ui.permission.SobotPermissionListener;
import com.sobot.widget.ui.permission.SobotPermissionListenerImpl;
import com.sobot.widget.ui.permission.SobotPermissionTipDialog;
import com.sobot.widget.ui.statusbar.SobotStatusBarUtils;
import com.sobot.widget.ui.toast.SobotToastUtil;
import com.sobot.widget.ui.utils.SobotResourceUtils;
import com.sobot.widget.ui.utils.SobotWidgetUtils;

import java.io.File;
import java.util.Locale;

/**
 * 基础 activity
 */
public abstract class SobotBaseActivity extends FragmentActivity {

    //相机拍照后返回的照片
    protected File cameraFile;
    //权限回调
    public SobotPermissionListener permissionListener;
    private int initMode;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        //修改国际化语言
        changeAppLanguage();
        super.onCreate(savedInstanceState);
        initMode = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
        if (Build.VERSION.SDK_INT != Build.VERSION_CODES.O) {
            if (!SobotWidgetApi.getSwitchMarkStatus(SobotMarkConfig.LANDSCAPE_SCREEN)) {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);//竖屏
            } else {
                setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);//横屏

            }
        }
        if (SobotWidgetApi.getSwitchMarkStatus(SobotMarkConfig.LANDSCAPE_SCREEN) && SobotWidgetApi.getSwitchMarkStatus(SobotMarkConfig.DISPLAY_INNOTCH)) {
            // 支持显示到刘海区域
            SobotNotchScreenManager.getInstance().setDisplayInNotch(this);
            // 设置Activity全屏
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        }

        setContentView(getContentViewResId());
        int sobot_status_bar_color = getStatusBarColor();
        if (sobot_status_bar_color != 0) {
            try {
                SobotStatusBarUtils.setStatusBarColor(this, sobot_status_bar_color);
            } catch (Exception e) {
                //请传入正确的颜色值
            }
        }
        setUpToolBar();
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        View toolBar = findViewById(getResId("sobot_layout_titlebar"));
        if (toolBar != null) {
            setUpToolBarLeftMenu();

            setUpToolBarRightMenu();
        }
        try {
            initBundleData(savedInstanceState);
            initView();
            initData();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //左上角返回按钮水滴屏适配
        if (getLeftMenu() != null) {
            displayInNotch(getLeftMenu());
        }
    }

    public void displayInNotch(final View view) {
        if (SobotWidgetApi.getSwitchMarkStatus(SobotMarkConfig.LANDSCAPE_SCREEN) && SobotWidgetApi.getSwitchMarkStatus(SobotMarkConfig.DISPLAY_INNOTCH) && view != null) {
            // 获取刘海屏信息
            SobotNotchScreenManager.getInstance().getNotchInfo(this, new SobotINotchScreen.NotchScreenCallback() {
                @Override
                public void onResult(SobotINotchScreen.NotchScreenInfo notchScreenInfo) {
                    if (notchScreenInfo.hasNotch) {
                        for (Rect rect : notchScreenInfo.notchRects) {
                            if (view instanceof WebView && view.getParent() instanceof LinearLayout) {
                                LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) view.getLayoutParams();
                                layoutParams.rightMargin = (rect.right > 110 ? 110 : rect.right) + 14;
                                layoutParams.leftMargin = (rect.right > 110 ? 110 : rect.right) + 14;
                                view.setLayoutParams(layoutParams);
                            } else if (view instanceof WebView && view.getParent() instanceof RelativeLayout) {
                                RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view.getLayoutParams();
                                layoutParams.rightMargin = (rect.right > 110 ? 110 : rect.right) + 14;
                                layoutParams.leftMargin = (rect.right > 110 ? 110 : rect.right) + 14;
                                view.setLayoutParams(layoutParams);
                            } else {
                                view.setPadding((rect.right > 110 ? 110 : rect.right) + view.getPaddingLeft(), view.getPaddingTop(), (rect.right > 110 ? 110 : rect.right) + view.getPaddingRight(), view.getPaddingBottom());
                            }
                        }
                    }
                }
            });

        }
    }

    /**
     * 获取系统首选语言
     * 注意：该方法获取的是用户实际设置的不经API调整的系统首选语言
     */
    public static Locale getSysPreferredLocale() {
        Locale locale;
        //7.0以下直接获取系统默认语言
        if (Build.VERSION.SDK_INT < 24) {
            // 等同于context.getResources().getConfiguration().locale;
            locale = Locale.getDefault();
            // 7.0以上获取系统首选语言
        } else {
            /*
             * 以下两种方法等价，都是获取经API调整过的系统语言列表（可能与用户实际设置的不同）
             * 1.context.getResources().getConfiguration().getLocales()
             * 2.LocaleList.getAdjustedDefault()
             */
            // 获取用户实际设置的语言列表
            locale = LocaleList.getDefault().get(0);
        }
        return locale;
    }


    //使用系统语言
    public void useSysLanguage() {
        try {
            Locale locale = getSysPreferredLocale();
            updateLanguage(locale);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void changeAppLanguage() {
        try {
            Locale locale = (Locale) SobotSharedPreferencesUtil.getInstance(getSobotBaseContext()).get("SobotLanguage", Locale.class);
            if (locale == null) {
                //获取系统语言
                locale = getSysPreferredLocale();
            }
            updateLanguage(locale);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void updateLanguage(Locale locale) {
        try {
            if (locale != null) {
                Resources resources = getResources();
                DisplayMetrics metrics = resources.getDisplayMetrics();
                Configuration configuration = resources.getConfiguration();
                //Android 7.0以上的方法
                if (Build.VERSION.SDK_INT >= 24) {
                    configuration.setLocale(locale);
                    configuration.setLocales(new LocaleList(locale));
                    createConfigurationContext(configuration);
                    //实测，updateConfiguration这个方法虽然很多博主说是版本不适用
                    //但是我的生产环境androidX+Android Q环境下，必须加上这一句，才可以通过重启App来切换语言
                    resources.updateConfiguration(configuration, metrics);

                } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                    //Android 4.1 以上方法
                    configuration.setLocale(locale);
                    resources.updateConfiguration(configuration, metrics);
                } else {
                    configuration.locale = locale;
                    resources.updateConfiguration(configuration, metrics);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void setUpToolBarRightMenu() {
        if (getRightMenu() != null) {
            getRightMenu().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onRightMenuClick(v);
                }
            });
        }
    }

    protected void setUpToolBarLeftMenu() {
        if (getLeftMenu() != null) {
            getLeftMenu().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onLeftMenuClick(v);
                }
            });
        }
    }

    protected int getStatusBarColor() {
        return getResColor("sobot_status_bar_color");
    }

    protected void setUpToolBar() {
        View toolBar = getToolBar();
        if (toolBar == null) {
            return;
        }
    }

    protected View getToolBar() {
        return findViewById(getResId("sobot_layout_titlebar"));
    }

    protected TextView getLeftMenu() {
        return findViewById(getResId("sobot_tv_left"));
    }

    protected TextView getRightSecondMenu() {
        return findViewById(getResId("sobot_tv_right_second"));
    }

    protected TextView getRightThirdMenu() {
        return findViewById(getResId("sobot_tv_right_third"));
    }

    protected TextView getRightMenu() {
        return findViewById(getResId("sobot_tv_right"));
    }

    protected View getTitleView() {
        return findViewById(getResId("sobot_text_title"));
    }

    protected SobotRCImageView getAvatarView() {
        return findViewById(getResId("sobot_avatar_iv"));
    }


    /**
     * @param resourceId
     * @param textId
     * @param isShow
     */
    protected TextView showRightMenu(int resourceId, String textId, boolean isShow, View.OnClickListener clickListener) {
        View tmpMenu = getRightMenu();
        if (tmpMenu == null || !(tmpMenu instanceof TextView)) {
            return null;
        }
        TextView rightMenu = (TextView) tmpMenu;
        if (!TextUtils.isEmpty(textId)) {
            rightMenu.setText(textId);
        } else {
            rightMenu.setText("");
        }

        if (resourceId != 0) {
            Drawable img = getResources().getDrawable(resourceId);
            img.setBounds(0, 0, img.getMinimumWidth(), img.getMinimumHeight());
            rightMenu.setCompoundDrawables(null, null, img, null);
        } else {
            rightMenu.setCompoundDrawables(null, null, null, null);
        }

        if (isShow) {
            rightMenu.setVisibility(View.VISIBLE);
        } else {
            rightMenu.setVisibility(View.GONE);
        }
        if (clickListener != null) {
            rightMenu.setOnClickListener(clickListener);
        }
        return rightMenu;
    }

    /**
     * @param resourceId
     * @param textId
     * @param isShow
     */
    protected TextView showLeftMenu(int resourceId, String textId, boolean isShow, View.OnClickListener clickListener) {
        View tmpMenu = getLeftMenu();
        if (tmpMenu == null || !(tmpMenu instanceof TextView)) {
            return null;
        }
        TextView leftMenu = (TextView) tmpMenu;
        if (!TextUtils.isEmpty(textId)) {
            leftMenu.setText(textId);
        } else {
            leftMenu.setText("");
        }

        if (resourceId != 0) {
            Drawable img = getResources().getDrawable(resourceId);
            img.setBounds(0, 0, img.getMinimumWidth(), img.getMinimumHeight());
            leftMenu.setCompoundDrawables(img, null, null, null);
        } else {
            leftMenu.setCompoundDrawables(null, null, null, null);
        }

        if (isShow) {
            leftMenu.setVisibility(View.VISIBLE);
        } else {
            leftMenu.setVisibility(View.GONE);
        }
        if (clickListener != null) {
            leftMenu.setOnClickListener(clickListener);
        }
        return leftMenu;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    /**
     * 导航栏左边点击事件
     *
     * @param view
     */
    protected void onLeftMenuClick(View view) {
        onBackPressed();
    }

    /**
     * 导航栏右边点击事件
     *
     * @param view
     */
    protected void onRightMenuClick(View view) {

    }

    public void setTitle(CharSequence title, boolean isShowTitle) {
        View tmpMenu = getTitleView();
        if (tmpMenu == null || !(tmpMenu instanceof TextView)) {
            return;
        }
        TextView tvTitle = (TextView) tmpMenu;
        tvTitle.setText(title);
        if (isShowTitle) {
            tvTitle.setVisibility(View.VISIBLE);
        } else {
            tvTitle.setVisibility(View.GONE);
        }
    }

    public void setTitle(CharSequence title) {
        setTitle(title, true);
    }

    // 头部设置头像
    public SobotRCImageView getAvatarImageView(boolean isShowAvatar) {
        SobotRCImageView tmpAvatart = getAvatarView();
        if (tmpAvatart != null) {
            if (isShowAvatar) {
                tmpAvatart.setVisibility(View.VISIBLE);
                tmpAvatart.setRoundAsCircle(true);
                tmpAvatart.setStrokeColor(getResources().getColor(R.color.sobot_color_title_bar_avatar_line));
            } else {
                tmpAvatart.setVisibility(View.GONE);
            }
        }
        return tmpAvatart;
    }

    public void setTitle(int title) {
        getAvatarView().setVisibility(View.GONE);
        View tmpMenu = getTitleView();
        if (tmpMenu == null || !(tmpMenu instanceof TextView)) {
            return;
        }
        TextView tvTitle = (TextView) tmpMenu;
        tvTitle.setVisibility(View.VISIBLE);
        tvTitle.setText(title);
    }

    //返回布局id
    protected abstract int getContentViewResId();

    protected void initBundleData(Bundle savedInstanceState) {
    }

    protected abstract void initView() throws InterruptedException;

    protected abstract void initData();

    public int getResId(String name) {
        return SobotResourceUtils.getIdByName(getSobotBaseContext(), "id", name);
    }

    public int getResDrawableId(String name) {
        return SobotResourceUtils.getIdByName(getSobotBaseContext(), "drawable", name);
    }

    public int getResLayoutId(String name) {
        return SobotResourceUtils.getIdByName(getSobotBaseContext(), "layout", name);
    }

    public int getResColorId(String name) {
        return SobotResourceUtils.getIdByName(getSobotBaseContext(), "color", name);
    }

    public int getResStringId(String name) {
        return SobotResourceUtils.getIdByName(getSobotBaseContext(), "string", name);
    }

    public String getResString(String name) {
        return SobotResourceUtils.getResString(getSobotBaseContext(), name);
    }

    public int getResColor(String name) {
        int resColorId = getResColorId(name);
        if (resColorId != 0) {
            return getResources().getColor(resColorId);
        }
        return 0;
    }


    public SobotBaseActivity getSobotBaseActivity() {
        return this;
    }

    public Context getSobotBaseContext() {
        return this;
    }

    //判断相机是否可用
    public static boolean isCameraCanUse() {
        boolean canUse = false;
        Camera mCamera = null;

        try {
            mCamera = Camera.open(0);
            Camera.Parameters mParameters = mCamera.getParameters();
            mCamera.setParameters(mParameters);
        } catch (Exception e) {
            e.printStackTrace();
            canUse = false;
        }

        if (mCamera != null) {
            mCamera.release();
            canUse = true;
        }
        return canUse;
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        int currentNightMode = newConfig.uiMode & Configuration.UI_MODE_NIGHT_MASK;
        if (initMode != currentNightMode) {
            initMode = currentNightMode;
            recreate();
        }
    }

    /**
     * 是否是全屏
     *
     * @return
     */
    protected boolean isFullScreen() {
        return (getWindow().getAttributes().flags & WindowManager.LayoutParams.FLAG_FULLSCREEN) == WindowManager.LayoutParams.FLAG_FULLSCREEN;
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case SobotBaseConstant.REQUEST_CODE_PICTURE:
                try {
                    for (int i = 0; i < grantResults.length; i++) {
                        //判断权限的结果，如果有被拒绝，就return
                        if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                            String permissionTitle = getResources().getString(R.string.sobot_no_permission_text);
                            if (permissions[i] != null && permissions[i].equals(Manifest.permission.READ_EXTERNAL_STORAGE)) {
                                permissionTitle = getResources().getString(R.string.sobot_no_write_external_storage_permission);
                                if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE) && !SobotWidgetApi.getSwitchMarkStatus(SobotMarkConfig.SHOW_PERMISSION_TIPS_POP)) {
                                    SobotToastUtil.showCustomLongToast(this, SobotSystemUtils.getAppName(this) + getResources().getString(R.string.sobot_want_use_your) + getResources().getString(R.string.sobot_memory_card) + " , " + getResources().getString(R.string.sobot_memory_card_yongtu));
                                } else {
                                    //调用权限失败
                                    if (permissionListener != null) {
                                        permissionListener.onPermissionErrorListener(this, permissionTitle);
                                    }
                                }
                            } else if (permissions[i] != null && permissions[i].equals(Manifest.permission.RECORD_AUDIO)) {
                                permissionTitle = getResources().getString(R.string.sobot_no_record_audio_permission);
                                if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.RECORD_AUDIO) && !SobotWidgetApi.getSwitchMarkStatus(SobotMarkConfig.SHOW_PERMISSION_TIPS_POP)) {
                                    SobotToastUtil.showCustomLongToast(this, SobotSystemUtils.getAppName(this) + getResources().getString(R.string.sobot_want_use_your) + getResources().getString(R.string.sobot_microphone) + " , " + getString(R.string.sobot_microphone_yongtu));
                                } else {
                                    //调用权限失败
                                    if (permissionListener != null) {
                                        permissionListener.onPermissionErrorListener(this, permissionTitle);
                                    }
                                }
                            } else if (permissions[i] != null && permissions[i].equals(Manifest.permission.CAMERA)) {
                                permissionTitle = getResources().getString(R.string.sobot_no_camera_permission);
                                if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA) && !SobotWidgetApi.getSwitchMarkStatus(SobotMarkConfig.SHOW_PERMISSION_TIPS_POP)) {
                                    SobotToastUtil.showCustomLongToast(this, SobotSystemUtils.getAppName(this) + getResources().getString(R.string.sobot_want_use_your) + getString(R.string.sobot_camera) + " , " + getString(R.string.sobot_camera_yongtu));
                                } else {
                                    //调用权限失败
                                    if (permissionListener != null) {
                                        permissionListener.onPermissionErrorListener(this, permissionTitle);
                                    }
                                }
                            } else if (permissions[i] != null && permissions[i].equals(Manifest.permission.READ_MEDIA_IMAGES)) {
                                permissionTitle = getResources().getString(R.string.sobot_no_write_external_storage_permission);
                                if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_MEDIA_IMAGES) && !SobotWidgetApi.getSwitchMarkStatus(SobotMarkConfig.SHOW_PERMISSION_TIPS_POP)) {
                                    SobotToastUtil.showCustomLongToast(this, SobotSystemUtils.getAppName(this) + getResources().getString(R.string.sobot_want_use_your) + getString(R.string.sobot_memory_card) + " , " + getString(R.string.sobot_memory_card_yongtu));
                                } else {
                                    //调用权限失败
                                    if (permissionListener != null) {
                                        permissionListener.onPermissionErrorListener(getSobotBaseActivity(), permissionTitle);
                                    }
                                }
                            } else if (permissions[i] != null && permissions[i].equals(Manifest.permission.READ_MEDIA_VIDEO)) {
                                permissionTitle = getResources().getString(R.string.sobot_no_write_external_storage_permission);
                                if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_MEDIA_VIDEO) && !SobotWidgetApi.getSwitchMarkStatus(SobotMarkConfig.SHOW_PERMISSION_TIPS_POP)) {
                                    SobotToastUtil.showCustomLongToast(this, SobotSystemUtils.getAppName(this) + getResources().getString(R.string.sobot_want_use_your) + getString(R.string.sobot_memory_card) + " , " + getString(R.string.sobot_memory_card_yongtu));
                                } else {
                                    //调用权限失败
                                    if (permissionListener != null) {
                                        permissionListener.onPermissionErrorListener(getSobotBaseActivity(), permissionTitle);
                                    }
                                }
                            } else if (permissions[i] != null && permissions[i].equals(Manifest.permission.READ_MEDIA_AUDIO)) {
                                permissionTitle = getResources().getString(R.string.sobot_no_write_external_storage_permission);
                                if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_MEDIA_AUDIO) && !SobotWidgetApi.getSwitchMarkStatus(SobotMarkConfig.SHOW_PERMISSION_TIPS_POP)) {
                                    SobotToastUtil.showCustomLongToast(this, SobotSystemUtils.getAppName(this) + getResources().getString(R.string.sobot_want_use_your) + getString(R.string.sobot_memory_card) + " , " + getString(R.string.sobot_memory_card_yongtu));
                                } else {
                                    //调用权限失败
                                    if (permissionListener != null) {
                                        permissionListener.onPermissionErrorListener(getSobotBaseActivity(), permissionTitle);
                                    }
                                }
                            }
                            return;
                        }
                    }
                    if (permissionListener != null) {
                        permissionListener.onPermissionSuccessListener();
                    }
                } catch (Exception e) {
//                    e.printStackTrace();
                }
                break;
        }
    }

    /**
     * 检查存储权限
     *
     * @param checkType 0：图片权限 1：视频权限，2：音频权限，3，所有细分的权限， android 13 使用
     * @return true, 已经获取权限;false,没有权限,尝试获取
     */
    protected boolean checkStoragePermission(int checkType) {
        //如果是升级Android13之前就已经具有读写SDK的权限，那么升级到13之后，自己具有上述三个权限。
        //如果是升级Android13之后新装的应用，并且targetSDK小于33，则申请READ_EXTERNAL_STORAGE权限时，会自动转化为对上述三个权限的申请，权限申请框只一个
        //如果是升级Android13之后新装的应用，并且targetSDK大于等于33，则申请READ_EXTERNAL_STORAGE权限时会自动拒绝。
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (checkType == 0) {
                if (ContextCompat.checkSelfPermission(getSobotBaseActivity(), Manifest.permission.READ_MEDIA_IMAGES)
                        != PackageManager.PERMISSION_GRANTED) {
                    //申请图片权限
                    this.requestPermissions(new String[]{Manifest.permission.READ_MEDIA_IMAGES}, SobotBaseConstant.REQUEST_CODE_PICTURE);
                    return false;
                }
            } else if (checkType == 1) {
                if (ContextCompat.checkSelfPermission(getSobotBaseActivity(), Manifest.permission.READ_MEDIA_VIDEO)
                        != PackageManager.PERMISSION_GRANTED) {
                    //申请视频权限
                    this.requestPermissions(new String[]{Manifest.permission.READ_MEDIA_VIDEO}, SobotBaseConstant.REQUEST_CODE_PICTURE);
                    return false;
                }
            } else if (checkType == 2) {
                if (ContextCompat.checkSelfPermission(getSobotBaseActivity(), Manifest.permission.READ_MEDIA_AUDIO)
                        != PackageManager.PERMISSION_GRANTED) {
                    //申请音频权限
                    this.requestPermissions(new String[]{Manifest.permission.READ_MEDIA_AUDIO}, SobotBaseConstant.REQUEST_CODE_PICTURE);
                    return false;
                }
            } else {
                if (ContextCompat.checkSelfPermission(getSobotBaseActivity(), Manifest.permission.READ_MEDIA_IMAGES)
                        != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(getSobotBaseActivity(), Manifest.permission.READ_MEDIA_VIDEO)
                        != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(getSobotBaseActivity(), Manifest.permission.READ_MEDIA_AUDIO)
                        != PackageManager.PERMISSION_GRANTED) {
                    //申请：图片权限 视频权限 音频权限
                    this.requestPermissions(new String[]{Manifest.permission.READ_MEDIA_AUDIO, Manifest.permission.READ_MEDIA_IMAGES, Manifest.permission.READ_MEDIA_VIDEO}, SobotBaseConstant.REQUEST_CODE_PICTURE);
                    return false;
                }
            }
        } else if (Build.VERSION.SDK_INT >= 23 && SobotSystemUtils.getTargetSdkVersion(getSobotBaseActivity().getApplicationContext()) >= 23) {
            if (ContextCompat.checkSelfPermission(getSobotBaseActivity(), Manifest.permission.READ_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED) {
                //申请READ_EXTERNAL_STORAGE权限
                this.requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, SobotBaseConstant.REQUEST_CODE_PICTURE);
                return false;
            }
        }
        return true;
    }

    /**
     * 判断是否有存储卡权限
     *
     * @param checkPermissionType 0：图片权限 1：视频权限，2：音频权限，3，所有细分的权限， android 13 使用
     * @return true, 已经获取权限;false,没有权限
     */
    protected boolean isHasStoragePermission(int checkPermissionType) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (checkPermissionType == 0) {
                if (ContextCompat.checkSelfPermission(getSobotBaseActivity(), Manifest.permission.READ_MEDIA_IMAGES)
                        != PackageManager.PERMISSION_GRANTED) {
                    return false;
                }
            } else if (checkPermissionType == 1) {
                if (ContextCompat.checkSelfPermission(getSobotBaseActivity(), Manifest.permission.READ_MEDIA_VIDEO)
                        != PackageManager.PERMISSION_GRANTED) {
                    return false;
                }
            } else if (checkPermissionType == 2) {
                if (ContextCompat.checkSelfPermission(getSobotBaseActivity(), Manifest.permission.READ_MEDIA_AUDIO)
                        != PackageManager.PERMISSION_GRANTED) {
                    return false;
                }
            } else {
                if (ContextCompat.checkSelfPermission(getSobotBaseActivity(), Manifest.permission.READ_MEDIA_IMAGES)
                        != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(getSobotBaseActivity(), Manifest.permission.READ_MEDIA_VIDEO)
                        != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(getSobotBaseActivity(), Manifest.permission.READ_MEDIA_AUDIO)
                        != PackageManager.PERMISSION_GRANTED) {
                    return false;
                }
            }
        } else if (Build.VERSION.SDK_INT >= 23 && SobotSystemUtils.getTargetSdkVersion(getSobotBaseActivity().getApplicationContext()) >= 23) {
            if (ContextCompat.checkSelfPermission(getSobotBaseActivity(), Manifest.permission.READ_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    /**
     * 检查录音权限
     *
     * @return true, 已经获取权限;false,没有权限,尝试获取
     */
    protected boolean checkAudioPermission() {
        if (Build.VERSION.SDK_INT >= 23 && SobotSystemUtils.getTargetSdkVersion(getSobotBaseActivity().getApplicationContext()) >= 23) {
            if (ContextCompat.checkSelfPermission(getSobotBaseActivity(), Manifest.permission.RECORD_AUDIO)
                    != PackageManager.PERMISSION_GRANTED) {
                this.requestPermissions(new String[]{Manifest.permission.RECORD_AUDIO},
                        SobotBaseConstant.REQUEST_CODE_PICTURE);
                return false;
            }
        }
        return true;
    }

    /**
     * 判断是否有录音权限
     *
     * @return true, 已经获取权限;false,没有权限
     */
    protected boolean isHasAudioPermission() {
        if (Build.VERSION.SDK_INT >= 23 && SobotSystemUtils.getTargetSdkVersion(getSobotBaseActivity().getApplicationContext()) >= 23) {
            if (ContextCompat.checkSelfPermission(getSobotBaseActivity(), Manifest.permission.RECORD_AUDIO)
                    != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    /**
     * 检查相机权限
     *
     * @return true, 已经获取权限;false,没有权限,尝试获取
     */
    protected boolean checkCameraPermission() {
        if (Build.VERSION.SDK_INT >= 23 && SobotSystemUtils.getTargetSdkVersion(getSobotBaseActivity().getApplicationContext()) >= 23) {
            if (ContextCompat.checkSelfPermission(getSobotBaseActivity(), Manifest.permission.CAMERA)
                    != PackageManager.PERMISSION_GRANTED) {
                this.requestPermissions(new String[]{Manifest.permission.CAMERA}
                        , SobotBaseConstant.REQUEST_CODE_PICTURE);
                return false;
            }
        }
        return true;
    }

    /**
     * 判断是否有相机权限
     *
     * @return true, 已经获取权限;false,没有权限
     */
    protected boolean isHasCameraPermission() {
        if (Build.VERSION.SDK_INT >= 23 && SobotSystemUtils.getTargetSdkVersion(getSobotBaseActivity().getApplicationContext()) >= 23) {
            if (ContextCompat.checkSelfPermission(getSobotBaseActivity(), Manifest.permission.CAMERA)
                    != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }


    /**
     * 从图库获取图片
     */
    public void selectPicFromLocal() {
        permissionListener = new SobotPermissionListenerImpl() {
            @Override
            public void onPermissionSuccessListener() {
                SobotWidgetUtils.openSelectPic(getSobotBaseActivity());
            }
        };
        if (checkIsShowPermissionPop(getString(R.string.sobot_memory_card), getString(R.string.sobot_memory_card_yongtu), 1, 0)) {
            return;
        }
        if (!checkStoragePermission(0)) {
            return;
        }
        SobotWidgetUtils.openSelectPic(getSobotBaseActivity());
    }

    /**
     * 判断是否有存储卡权限
     *
     * @param type                1 存储卡;2 麦克风;3 相机;
     * @param checkPermissionType 0：图片权限 1：视频权限，2：音频权限，3，所有细分的权限， android 13 使用
     * @return true, 已经获取权限;false,没有权限
     */
    protected boolean isHasPermission(int type, int checkPermissionType) {
        if (type == 1) {
            return isHasStoragePermission(checkPermissionType);
        } else if (type == 2) {
            return isHasAudioPermission();
        } else if (type == 3) {
            return isHasCameraPermission();
        }
        return true;
    }

    /**
     * 检测是否需要弹出权限用途提示框pop,如果弹出，则拦截接下来的处理逻辑，自己处理
     *
     * @param title
     * @param content
     * @param type
     * @param checkPermissionType 0：图片权限 1：视频权限，2：音频权限，3，所有细分的权限， android 13 使用
     * @return
     */
    public boolean checkIsShowPermissionPop(String title, String content, final int type, final int checkPermissionType) {
        if (SobotWidgetApi.getSwitchMarkStatus(SobotMarkConfig.SHOW_PERMISSION_TIPS_POP)) {
            if (!isHasPermission(type, checkPermissionType)) {
                SobotPermissionTipDialog dialog = new SobotPermissionTipDialog(getSobotBaseActivity(), title, content, new SobotPermissionTipDialog.ClickViewListener() {
                    @Override
                    public void clickRightView(Context context, SobotPermissionTipDialog dialog) {
                        dialog.dismiss();
                        if (type == 1) {
                            if (!checkStoragePermission(checkPermissionType)) {
                                return;
                            }
                        } else if (type == 2) {
                            if (!checkAudioPermission()) {
                                return;
                            }
                        } else if (type == 3) {
                            if (!checkCameraPermission()) {
                                return;
                            }
                        }
                    }

                    @Override
                    public void clickLeftView(Context context, SobotPermissionTipDialog dialog) {
                        dialog.dismiss();
                    }
                });
                dialog.show();
                return true;
            }
        }
        return false;
    }

    /**
     * 从图库获取视频
     */
    public void selectVedioFromLocal() {
        permissionListener = new SobotPermissionListenerImpl() {
            @Override
            public void onPermissionSuccessListener() {
                SobotWidgetUtils.openSelectVedio(getSobotBaseActivity());
            }
        };
        if (checkIsShowPermissionPop(getString(R.string.sobot_memory_card), getString(R.string.sobot_memory_card_yongtu), 1, 1)) {
            return;
        }
        if (!checkStoragePermission(1)) {
            return;
        }
        SobotWidgetUtils.openSelectVedio(getSobotBaseActivity());
    }

    /**
     * 打开相机
     */
    public void openCamera() {
        openCamera("", "");
    }

    /**
     * 打开相机
     *
     * @param title   权限用途提示弹窗开启后，弹窗的的标题
     * @param content 权限用途提示弹窗开启后，弹窗的内容
     */
    public void openCamera(String title, String content) {
        cameraFile = null;
        permissionListener = null;
        permissionListener = new SobotPermissionListenerImpl() {
            @Override
            public void onPermissionSuccessListener() {
                if (isCameraCanUse()) {
                    cameraFile = SobotWidgetUtils.openCamera(getSobotBaseActivity());
                }
            }
        };
        if (checkIsShowPermissionPop(TextUtils.isEmpty(title) ? getResources().getString(R.string.sobot_camera) : title, TextUtils.isEmpty(content) ? getResources().getString(R.string.sobot_camera_yongtu) : content, 3, 4)) {
            return;
        }
        if (!checkCameraPermission()) {
            return;
        }
        if (isCameraCanUse()) {
            cameraFile = SobotWidgetUtils.openCamera(getSobotBaseActivity());
        }
    }
}