package com.uiuipad.appstore.activity;

import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.flyco.tablayout.SlidingTabLayout;
import com.hjq.permissions.OnPermission;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.uiuipad.appstore.R;
import com.uiuipad.appstore.base.BaseActivity;
import com.uiuipad.appstore.fragment.featured.FeaturedFragment;
import com.uiuipad.appstore.service.main.MainService;
import com.uiuipad.appstore.utils.JGYUtils;
import com.uiuipad.appstore.utils.ToastUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.rxjava3.annotations.NonNull;

public class MainActivity extends BaseActivity {
    private static final String TAG = MainActivity.class.getSimpleName();

    @BindView(R.id.search_layout)
    RelativeLayout search_layout;
    @BindView(R.id.iv_download)
    ImageView iv_download;
    @BindView(R.id.iv_appicon)
    ImageView iv_appicon;
    @BindView(R.id.main_sliding_tab_layout)
    SlidingTabLayout mSlidingTabLayout;
    @BindView(R.id.main_view_pager)
    ViewPager mViewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.e(TAG, "onCreate");
        starService();
        JGYUtils.getInstance().checkLocalExternalFiles();
    }

    /**
     * 设置布局
     */
    @Override
    public int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    public void initView() {
        ButterKnife.bind(this);
        iv_appicon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                startActivity(new Intent(MainActivity.this, AboutActivity.class));
            }
        });
        iv_download.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(MainActivity.this, ManagerAppActivity.class));
            }
        });
        search_layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(MainActivity.this, SearcherActivity.class));
            }
        });
        initTabLayout();
    }

    @Override
    public void initData() {

    }

    private void starService() {
        startService(new Intent(this, MainService.class));
    }

    private void initTabLayout() {
        final List<Fragment> fragmentList = new ArrayList<>();
        fragmentList.add(new FeaturedFragment());
//        fragmentList.add(new RankFragment());
//        fragmentList.add(new KindFragment());
//        fragmentList.add(new ManageFragment());
        mViewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                return fragmentList.get(position);
            }

            @Override
            public int getCount() {
                return fragmentList.size();
            }
        });
        mViewPager.setOffscreenPageLimit(3);
        String titles[] = new String[]{"专属应用",/* "我的分类",*/ /*"下载管理"*/};
//        mSlidingTabLayout.setViewPager(mViewPager, titles);
    }

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

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

    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        Log.e(TAG, "onConfigurationChanged");
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        Log.e(TAG, "onSaveInstanceState");
    }

    private String[] permission = new String[]{
            Permission.REQUEST_INSTALL_PACKAGES,
            Permission.READ_EXTERNAL_STORAGE,
            Permission.WRITE_EXTERNAL_STORAGE,
    };

    public void requestPermission() {
        XXPermissions.with(this)
                // 可设置被拒绝后继续申请，直到用户授权或者永久拒绝
                .constantRequest()
                // 支持请求6.0悬浮窗权限8.0请求安装权限
                //.permission(Permission.REQUEST_INSTALL_PACKAGES)
                // 不指定权限则自动获取清单中的危险权限
                .permission(permission)
                .request(new OnPermission() {

                    @Override
                    public void hasPermission(List<String> granted, boolean isAll) {
                        if (isAll) {
                            File file = new File(JGYUtils.getInstance().getDownLoadPath());
                            file.mkdirs();
                        } else {
                            ToastUtil.show("需要授予所有权限才能正常使用本程序！");
                        }
                    }

                    @Override
                    public void noPermission(List<String> denied, boolean quick) {
                        if (quick) {
                            ToastUtil.show("被永久拒绝授权，请手动授予权限！");
                            //如果是被永久拒绝就跳转到应用权限系统设置页面
                            XXPermissions.gotoPermissionSettings(MainActivity.this);
                        } else {
                            ToastUtil.show("获取权限失败");
                        }
                    }
                });
    }


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

    private long exitTime = 0;

    public void exit() {
        if ((System.currentTimeMillis() - exitTime) > 2000) {
            ToastUtil.show("再按一次退出程序");
            exitTime = System.currentTimeMillis();
        } else {
            finish();
        }
    }
}
