package com.bonait.bnframework.common.base;

import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.Uri;
import android.provider.Settings;
import android.text.InputType;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.bonait.bnframework.MainApplication;
import com.bonait.bnframework.R;
import com.bonait.bnframework.common.constant.ConfigName;
import com.bonait.bnframework.common.constant.Constants;
import com.bonait.bnframework.common.db.QueryDB;
import com.bonait.bnframework.common.db.mode.BPA_USER;
import com.bonait.bnframework.common.filepicker.PickerManager;
import com.bonait.bnframework.common.filepicker.adapter.FilePickerShowAdapter;
import com.bonait.bnframework.common.filepicker.adapter.OnFileItemClickListener;
import com.bonait.bnframework.common.filepicker.util.OpenFile;
import com.bonait.bnframework.common.helper.MediaPlayerHelper;
import com.bonait.bnframework.common.utils.AlertDialogUtils;
import com.bonait.bnframework.common.utils.ToastUtils;
import com.qmuiteam.qmui.arch.QMUIFragment;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.dialog.QMUIDialogAction;

import java.util.List;

import pub.devrel.easypermissions.EasyPermissions;

/**
 * Created by LY on 2019/3/25.
 */
public abstract class BaseFragment extends QMUIFragment implements EasyPermissions.PermissionCallbacks {

    public BaseFragment() {

    }

    @Override
    protected int backViewInitOffset() {
        return QMUIDisplayHelper.dp2px(requireContext(), 100);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == Constants.APP_SETTING_DIALOG_REQUEST_CODE) {
            //在这儿，你可以再对权限进行检查，从而给出提示，或进行下一步操作
            checkPermission();
            ToastUtils.info("从设置中返回");
        }
    }

    //----------------以下是请求权限base，子类activity只需要重写checkPermission()方法即可----------------//

    /**
     * 检查权限，子类要申请权限，需要重写该方法
     * */
    public void checkPermission() {
    }


    /**
     * 跳转界面
     */
    public void skipToActivity(Class da) {
        Context context=this.getContext();
        if(ConfigName.getInstance().user.name.equals("admin")
                || ConfigName.getInstance().user.account.equals("admin"))
        {
            Intent intent = new Intent(context, da);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }else
        {
            if(da.getName().equals("com.bonait.bnframework.modules.home.fragment.from.OrderListActivity")
                    || da.getName().equals("com.bonait.bnframework.modules.home.fragment.from.SalesStatisticsActivity")
            )
            {
                Intent intent = new Intent(context, da);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
                return;
            }

            // 跳转到登录页面
            final QMUIDialog.EditTextDialogBuilder builder2 = new QMUIDialog.EditTextDialogBuilder(context);
            builder2.setTitle("权限验证")
                    .setPlaceholder("在此输入权限密码")
                    .setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD)
                    .addAction("取消", new QMUIDialogAction.ActionListener() {
                        @Override
                        public void onClick(QMUIDialog dialog, int index) {
                            dialog.dismiss();
                        }
                    })
                    .addAction("确定", new QMUIDialogAction.ActionListener() {
                        @Override
                        public void onClick(QMUIDialog dialog, int index) {
                            CharSequence s = builder2.getEditText().getText();
                            if (s != null && s.length() > 0)
                            {
                                if(s.toString().equals(ConfigName.getInstance().user.pass))
                                {
                                    Intent intent = new Intent(context, da);
                                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                    startActivity(intent);
                                    dialog.dismiss();
                                }else
                                {
                                    ToastUtils.warning("权限密码不正确！");
                                }

                            }else
                            {
                                ToastUtils.warning("权限密码不能为空！");
                            }

                        }
                    })
                    .show();
        }
    }

    FragmentManager fragmentManager;
    FragmentTransaction fragmentTransaction;

    /**
     * 显示流
     * @param fragment
     */
    public void ShowFragment(Fragment fragment)
    {
        // TODO Auto-generated method stub
        /*在activity对应java类中通过getFragmentManager()
         *获得FragmentManager，用于管理ViewGrop中的fragment
         * */
        fragmentManager=getFragmentManager();
        /*FragmentManager要管理fragment（添加，替换以及其他的执行动作）
         *的一系列的事务变化，需要通过fragmentTransaction来操作执行
         */
        fragmentTransaction = fragmentManager.beginTransaction();
        //实例化要管理的fragment
        //通过添加（事务处理的方式）将fragment加到对应的布局中
        fragmentTransaction.replace(R.id.viewpager_jiaoyan, fragment);
        //事务处理完需要提交
        fragmentTransaction.commit();
    }

    /**
     * 播放
     * @param resid
     */
    public void Speak(int resid)
    {
        MediaPlayerHelper.getInstance().PlaySound(resid);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // 将结果转发给EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {

        //若是在权限弹窗中，用户勾选了'NEVER ASK AGAIN.'或者'不再提示'，且拒绝权限。
        //跳转到设置界面去，让用户手动开启。
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {

            String title = "需要权限，才能正常使用：";
            String message = "如果没有请求的权限，此应用可能无法正常工作。请打开应用设置以修改应用权限。";
            AlertDialogUtils.showDialog(getContext(), title, message, "去设置", new QMUIDialogAction.ActionListener() {
                @Override
                public void onClick(QMUIDialog dialog, int index) {
                    Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                    Uri uri = Uri.fromParts("package", MainApplication.getContext().getPackageName(), null);
                    intent.setData(uri);
                    startActivityForResult(intent, Constants.APP_SETTING_DIALOG_REQUEST_CODE);
                    dialog.dismiss();
                }
            });
        }
    }

}
