package com.unis.sxzcl.ui;

import android.Manifest;
import android.os.Bundle;
import android.os.Handler;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.unis.model.UserModel;
import com.unis.model.bean.user.UserBean;
import com.unis.sxzcl.base.FactoryActivity;
import com.unis.sxzcl.ui.home.MainActivity;
import com.unis.sxzcl.ui.login.LoginFragment;
import com.xyxsbj.mylibrary.tool.ActivityTool;
import com.xyxsbj.mylibrary.tool.LogTool;
import com.xyxsbj.mylibrary.tool.PermissionTool;

import java.util.Arrays;

/**
 * 包名: com.unis.sxzcl.ui
 * 类名: WelcomeActivity
 * 作用描述: 启动页
 * 创建人: mQ
 * 创建时间: 2020/11/9 14:09
 * 更新人:
 * 更新时间: 2020/11/9 14:09
 * 更新说明:
 * 版本号: 1.0
 */
public class WelcomeActivity extends AppCompatActivity {

    private PermissionTool mPermissionTool;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mPermissionTool = PermissionTool.get().init(
                new String[]{
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE});
        new Handler().postDelayed(this::permission, 1 * 1000);
    }

    private void permission() {
        //系统权限是否同意
        if (mPermissionTool.checkPermissionAll(this)) {
            next();
        } else {
            mPermissionTool.requestPermission(this);
        }
    }

    private void next() {
        UserBean user = UserModel.get().getUser();
        if (user == null) {
            // 无用户信息 跳转登录页
            FactoryActivity.startPage(WelcomeActivity.this, LoginFragment.class);
        } else {
            // 有用户信息 跳转首页
            ActivityTool.startActivity(this, MainActivity.class);
        }
        finish();
    }

    /**
     * 权限申请结果回调
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        mPermissionTool.onRequestPermissionsResult(requestCode, permissions, grantResults, new PermissionTool.PermissionCallBack() {
            @Override
            public void onGrantedPermissionAll() {
                //权限全部通过
                next();
            }
            @Override
            public void onDeniedPermission(String[] deniedPermissions) {
                LogTool.i("onDeniedPermission: 权限拒绝 " + Arrays.toString(deniedPermissions));
                //权限拒绝 重新申请
                if (mPermissionTool.getIsRequestUI(WelcomeActivity.this, deniedPermissions)) {
                    mPermissionTool.requestPermission(WelcomeActivity.this);
                } else {
                    mPermissionTool.showSettingDialog(WelcomeActivity.this, true);
                }
            }

        });
    }

}
