package com.sobot.widget.ui.base;

import android.content.Context;
import android.content.pm.ActivityInfo;
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 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.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.fragment.app.FragmentActivity;

import com.sobot.utils.SobotSharedPreferencesUtil;
import com.sobot.widget.R;
import com.sobot.widget.SobotWidgetApi;
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.statusbar.SobotStatusBarUtils;
import com.sobot.widget.ui.utils.SobotResourceUtils;

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(R.id.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 = (Math.min(rect.right, 110)) + 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(getSobotBaseActivity()).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 ImageView getRightIcon() {
        return findViewById(getResId("call_icon"));
    }

    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();

    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;
    }
}